1/* ------------------------------------------------------------------ */
2/* Decimal Number arithmetic module                                   */
3/* ------------------------------------------------------------------ */
4/* Copyright (c) IBM Corporation, 2000-2010.  All rights reserved.    */
5/*                                                                    */
6/* This software is made available under the terms of the             */
7/* ICU License -- ICU 1.8.1 and later.                                */
8/*                                                                    */
9/* The description and User's Guide ("The decNumber C Library") for   */
10/* this software is called decNumber.pdf.  This document is           */
11/* available, together with arithmetic and format specifications,     */
12/* testcases, and Web links, on the General Decimal Arithmetic page.  */
13/*                                                                    */
14/* Please send comments, suggestions, and corrections to the author:  */
15/*   mfc@uk.ibm.com                                                   */
16/*   Mike Cowlishaw, IBM Fellow                                       */
17/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */
18/* ------------------------------------------------------------------ */
19
20/* Modified version, for use from within ICU.
21 *    Renamed public functions, to avoid an unwanted export of the
22 *    standard names from the ICU library.
23 *
24 *    Use ICU's uprv_malloc() and uprv_free()
25 *
26 *    Revert comment syntax to plain C
27 *
28 *    Remove a few compiler warnings.
29 */
30
31/* This module comprises the routines for arbitrary-precision General */
32/* Decimal Arithmetic as defined in the specification which may be    */
33/* found on the General Decimal Arithmetic pages.  It implements both */
34/* the full ('extended') arithmetic and the simpler ('subset')        */
35/* arithmetic.                                                        */
36/*                                                                    */
37/* Usage notes:                                                       */
38/*                                                                    */
39/* 1. This code is ANSI C89 except:                                   */
40/*                                                                    */
41/*    a) C99 line comments (double forward slash) are used.  (Most C  */
42/*       compilers accept these.  If yours does not, a simple script  */
43/*       can be used to convert them to ANSI C comments.)             */
44/*                                                                    */
45/*    b) Types from C99 stdint.h are used.  If you do not have this   */
46/*       header file, see the User's Guide section of the decNumber   */
47/*       documentation; this lists the necessary definitions.         */
48/*                                                                    */
49/*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
50/*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
51/*       and DECDPUN<=4 (see documentation).                          */
52/*                                                                    */
53/*    The code also conforms to C99 restrictions; in particular,      */
54/*    strict aliasing rules are observed.                             */
55/*                                                                    */
56/* 2. The decNumber format which this library uses is optimized for   */
57/*    efficient processing of relatively short numbers; in particular */
58/*    it allows the use of fixed sized structures and minimizes copy  */
59/*    and move operations.  It does, however, support arbitrary       */
60/*    precision (up to 999,999,999 digits) and arbitrary exponent     */
61/*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
62/*    range -999,999,999 through 0).  Mathematical functions (for     */
63/*    example decNumberExp) as identified below are restricted more   */
64/*    tightly: digits, emax, and -emin in the context must be <=      */
65/*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
66/*    these bounds.                                                   */
67/*                                                                    */
68/* 3. Logical functions are further restricted; their operands must   */
69/*    be finite, positive, have an exponent of zero, and all digits   */
70/*    must be either 0 or 1.  The result will only contain digits     */
71/*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
72/*                                                                    */
73/* 4. Operands to operator functions are never modified unless they   */
74/*    are also specified to be the result number (which is always     */
75/*    permitted).  Other than that case, operands must not overlap.   */
76/*                                                                    */
77/* 5. Error handling: the type of the error is ORed into the status   */
78/*    flags in the current context (decContext structure).  The       */
79/*    SIGFPE signal is then raised if the corresponding trap-enabler  */
80/*    flag in the decContext is set (is 1).                           */
81/*                                                                    */
82/*    It is the responsibility of the caller to clear the status      */
83/*    flags as required.                                              */
84/*                                                                    */
85/*    The result of any routine which returns a number will always    */
86/*    be a valid number (which may be a special value, such as an     */
87/*    Infinity or NaN).                                               */
88/*                                                                    */
89/* 6. The decNumber format is not an exchangeable concrete            */
90/*    representation as it comprises fields which may be machine-     */
91/*    dependent (packed or unpacked, or special length, for example). */
92/*    Canonical conversions to and from strings are provided; other   */
93/*    conversions are available in separate modules.                  */
94/*                                                                    */
95/* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
96/*    to 1 for extended operand checking (including NULL operands).   */
97/*    Results are undefined if a badly-formed structure (or a NULL    */
98/*    pointer to a structure) is provided, though with DECCHECK       */
99/*    enabled the operator routines are protected against exceptions. */
100/*    (Except if the result pointer is NULL, which is unrecoverable.) */
101/*                                                                    */
102/*    However, the routines will never cause exceptions if they are   */
103/*    given well-formed operands, even if the value of the operands   */
104/*    is inappropriate for the operation and DECCHECK is not set.     */
105/*    (Except for SIGFPE, as and where documented.)                   */
106/*                                                                    */
107/* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
108/* ------------------------------------------------------------------ */
109/* Implementation notes for maintenance of this module:               */
110/*                                                                    */
111/* 1. Storage leak protection:  Routines which use malloc are not     */
112/*    permitted to use return for fastpath or error exits (i.e.,      */
113/*    they follow strict structured programming conventions).         */
114/*    Instead they have a do{}while(0); construct surrounding the     */
115/*    code which is protected -- break may be used to exit this.      */
116/*    Other routines can safely use the return statement inline.      */
117/*                                                                    */
118/*    Storage leak accounting can be enabled using DECALLOC.          */
119/*                                                                    */
120/* 2. All loops use the for(;;) construct.  Any do construct does     */
121/*    not loop; it is for allocation protection as just described.    */
122/*                                                                    */
123/* 3. Setting status in the context must always be the very last      */
124/*    action in a routine, as non-0 status may raise a trap and hence */
125/*    the call to set status may not return (if the handler uses long */
126/*    jump).  Therefore all cleanup must be done first.  In general,  */
127/*    to achieve this status is accumulated and is only applied just  */
128/*    before return by calling decContextSetStatus (via decStatus).   */
129/*                                                                    */
130/*    Routines which allocate storage cannot, in general, use the     */
131/*    'top level' routines which could cause a non-returning          */
132/*    transfer of control.  The decXxxxOp routines are safe (do not   */
133/*    call decStatus even if traps are set in the context) and should */
134/*    be used instead (they are also a little faster).                */
135/*                                                                    */
136/* 4. Exponent checking is minimized by allowing the exponent to      */
137/*    grow outside its limits during calculations, provided that      */
138/*    the decFinalize function is called later.  Multiplication and   */
139/*    division, and intermediate calculations in exponentiation,      */
140/*    require more careful checks because of the risk of 31-bit       */
141/*    overflow (the most negative valid exponent is -1999999997, for  */
142/*    a 999999999-digit number with adjusted exponent of -999999999). */
143/*                                                                    */
144/* 5. Rounding is deferred until finalization of results, with any    */
145/*    'off to the right' data being represented as a single digit     */
146/*    residue (in the range -1 through 9).  This avoids any double-   */
147/*    rounding when more than one shortening takes place (for         */
148/*    example, when a result is subnormal).                           */
149/*                                                                    */
150/* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
151/*    during many operations, so whole Units are handled and exact    */
152/*    accounting of digits is not needed.  The correct digits value   */
153/*    is found by decGetDigits, which accounts for leading zeros.     */
154/*    This must be called before any rounding if the number of digits */
155/*    is not known exactly.                                           */
156/*                                                                    */
157/* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
158/*    numbers up to four digits, using appropriate constants.  This   */
159/*    is not useful for longer numbers because overflow of 32 bits    */
160/*    would lead to 4 multiplies, which is almost as expensive as     */
161/*    a divide (unless a floating-point or 64-bit multiply is         */
162/*    assumed to be available).                                       */
163/*                                                                    */
164/* 8. Unusual abbreviations that may be used in the commentary:       */
165/*      lhs -- left hand side (operand, of an operation)              */
166/*      lsd -- least significant digit (of coefficient)               */
167/*      lsu -- least significant Unit (of coefficient)                */
168/*      msd -- most significant digit (of coefficient)                */
169/*      msi -- most significant item (in an array)                    */
170/*      msu -- most significant Unit (of coefficient)                 */
171/*      rhs -- right hand side (operand, of an operation)             */
172/*      +ve -- positive                                               */
173/*      -ve -- negative                                               */
174/*      **  -- raise to the power                                     */
175/* ------------------------------------------------------------------ */
176
177#include <stdlib.h>                /* for malloc, free, etc.  */
178/*  #include <stdio.h>   */        /* for printf [if needed]  */
179#include <string.h>                /* for strcpy  */
180#include <ctype.h>                 /* for lower  */
181#include "cmemory.h"               /* for uprv_malloc, etc., in ICU */
182#include "decNumber.h"             /* base number library  */
183#include "decNumberLocal.h"        /* decNumber local types, etc.  */
184
185/* Constants */
186/* Public lookup table used by the D2U macro  */
187const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
188
189#define DECVERB     1              /* set to 1 for verbose DECCHECK  */
190#define powers      DECPOWERS      /* old internal name  */
191
192/* Local constants  */
193#define DIVIDE      0x80           /* Divide operators  */
194#define REMAINDER   0x40           /* ..  */
195#define DIVIDEINT   0x20           /* ..  */
196#define REMNEAR     0x10           /* ..  */
197#define COMPARE     0x01           /* Compare operators  */
198#define COMPMAX     0x02           /* ..  */
199#define COMPMIN     0x03           /* ..  */
200#define COMPTOTAL   0x04           /* ..  */
201#define COMPNAN     0x05           /* .. [NaN processing]  */
202#define COMPSIG     0x06           /* .. [signaling COMPARE]  */
203#define COMPMAXMAG  0x07           /* ..  */
204#define COMPMINMAG  0x08           /* ..  */
205
206#define DEC_sNaN     0x40000000    /* local status: sNaN signal  */
207#define BADINT  (Int)0x80000000    /* most-negative Int; error indicator  */
208/* Next two indicate an integer >= 10**6, and its parity (bottom bit)  */
209#define BIGEVEN (Int)0x80000002
210#define BIGODD  (Int)0x80000003
211
212static Unit uarrone[1]={1};   /* Unit array of 1, used for incrementing  */
213
214/* Granularity-dependent code */
215#if DECDPUN<=4
216  #define eInt  Int           /* extended integer  */
217  #define ueInt uInt          /* unsigned extended integer  */
218  /* Constant multipliers for divide-by-power-of five using reciprocal  */
219  /* multiply, after removing powers of 2 by shifting, and final shift  */
220  /* of 17 [we only need up to **4]  */
221  static const uInt multies[]={131073, 26215, 5243, 1049, 210};
222  /* QUOT10 -- macro to return the quotient of unit u divided by 10**n  */
223  #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
224#else
225  /* For DECDPUN>4 non-ANSI-89 64-bit types are needed.  */
226  #if !DECUSE64
227    #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
228  #endif
229  #define eInt  Long          /* extended integer  */
230  #define ueInt uLong         /* unsigned extended integer  */
231#endif
232
233/* Local routines */
234static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
235                              decContext *, uByte, uInt *);
236static Flag        decBiStr(const char *, const char *, const char *);
237static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
238static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
239static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
240static decNumber * decCompareOp(decNumber *, const decNumber *,
241                              const decNumber *, decContext *,
242                              Flag, uInt *);
243static void        decCopyFit(decNumber *, const decNumber *, decContext *,
244                              Int *, uInt *);
245static decNumber * decDecap(decNumber *, Int);
246static decNumber * decDivideOp(decNumber *, const decNumber *,
247                              const decNumber *, decContext *, Flag, uInt *);
248static decNumber * decExpOp(decNumber *, const decNumber *,
249                              decContext *, uInt *);
250static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
251static Int         decGetDigits(Unit *, Int);
252static Int         decGetInt(const decNumber *);
253static decNumber * decLnOp(decNumber *, const decNumber *,
254                              decContext *, uInt *);
255static decNumber * decMultiplyOp(decNumber *, const decNumber *,
256                              const decNumber *, decContext *,
257                              uInt *);
258static decNumber * decNaNs(decNumber *, const decNumber *,
259                              const decNumber *, decContext *, uInt *);
260static decNumber * decQuantizeOp(decNumber *, const decNumber *,
261                              const decNumber *, decContext *, Flag,
262                              uInt *);
263static void        decReverse(Unit *, Unit *);
264static void        decSetCoeff(decNumber *, decContext *, const Unit *,
265                              Int, Int *, uInt *);
266static void        decSetMaxValue(decNumber *, decContext *);
267static void        decSetOverflow(decNumber *, decContext *, uInt *);
268static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
269static Int         decShiftToLeast(Unit *, Int, Int);
270static Int         decShiftToMost(Unit *, Int, Int);
271static void        decStatus(decNumber *, uInt, decContext *);
272static void        decToString(const decNumber *, char[], Flag);
273static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
274static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
275                              Unit *, Int);
276static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
277
278#if !DECSUBSET
279/* decFinish == decFinalize when no subset arithmetic needed */
280#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
281#else
282static void        decFinish(decNumber *, decContext *, Int *, uInt *);
283static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
284#endif
285
286/* Local macros */
287/* masked special-values bits  */
288#define SPECIALARG  (rhs->bits & DECSPECIAL)
289#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
290
291/* For use in ICU */
292#define malloc(a) uprv_malloc(a)
293#define free(a) uprv_free(a)
294
295/* Diagnostic macros, etc. */
296#if DECALLOC
297/* Handle malloc/free accounting.  If enabled, our accountable routines  */
298/* are used; otherwise the code just goes straight to the system malloc  */
299/* and free routines.  */
300#define malloc(a) decMalloc(a)
301#define free(a) decFree(a)
302#define DECFENCE 0x5a              /* corruption detector  */
303/* 'Our' malloc and free:  */
304static void *decMalloc(size_t);
305static void  decFree(void *);
306uInt decAllocBytes=0;              /* count of bytes allocated  */
307/* Note that DECALLOC code only checks for storage buffer overflow.  */
308/* To check for memory leaks, the decAllocBytes variable must be  */
309/* checked to be 0 at appropriate times (e.g., after the test  */
310/* harness completes a set of tests).  This checking may be unreliable  */
311/* if the testing is done in a multi-thread environment.  */
312#endif
313
314#if DECCHECK
315/* Optional checking routines.  Enabling these means that decNumber  */
316/* and decContext operands to operator routines are checked for  */
317/* correctness.  This roughly doubles the execution time of the  */
318/* fastest routines (and adds 600+ bytes), so should not normally be  */
319/* used in 'production'.  */
320/* decCheckInexact is used to check that inexact results have a full  */
321/* complement of digits (where appropriate -- this is not the case  */
322/* for Quantize, for example)  */
323#define DECUNRESU ((decNumber *)(void *)0xffffffff)
324#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
325#define DECUNCONT ((decContext *)(void *)(0xffffffff))
326static Flag decCheckOperands(decNumber *, const decNumber *,
327                             const decNumber *, decContext *);
328static Flag decCheckNumber(const decNumber *);
329static void decCheckInexact(const decNumber *, decContext *);
330#endif
331
332#if DECTRACE || DECCHECK
333/* Optional trace/debugging routines (may or may not be used)  */
334void decNumberShow(const decNumber *);  /* displays the components of a number  */
335static void decDumpAr(char, const Unit *, Int);
336#endif
337
338/* ================================================================== */
339/* Conversions                                                        */
340/* ================================================================== */
341
342/* ------------------------------------------------------------------ */
343/* from-int32 -- conversion from Int or uInt                          */
344/*                                                                    */
345/*  dn is the decNumber to receive the integer                        */
346/*  in or uin is the integer to be converted                          */
347/*  returns dn                                                        */
348/*                                                                    */
349/* No error is possible.                                              */
350/* ------------------------------------------------------------------ */
351U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
352  uInt unsig;
353  if (in>=0) unsig=in;
354   else {                               /* negative (possibly BADINT)  */
355    if (in==BADINT) unsig=(uInt)1073741824*2; /* special case  */
356     else unsig=-in;                    /* invert  */
357    }
358  /* in is now positive  */
359  uprv_decNumberFromUInt32(dn, unsig);
360  if (in<0) dn->bits=DECNEG;            /* sign needed  */
361  return dn;
362  } /* decNumberFromInt32  */
363
364U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
365  Unit *up;                             /* work pointer  */
366  uprv_decNumberZero(dn);                    /* clean  */
367  if (uin==0) return dn;                /* [or decGetDigits bad call]  */
368  for (up=dn->lsu; uin>0; up++) {
369    *up=(Unit)(uin%(DECDPUNMAX+1));
370    uin=uin/(DECDPUNMAX+1);
371    }
372  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
373  return dn;
374  } /* decNumberFromUInt32  */
375
376/* ------------------------------------------------------------------ */
377/* to-int32 -- conversion to Int or uInt                              */
378/*                                                                    */
379/*  dn is the decNumber to convert                                    */
380/*  set is the context for reporting errors                           */
381/*  returns the converted decNumber, or 0 if Invalid is set           */
382/*                                                                    */
383/* Invalid is set if the decNumber does not have exponent==0 or if    */
384/* it is a NaN, Infinite, or out-of-range.                            */
385/* ------------------------------------------------------------------ */
386U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
387  #if DECCHECK
388  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
389  #endif
390
391  /* special or too many digits, or bad exponent  */
392  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad  */
393   else { /* is a finite integer with 10 or fewer digits  */
394    Int d;                         /* work  */
395    const Unit *up;                /* ..  */
396    uInt hi=0, lo;                 /* ..  */
397    up=dn->lsu;                    /* -> lsu  */
398    lo=*up;                        /* get 1 to 9 digits  */
399    #if DECDPUN>1                  /* split to higher  */
400      hi=lo/10;
401      lo=lo%10;
402    #endif
403    up++;
404    /* collect remaining Units, if any, into hi  */
405    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
406    /* now low has the lsd, hi the remainder  */
407    if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range?  */
408      /* most-negative is a reprieve  */
409      if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
410      /* bad -- drop through  */
411      }
412     else { /* in-range always  */
413      Int i=X10(hi)+lo;
414      if (dn->bits&DECNEG) return -i;
415      return i;
416      }
417    } /* integer  */
418  uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
419  return 0;
420  } /* decNumberToInt32  */
421
422U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
423  #if DECCHECK
424  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
425  #endif
426  /* special or too many digits, or bad exponent, or negative (<0)  */
427  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
428    || (dn->bits&DECNEG && !ISZERO(dn)));                   /* bad  */
429   else { /* is a finite integer with 10 or fewer digits  */
430    Int d;                         /* work  */
431    const Unit *up;                /* ..  */
432    uInt hi=0, lo;                 /* ..  */
433    up=dn->lsu;                    /* -> lsu  */
434    lo=*up;                        /* get 1 to 9 digits  */
435    #if DECDPUN>1                  /* split to higher  */
436      hi=lo/10;
437      lo=lo%10;
438    #endif
439    up++;
440    /* collect remaining Units, if any, into hi  */
441    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
442
443    /* now low has the lsd, hi the remainder  */
444    if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible  */
445     else return X10(hi)+lo;
446    } /* integer  */
447  uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
448  return 0;
449  } /* decNumberToUInt32  */
450
451/* ------------------------------------------------------------------ */
452/* to-scientific-string -- conversion to numeric string               */
453/* to-engineering-string -- conversion to numeric string              */
454/*                                                                    */
455/*   decNumberToString(dn, string);                                   */
456/*   decNumberToEngString(dn, string);                                */
457/*                                                                    */
458/*  dn is the decNumber to convert                                    */
459/*  string is the string where the result will be laid out            */
460/*                                                                    */
461/*  string must be at least dn->digits+14 characters long             */
462/*                                                                    */
463/*  No error is possible, and no status can be set.                   */
464/* ------------------------------------------------------------------ */
465U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
466  decToString(dn, string, 0);
467  return string;
468  } /* DecNumberToString  */
469
470U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
471  decToString(dn, string, 1);
472  return string;
473  } /* DecNumberToEngString  */
474
475/* ------------------------------------------------------------------ */
476/* to-number -- conversion from numeric string                        */
477/*                                                                    */
478/* decNumberFromString -- convert string to decNumber                 */
479/*   dn        -- the number structure to fill                        */
480/*   chars[]   -- the string to convert ('\0' terminated)             */
481/*   set       -- the context used for processing any error,          */
482/*                determining the maximum precision available         */
483/*                (set.digits), determining the maximum and minimum   */
484/*                exponent (set.emax and set.emin), determining if    */
485/*                extended values are allowed, and checking the       */
486/*                rounding mode if overflow occurs or rounding is     */
487/*                needed.                                             */
488/*                                                                    */
489/* The length of the coefficient and the size of the exponent are     */
490/* checked by this routine, so the correct error (Underflow or        */
491/* Overflow) can be reported or rounding applied, as necessary.       */
492/*                                                                    */
493/* If bad syntax is detected, the result will be a quiet NaN.         */
494/* ------------------------------------------------------------------ */
495U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
496                                decContext *set) {
497  Int   exponent=0;                /* working exponent [assume 0]  */
498  uByte bits=0;                    /* working flags [assume +ve]  */
499  Unit  *res;                      /* where result will be built  */
500  Unit  resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary  */
501                                   /* [+9 allows for ln() constants]  */
502  Unit  *allocres=NULL;            /* -> allocated result, iff allocated  */
503  Int   d=0;                       /* count of digits found in decimal part  */
504  const char *dotchar=NULL;        /* where dot was found  */
505  const char *cfirst=chars;        /* -> first character of decimal part  */
506  const char *last=NULL;           /* -> last digit of decimal part  */
507  const char *c;                   /* work  */
508  Unit  *up;                       /* ..  */
509  #if DECDPUN>1
510  Int   cut, out;                  /* ..  */
511  #endif
512  Int   residue;                   /* rounding residue  */
513  uInt  status=0;                  /* error code  */
514
515  #if DECCHECK
516  if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
517    return uprv_decNumberZero(dn);
518  #endif
519
520  do {                             /* status & malloc protection  */
521    for (c=chars;; c++) {          /* -> input character  */
522      if (*c>='0' && *c<='9') {    /* test for Arabic digit  */
523        last=c;
524        d++;                       /* count of real digits  */
525        continue;                  /* still in decimal part  */
526        }
527      if (*c=='.' && dotchar==NULL) { /* first '.'  */
528        dotchar=c;                 /* record offset into decimal part  */
529        if (c==cfirst) cfirst++;   /* first digit must follow  */
530        continue;}
531      if (c==chars) {              /* first in string...  */
532        if (*c=='-') {             /* valid - sign  */
533          cfirst++;
534          bits=DECNEG;
535          continue;}
536        if (*c=='+') {             /* valid + sign  */
537          cfirst++;
538          continue;}
539        }
540      /* *c is not a digit, or a valid +, -, or '.'  */
541      break;
542      } /* c  */
543
544    if (last==NULL) {              /* no digits yet  */
545      status=DEC_Conversion_syntax;/* assume the worst  */
546      if (*c=='\0') break;         /* and no more to come...  */
547      #if DECSUBSET
548      /* if subset then infinities and NaNs are not allowed  */
549      if (!set->extended) break;   /* hopeless  */
550      #endif
551      /* Infinities and NaNs are possible, here  */
552      if (dotchar!=NULL) break;    /* .. unless had a dot  */
553      uprv_decNumberZero(dn);           /* be optimistic  */
554      if (decBiStr(c, "infinity", "INFINITY")
555       || decBiStr(c, "inf", "INF")) {
556        dn->bits=bits | DECINF;
557        status=0;                  /* is OK  */
558        break; /* all done  */
559        }
560      /* a NaN expected  */
561      /* 2003.09.10 NaNs are now permitted to have a sign  */
562      dn->bits=bits | DECNAN;      /* assume simple NaN  */
563      if (*c=='s' || *c=='S') {    /* looks like an sNaN  */
564        c++;
565        dn->bits=bits | DECSNAN;
566        }
567      if (*c!='n' && *c!='N') break;    /* check caseless "NaN"  */
568      c++;
569      if (*c!='a' && *c!='A') break;    /* ..  */
570      c++;
571      if (*c!='n' && *c!='N') break;    /* ..  */
572      c++;
573      /* now either nothing, or nnnn payload, expected  */
574      /* -> start of integer and skip leading 0s [including plain 0]  */
575      for (cfirst=c; *cfirst=='0';) cfirst++;
576      if (*cfirst=='\0') {         /* "NaN" or "sNaN", maybe with all 0s  */
577        status=0;                  /* it's good  */
578        break;                     /* ..  */
579        }
580      /* something other than 0s; setup last and d as usual [no dots]  */
581      for (c=cfirst;; c++, d++) {
582        if (*c<'0' || *c>'9') break; /* test for Arabic digit  */
583        last=c;
584        }
585      if (*c!='\0') break;         /* not all digits  */
586      if (d>set->digits-1) {
587        /* [NB: payload in a decNumber can be full length unless  */
588        /* clamped, in which case can only be digits-1]  */
589        if (set->clamp) break;
590        if (d>set->digits) break;
591        } /* too many digits?  */
592      /* good; drop through to convert the integer to coefficient  */
593      status=0;                    /* syntax is OK  */
594      bits=dn->bits;               /* for copy-back  */
595      } /* last==NULL  */
596
597     else if (*c!='\0') {          /* more to process...  */
598      /* had some digits; exponent is only valid sequence now  */
599      Flag nege;                   /* 1=negative exponent  */
600      const char *firstexp;        /* -> first significant exponent digit  */
601      status=DEC_Conversion_syntax;/* assume the worst  */
602      if (*c!='e' && *c!='E') break;
603      /* Found 'e' or 'E' -- now process explicit exponent */
604      /* 1998.07.11: sign no longer required  */
605      nege=0;
606      c++;                         /* to (possible) sign  */
607      if (*c=='-') {nege=1; c++;}
608       else if (*c=='+') c++;
609      if (*c=='\0') break;
610
611      for (; *c=='0' && *(c+1)!='\0';) c++;  /* strip insignificant zeros  */
612      firstexp=c;                            /* save exponent digit place  */
613      for (; ;c++) {
614        if (*c<'0' || *c>'9') break;         /* not a digit  */
615        exponent=X10(exponent)+(Int)*c-(Int)'0';
616        } /* c  */
617      /* if not now on a '\0', *c must not be a digit  */
618      if (*c!='\0') break;
619
620      /* (this next test must be after the syntax checks)  */
621      /* if it was too long the exponent may have wrapped, so check  */
622      /* carefully and set it to a certain overflow if wrap possible  */
623      if (c>=firstexp+9+1) {
624        if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
625        /* [up to 1999999999 is OK, for example 1E-1000000998]  */
626        }
627      if (nege) exponent=-exponent;     /* was negative  */
628      status=0;                         /* is OK  */
629      } /* stuff after digits  */
630
631    /* Here when whole string has been inspected; syntax is good  */
632    /* cfirst->first digit (never dot), last->last digit (ditto)  */
633
634    /* strip leading zeros/dot [leave final 0 if all 0's]  */
635    if (*cfirst=='0') {                 /* [cfirst has stepped over .]  */
636      for (c=cfirst; c<last; c++, cfirst++) {
637        if (*c=='.') continue;          /* ignore dots  */
638        if (*c!='0') break;             /* non-zero found  */
639        d--;                            /* 0 stripped  */
640        } /* c  */
641      #if DECSUBSET
642      /* make a rapid exit for easy zeros if !extended  */
643      if (*cfirst=='0' && !set->extended) {
644        uprv_decNumberZero(dn);              /* clean result  */
645        break;                          /* [could be return]  */
646        }
647      #endif
648      } /* at least one leading 0  */
649
650    /* Handle decimal point...  */
651    if (dotchar!=NULL && dotchar<last)  /* non-trailing '.' found?  */
652      exponent-=(last-dotchar);         /* adjust exponent  */
653    /* [we can now ignore the .]  */
654
655    /* OK, the digits string is good.  Assemble in the decNumber, or in  */
656    /* a temporary units array if rounding is needed  */
657    if (d<=set->digits) res=dn->lsu;    /* fits into supplied decNumber  */
658     else {                             /* rounding needed  */
659      Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed  */
660      res=resbuff;                      /* assume use local buffer  */
661      if (needbytes>(Int)sizeof(resbuff)) { /* too big for local  */
662        allocres=(Unit *)malloc(needbytes);
663        if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
664        res=allocres;
665        }
666      }
667    /* res now -> number lsu, buffer, or allocated storage for Unit array  */
668
669    /* Place the coefficient into the selected Unit array  */
670    /* [this is often 70% of the cost of this function when DECDPUN>1]  */
671    #if DECDPUN>1
672    out=0;                         /* accumulator  */
673    up=res+D2U(d)-1;               /* -> msu  */
674    cut=d-(up-res)*DECDPUN;        /* digits in top unit  */
675    for (c=cfirst;; c++) {         /* along the digits  */
676      if (*c=='.') continue;       /* ignore '.' [don't decrement cut]  */
677      out=X10(out)+(Int)*c-(Int)'0';
678      if (c==last) break;          /* done [never get to trailing '.']  */
679      cut--;
680      if (cut>0) continue;         /* more for this unit  */
681      *up=(Unit)out;               /* write unit  */
682      up--;                        /* prepare for unit below..  */
683      cut=DECDPUN;                 /* ..  */
684      out=0;                       /* ..  */
685      } /* c  */
686    *up=(Unit)out;                 /* write lsu  */
687
688    #else
689    /* DECDPUN==1  */
690    up=res;                        /* -> lsu  */
691    for (c=last; c>=cfirst; c--) { /* over each character, from least  */
692      if (*c=='.') continue;       /* ignore . [don't step up]  */
693      *up=(Unit)((Int)*c-(Int)'0');
694      up++;
695      } /* c  */
696    #endif
697
698    dn->bits=bits;
699    dn->exponent=exponent;
700    dn->digits=d;
701
702    /* if not in number (too long) shorten into the number  */
703    if (d>set->digits) {
704      residue=0;
705      decSetCoeff(dn, set, res, d, &residue, &status);
706      /* always check for overflow or subnormal and round as needed  */
707      decFinalize(dn, set, &residue, &status);
708      }
709     else { /* no rounding, but may still have overflow or subnormal  */
710      /* [these tests are just for performance; finalize repeats them]  */
711      if ((dn->exponent-1<set->emin-dn->digits)
712       || (dn->exponent-1>set->emax-set->digits)) {
713        residue=0;
714        decFinalize(dn, set, &residue, &status);
715        }
716      }
717    /* decNumberShow(dn);  */
718    } while(0);                         /* [for break]  */
719
720  if (allocres!=NULL) free(allocres);   /* drop any storage used  */
721  if (status!=0) decStatus(dn, status, set);
722  return dn;
723  } /* decNumberFromString */
724
725/* ================================================================== */
726/* Operators                                                          */
727/* ================================================================== */
728
729/* ------------------------------------------------------------------ */
730/* decNumberAbs -- absolute value operator                            */
731/*                                                                    */
732/*   This computes C = abs(A)                                         */
733/*                                                                    */
734/*   res is C, the result.  C may be A                                */
735/*   rhs is A                                                         */
736/*   set is the context                                               */
737/*                                                                    */
738/* See also decNumberCopyAbs for a quiet bitwise version of this.     */
739/* C must have space for set->digits digits.                          */
740/* ------------------------------------------------------------------ */
741/* This has the same effect as decNumberPlus unless A is negative,    */
742/* in which case it has the same effect as decNumberMinus.            */
743/* ------------------------------------------------------------------ */
744U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
745                         decContext *set) {
746  decNumber dzero;                      /* for 0  */
747  uInt status=0;                        /* accumulator  */
748
749  #if DECCHECK
750  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
751  #endif
752
753  uprv_decNumberZero(&dzero);                /* set 0  */
754  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
755  decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
756  if (status!=0) decStatus(res, status, set);
757  #if DECCHECK
758  decCheckInexact(res, set);
759  #endif
760  return res;
761  } /* decNumberAbs  */
762
763/* ------------------------------------------------------------------ */
764/* decNumberAdd -- add two Numbers                                    */
765/*                                                                    */
766/*   This computes C = A + B                                          */
767/*                                                                    */
768/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
769/*   lhs is A                                                         */
770/*   rhs is B                                                         */
771/*   set is the context                                               */
772/*                                                                    */
773/* C must have space for set->digits digits.                          */
774/* ------------------------------------------------------------------ */
775/* This just calls the routine shared with Subtract                   */
776U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
777                         const decNumber *rhs, decContext *set) {
778  uInt status=0;                        /* accumulator  */
779  decAddOp(res, lhs, rhs, set, 0, &status);
780  if (status!=0) decStatus(res, status, set);
781  #if DECCHECK
782  decCheckInexact(res, set);
783  #endif
784  return res;
785  } /* decNumberAdd  */
786
787/* ------------------------------------------------------------------ */
788/* decNumberAnd -- AND two Numbers, digitwise                         */
789/*                                                                    */
790/*   This computes C = A & B                                          */
791/*                                                                    */
792/*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
793/*   lhs is A                                                         */
794/*   rhs is B                                                         */
795/*   set is the context (used for result length and error report)     */
796/*                                                                    */
797/* C must have space for set->digits digits.                          */
798/*                                                                    */
799/* Logical function restrictions apply (see above); a NaN is          */
800/* returned with Invalid_operation if a restriction is violated.      */
801/* ------------------------------------------------------------------ */
802U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
803                         const decNumber *rhs, decContext *set) {
804  const Unit *ua, *ub;                  /* -> operands  */
805  const Unit *msua, *msub;              /* -> operand msus  */
806  Unit *uc,  *msuc;                     /* -> result and its msu  */
807  Int   msudigs;                        /* digits in res msu  */
808  #if DECCHECK
809  if (decCheckOperands(res, lhs, rhs, set)) return res;
810  #endif
811
812  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
813   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
814    decStatus(res, DEC_Invalid_operation, set);
815    return res;
816    }
817
818  /* operands are valid  */
819  ua=lhs->lsu;                          /* bottom-up  */
820  ub=rhs->lsu;                          /* ..  */
821  uc=res->lsu;                          /* ..  */
822  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
823  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
824  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
825  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
826  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
827    Unit a, b;                          /* extract units  */
828    if (ua>msua) a=0;
829     else a=*ua;
830    if (ub>msub) b=0;
831     else b=*ub;
832    *uc=0;                              /* can now write back  */
833    if (a|b) {                          /* maybe 1 bits to examine  */
834      Int i, j;
835      *uc=0;                            /* can now write back  */
836      /* This loop could be unrolled and/or use BIN2BCD tables  */
837      for (i=0; i<DECDPUN; i++) {
838        if (a&b&1) *uc=*uc+(Unit)powers[i];  /* effect AND  */
839        j=a%10;
840        a=a/10;
841        j|=b%10;
842        b=b/10;
843        if (j>1) {
844          decStatus(res, DEC_Invalid_operation, set);
845          return res;
846          }
847        if (uc==msuc && i==msudigs-1) break; /* just did final digit  */
848        } /* each digit  */
849      } /* both OK  */
850    } /* each unit  */
851  /* [here uc-1 is the msu of the result]  */
852  res->digits=decGetDigits(res->lsu, uc-res->lsu);
853  res->exponent=0;                      /* integer  */
854  res->bits=0;                          /* sign=0  */
855  return res;  /* [no status to set]  */
856  } /* decNumberAnd  */
857
858/* ------------------------------------------------------------------ */
859/* decNumberCompare -- compare two Numbers                            */
860/*                                                                    */
861/*   This computes C = A ? B                                          */
862/*                                                                    */
863/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
864/*   lhs is A                                                         */
865/*   rhs is B                                                         */
866/*   set is the context                                               */
867/*                                                                    */
868/* C must have space for one digit (or NaN).                          */
869/* ------------------------------------------------------------------ */
870U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
871                             const decNumber *rhs, decContext *set) {
872  uInt status=0;                        /* accumulator  */
873  decCompareOp(res, lhs, rhs, set, COMPARE, &status);
874  if (status!=0) decStatus(res, status, set);
875  return res;
876  } /* decNumberCompare  */
877
878/* ------------------------------------------------------------------ */
879/* decNumberCompareSignal -- compare, signalling on all NaNs          */
880/*                                                                    */
881/*   This computes C = A ? B                                          */
882/*                                                                    */
883/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
884/*   lhs is A                                                         */
885/*   rhs is B                                                         */
886/*   set is the context                                               */
887/*                                                                    */
888/* C must have space for one digit (or NaN).                          */
889/* ------------------------------------------------------------------ */
890U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
891                                   const decNumber *rhs, decContext *set) {
892  uInt status=0;                        /* accumulator  */
893  decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
894  if (status!=0) decStatus(res, status, set);
895  return res;
896  } /* decNumberCompareSignal  */
897
898/* ------------------------------------------------------------------ */
899/* decNumberCompareTotal -- compare two Numbers, using total ordering */
900/*                                                                    */
901/*   This computes C = A ? B, under total ordering                    */
902/*                                                                    */
903/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
904/*   lhs is A                                                         */
905/*   rhs is B                                                         */
906/*   set is the context                                               */
907/*                                                                    */
908/* C must have space for one digit; the result will always be one of  */
909/* -1, 0, or 1.                                                       */
910/* ------------------------------------------------------------------ */
911U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
912                                  const decNumber *rhs, decContext *set) {
913  uInt status=0;                        /* accumulator  */
914  decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
915  if (status!=0) decStatus(res, status, set);
916  return res;
917  } /* decNumberCompareTotal  */
918
919/* ------------------------------------------------------------------ */
920/* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
921/*                                                                    */
922/*   This computes C = |A| ? |B|, under total ordering                */
923/*                                                                    */
924/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
925/*   lhs is A                                                         */
926/*   rhs is B                                                         */
927/*   set is the context                                               */
928/*                                                                    */
929/* C must have space for one digit; the result will always be one of  */
930/* -1, 0, or 1.                                                       */
931/* ------------------------------------------------------------------ */
932U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
933                                     const decNumber *rhs, decContext *set) {
934  uInt status=0;                   /* accumulator  */
935  uInt needbytes;                  /* for space calculations  */
936  decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0  */
937  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
938  decNumber bufb[D2N(DECBUFFER+1)];
939  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
940  decNumber *a, *b;                /* temporary pointers  */
941
942  #if DECCHECK
943  if (decCheckOperands(res, lhs, rhs, set)) return res;
944  #endif
945
946  do {                                  /* protect allocated storage  */
947    /* if either is negative, take a copy and absolute  */
948    if (decNumberIsNegative(lhs)) {     /* lhs<0  */
949      a=bufa;
950      needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
951      if (needbytes>sizeof(bufa)) {     /* need malloc space  */
952        allocbufa=(decNumber *)malloc(needbytes);
953        if (allocbufa==NULL) {          /* hopeless -- abandon  */
954          status|=DEC_Insufficient_storage;
955          break;}
956        a=allocbufa;                    /* use the allocated space  */
957        }
958      uprv_decNumberCopy(a, lhs);            /* copy content  */
959      a->bits&=~DECNEG;                 /* .. and clear the sign  */
960      lhs=a;                            /* use copy from here on  */
961      }
962    if (decNumberIsNegative(rhs)) {     /* rhs<0  */
963      b=bufb;
964      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
965      if (needbytes>sizeof(bufb)) {     /* need malloc space  */
966        allocbufb=(decNumber *)malloc(needbytes);
967        if (allocbufb==NULL) {          /* hopeless -- abandon  */
968          status|=DEC_Insufficient_storage;
969          break;}
970        b=allocbufb;                    /* use the allocated space  */
971        }
972      uprv_decNumberCopy(b, rhs);            /* copy content  */
973      b->bits&=~DECNEG;                 /* .. and clear the sign  */
974      rhs=b;                            /* use copy from here on  */
975      }
976    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
977    } while(0);                         /* end protected  */
978
979  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
980  if (allocbufb!=NULL) free(allocbufb); /* ..  */
981  if (status!=0) decStatus(res, status, set);
982  return res;
983  } /* decNumberCompareTotalMag  */
984
985/* ------------------------------------------------------------------ */
986/* decNumberDivide -- divide one number by another                    */
987/*                                                                    */
988/*   This computes C = A / B                                          */
989/*                                                                    */
990/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
991/*   lhs is A                                                         */
992/*   rhs is B                                                         */
993/*   set is the context                                               */
994/*                                                                    */
995/* C must have space for set->digits digits.                          */
996/* ------------------------------------------------------------------ */
997U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
998                            const decNumber *rhs, decContext *set) {
999  uInt status=0;                        /* accumulator  */
1000  decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1001  if (status!=0) decStatus(res, status, set);
1002  #if DECCHECK
1003  decCheckInexact(res, set);
1004  #endif
1005  return res;
1006  } /* decNumberDivide  */
1007
1008/* ------------------------------------------------------------------ */
1009/* decNumberDivideInteger -- divide and return integer quotient       */
1010/*                                                                    */
1011/*   This computes C = A # B, where # is the integer divide operator  */
1012/*                                                                    */
1013/*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1014/*   lhs is A                                                         */
1015/*   rhs is B                                                         */
1016/*   set is the context                                               */
1017/*                                                                    */
1018/* C must have space for set->digits digits.                          */
1019/* ------------------------------------------------------------------ */
1020U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1021                                   const decNumber *rhs, decContext *set) {
1022  uInt status=0;                        /* accumulator  */
1023  decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1024  if (status!=0) decStatus(res, status, set);
1025  return res;
1026  } /* decNumberDivideInteger  */
1027
1028/* ------------------------------------------------------------------ */
1029/* decNumberExp -- exponentiation                                     */
1030/*                                                                    */
1031/*   This computes C = exp(A)                                         */
1032/*                                                                    */
1033/*   res is C, the result.  C may be A                                */
1034/*   rhs is A                                                         */
1035/*   set is the context; note that rounding mode has no effect        */
1036/*                                                                    */
1037/* C must have space for set->digits digits.                          */
1038/*                                                                    */
1039/* Mathematical function restrictions apply (see above); a NaN is     */
1040/* returned with Invalid_operation if a restriction is violated.      */
1041/*                                                                    */
1042/* Finite results will always be full precision and Inexact, except   */
1043/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1044/*                                                                    */
1045/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1046/* almost always be correctly rounded, but may be up to 1 ulp in      */
1047/* error in rare cases.                                               */
1048/* ------------------------------------------------------------------ */
1049/* This is a wrapper for decExpOp which can handle the slightly wider */
1050/* (double) range needed by Ln (which has to be able to calculate     */
1051/* exp(-a) where a can be the tiniest number (Ntiny).                 */
1052/* ------------------------------------------------------------------ */
1053U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
1054                         decContext *set) {
1055  uInt status=0;                        /* accumulator  */
1056  #if DECSUBSET
1057  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1058  #endif
1059
1060  #if DECCHECK
1061  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1062  #endif
1063
1064  /* Check restrictions; these restrictions ensure that if h=8 (see  */
1065  /* decExpOp) then the result will either overflow or underflow to 0.  */
1066  /* Other math functions restrict the input range, too, for inverses.  */
1067  /* If not violated then carry out the operation.  */
1068  if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1069    #if DECSUBSET
1070    if (!set->extended) {
1071      /* reduce operand and set lostDigits status, as needed  */
1072      if (rhs->digits>set->digits) {
1073        allocrhs=decRoundOperand(rhs, set, &status);
1074        if (allocrhs==NULL) break;
1075        rhs=allocrhs;
1076        }
1077      }
1078    #endif
1079    decExpOp(res, rhs, set, &status);
1080    } while(0);                         /* end protected  */
1081
1082  #if DECSUBSET
1083  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1084  #endif
1085  /* apply significant status  */
1086  if (status!=0) decStatus(res, status, set);
1087  #if DECCHECK
1088  decCheckInexact(res, set);
1089  #endif
1090  return res;
1091  } /* decNumberExp  */
1092
1093/* ------------------------------------------------------------------ */
1094/* decNumberFMA -- fused multiply add                                 */
1095/*                                                                    */
1096/*   This computes D = (A * B) + C with only one rounding             */
1097/*                                                                    */
1098/*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1099/*   lhs is A                                                         */
1100/*   rhs is B                                                         */
1101/*   fhs is C [far hand side]                                         */
1102/*   set is the context                                               */
1103/*                                                                    */
1104/* Mathematical function restrictions apply (see above); a NaN is     */
1105/* returned with Invalid_operation if a restriction is violated.      */
1106/*                                                                    */
1107/* C must have space for set->digits digits.                          */
1108/* ------------------------------------------------------------------ */
1109U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
1110                         const decNumber *rhs, const decNumber *fhs,
1111                         decContext *set) {
1112  uInt status=0;                   /* accumulator  */
1113  decContext dcmul;                /* context for the multiplication  */
1114  uInt needbytes;                  /* for space calculations  */
1115  decNumber bufa[D2N(DECBUFFER*2+1)];
1116  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1117  decNumber *acc;                  /* accumulator pointer  */
1118  decNumber dzero;                 /* work  */
1119
1120  #if DECCHECK
1121  if (decCheckOperands(res, lhs, rhs, set)) return res;
1122  if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1123  #endif
1124
1125  do {                                  /* protect allocated storage  */
1126    #if DECSUBSET
1127    if (!set->extended) {               /* [undefined if subset]  */
1128      status|=DEC_Invalid_operation;
1129      break;}
1130    #endif
1131    /* Check math restrictions [these ensure no overflow or underflow]  */
1132    if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1133     || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1134     || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1135    /* set up context for multiply  */
1136    dcmul=*set;
1137    dcmul.digits=lhs->digits+rhs->digits; /* just enough  */
1138    /* [The above may be an over-estimate for subset arithmetic, but that's OK]  */
1139    dcmul.emax=DEC_MAX_EMAX;            /* effectively unbounded ..  */
1140    dcmul.emin=DEC_MIN_EMIN;            /* [thanks to Math restrictions]  */
1141    /* set up decNumber space to receive the result of the multiply  */
1142    acc=bufa;                           /* may fit  */
1143    needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1144    if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1145      allocbufa=(decNumber *)malloc(needbytes);
1146      if (allocbufa==NULL) {            /* hopeless -- abandon  */
1147        status|=DEC_Insufficient_storage;
1148        break;}
1149      acc=allocbufa;                    /* use the allocated space  */
1150      }
1151    /* multiply with extended range and necessary precision  */
1152    /*printf("emin=%ld\n", dcmul.emin);  */
1153    decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1154    /* Only Invalid operation (from sNaN or Inf * 0) is possible in  */
1155    /* status; if either is seen than ignore fhs (in case it is  */
1156    /* another sNaN) and set acc to NaN unless we had an sNaN  */
1157    /* [decMultiplyOp leaves that to caller]  */
1158    /* Note sNaN has to go through addOp to shorten payload if  */
1159    /* necessary  */
1160    if ((status&DEC_Invalid_operation)!=0) {
1161      if (!(status&DEC_sNaN)) {         /* but be true invalid  */
1162        uprv_decNumberZero(res);             /* acc not yet set  */
1163        res->bits=DECNAN;
1164        break;
1165        }
1166      uprv_decNumberZero(&dzero);            /* make 0 (any non-NaN would do)  */
1167      fhs=&dzero;                       /* use that  */
1168      }
1169    #if DECCHECK
1170     else { /* multiply was OK  */
1171      if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1172      }
1173    #endif
1174    /* add the third operand and result -> res, and all is done  */
1175    decAddOp(res, acc, fhs, set, 0, &status);
1176    } while(0);                         /* end protected  */
1177
1178  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1179  if (status!=0) decStatus(res, status, set);
1180  #if DECCHECK
1181  decCheckInexact(res, set);
1182  #endif
1183  return res;
1184  } /* decNumberFMA  */
1185
1186/* ------------------------------------------------------------------ */
1187/* decNumberInvert -- invert a Number, digitwise                      */
1188/*                                                                    */
1189/*   This computes C = ~A                                             */
1190/*                                                                    */
1191/*   res is C, the result.  C may be A (e.g., X=~X)                   */
1192/*   rhs is A                                                         */
1193/*   set is the context (used for result length and error report)     */
1194/*                                                                    */
1195/* C must have space for set->digits digits.                          */
1196/*                                                                    */
1197/* Logical function restrictions apply (see above); a NaN is          */
1198/* returned with Invalid_operation if a restriction is violated.      */
1199/* ------------------------------------------------------------------ */
1200U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
1201                            decContext *set) {
1202  const Unit *ua, *msua;                /* -> operand and its msu  */
1203  Unit  *uc, *msuc;                     /* -> result and its msu  */
1204  Int   msudigs;                        /* digits in res msu  */
1205  #if DECCHECK
1206  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1207  #endif
1208
1209  if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1210    decStatus(res, DEC_Invalid_operation, set);
1211    return res;
1212    }
1213  /* operand is valid  */
1214  ua=rhs->lsu;                          /* bottom-up  */
1215  uc=res->lsu;                          /* ..  */
1216  msua=ua+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1217  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1218  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1219  for (; uc<=msuc; ua++, uc++) {        /* Unit loop  */
1220    Unit a;                             /* extract unit  */
1221    Int  i, j;                          /* work  */
1222    if (ua>msua) a=0;
1223     else a=*ua;
1224    *uc=0;                              /* can now write back  */
1225    /* always need to examine all bits in rhs  */
1226    /* This loop could be unrolled and/or use BIN2BCD tables  */
1227    for (i=0; i<DECDPUN; i++) {
1228      if ((~a)&1) *uc=*uc+(Unit)powers[i];   /* effect INVERT  */
1229      j=a%10;
1230      a=a/10;
1231      if (j>1) {
1232        decStatus(res, DEC_Invalid_operation, set);
1233        return res;
1234        }
1235      if (uc==msuc && i==msudigs-1) break;   /* just did final digit  */
1236      } /* each digit  */
1237    } /* each unit  */
1238  /* [here uc-1 is the msu of the result]  */
1239  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1240  res->exponent=0;                      /* integer  */
1241  res->bits=0;                          /* sign=0  */
1242  return res;  /* [no status to set]  */
1243  } /* decNumberInvert  */
1244
1245/* ------------------------------------------------------------------ */
1246/* decNumberLn -- natural logarithm                                   */
1247/*                                                                    */
1248/*   This computes C = ln(A)                                          */
1249/*                                                                    */
1250/*   res is C, the result.  C may be A                                */
1251/*   rhs is A                                                         */
1252/*   set is the context; note that rounding mode has no effect        */
1253/*                                                                    */
1254/* C must have space for set->digits digits.                          */
1255/*                                                                    */
1256/* Notable cases:                                                     */
1257/*   A<0 -> Invalid                                                   */
1258/*   A=0 -> -Infinity (Exact)                                         */
1259/*   A=+Infinity -> +Infinity (Exact)                                 */
1260/*   A=1 exactly -> 0 (Exact)                                         */
1261/*                                                                    */
1262/* Mathematical function restrictions apply (see above); a NaN is     */
1263/* returned with Invalid_operation if a restriction is violated.      */
1264/*                                                                    */
1265/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1266/* almost always be correctly rounded, but may be up to 1 ulp in      */
1267/* error in rare cases.                                               */
1268/* ------------------------------------------------------------------ */
1269/* This is a wrapper for decLnOp which can handle the slightly wider  */
1270/* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1271/* to calculate at p+e+2).                                            */
1272/* ------------------------------------------------------------------ */
1273U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
1274                        decContext *set) {
1275  uInt status=0;                   /* accumulator  */
1276  #if DECSUBSET
1277  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1278  #endif
1279
1280  #if DECCHECK
1281  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1282  #endif
1283
1284  /* Check restrictions; this is a math function; if not violated  */
1285  /* then carry out the operation.  */
1286  if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1287    #if DECSUBSET
1288    if (!set->extended) {
1289      /* reduce operand and set lostDigits status, as needed  */
1290      if (rhs->digits>set->digits) {
1291        allocrhs=decRoundOperand(rhs, set, &status);
1292        if (allocrhs==NULL) break;
1293        rhs=allocrhs;
1294        }
1295      /* special check in subset for rhs=0  */
1296      if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1297        status|=DEC_Invalid_operation;
1298        break;}
1299      } /* extended=0  */
1300    #endif
1301    decLnOp(res, rhs, set, &status);
1302    } while(0);                         /* end protected  */
1303
1304  #if DECSUBSET
1305  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1306  #endif
1307  /* apply significant status  */
1308  if (status!=0) decStatus(res, status, set);
1309  #if DECCHECK
1310  decCheckInexact(res, set);
1311  #endif
1312  return res;
1313  } /* decNumberLn  */
1314
1315/* ------------------------------------------------------------------ */
1316/* decNumberLogB - get adjusted exponent, by 754 rules                */
1317/*                                                                    */
1318/*   This computes C = adjustedexponent(A)                            */
1319/*                                                                    */
1320/*   res is C, the result.  C may be A                                */
1321/*   rhs is A                                                         */
1322/*   set is the context, used only for digits and status              */
1323/*                                                                    */
1324/* C must have space for 10 digits (A might have 10**9 digits and     */
1325/* an exponent of +999999999, or one digit and an exponent of         */
1326/* -1999999999).                                                      */
1327/*                                                                    */
1328/* This returns the adjusted exponent of A after (in theory) padding  */
1329/* with zeros on the right to set->digits digits while keeping the    */
1330/* same value.  The exponent is not limited by emin/emax.             */
1331/*                                                                    */
1332/* Notable cases:                                                     */
1333/*   A<0 -> Use |A|                                                   */
1334/*   A=0 -> -Infinity (Division by zero)                              */
1335/*   A=Infinite -> +Infinity (Exact)                                  */
1336/*   A=1 exactly -> 0 (Exact)                                         */
1337/*   NaNs are propagated as usual                                     */
1338/* ------------------------------------------------------------------ */
1339U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
1340                          decContext *set) {
1341  uInt status=0;                   /* accumulator  */
1342
1343  #if DECCHECK
1344  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1345  #endif
1346
1347  /* NaNs as usual; Infinities return +Infinity; 0->oops  */
1348  if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1349   else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
1350   else if (decNumberIsZero(rhs)) {
1351    uprv_decNumberZero(res);                 /* prepare for Infinity  */
1352    res->bits=DECNEG|DECINF;            /* -Infinity  */
1353    status|=DEC_Division_by_zero;       /* as per 754  */
1354    }
1355   else { /* finite non-zero  */
1356    Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent  */
1357    uprv_decNumberFromInt32(res, ae);        /* lay it out  */
1358    }
1359
1360  if (status!=0) decStatus(res, status, set);
1361  return res;
1362  } /* decNumberLogB  */
1363
1364/* ------------------------------------------------------------------ */
1365/* decNumberLog10 -- logarithm in base 10                             */
1366/*                                                                    */
1367/*   This computes C = log10(A)                                       */
1368/*                                                                    */
1369/*   res is C, the result.  C may be A                                */
1370/*   rhs is A                                                         */
1371/*   set is the context; note that rounding mode has no effect        */
1372/*                                                                    */
1373/* C must have space for set->digits digits.                          */
1374/*                                                                    */
1375/* Notable cases:                                                     */
1376/*   A<0 -> Invalid                                                   */
1377/*   A=0 -> -Infinity (Exact)                                         */
1378/*   A=+Infinity -> +Infinity (Exact)                                 */
1379/*   A=10**n (if n is an integer) -> n (Exact)                        */
1380/*                                                                    */
1381/* Mathematical function restrictions apply (see above); a NaN is     */
1382/* returned with Invalid_operation if a restriction is violated.      */
1383/*                                                                    */
1384/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1385/* almost always be correctly rounded, but may be up to 1 ulp in      */
1386/* error in rare cases.                                               */
1387/* ------------------------------------------------------------------ */
1388/* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1389/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1390/* requested digits and t is the number of digits in the exponent     */
1391/* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1392/* fastpath in decLnOp.  The final division is done to the requested  */
1393/* precision.                                                         */
1394/* ------------------------------------------------------------------ */
1395U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1396                          decContext *set) {
1397  uInt status=0, ignore=0;         /* status accumulators  */
1398  uInt needbytes;                  /* for space calculations  */
1399  Int p;                           /* working precision  */
1400  Int t;                           /* digits in exponent of A  */
1401
1402  /* buffers for a and b working decimals  */
1403  /* (adjustment calculator, same size)  */
1404  decNumber bufa[D2N(DECBUFFER+2)];
1405  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1406  decNumber *a=bufa;               /* temporary a  */
1407  decNumber bufb[D2N(DECBUFFER+2)];
1408  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
1409  decNumber *b=bufb;               /* temporary b  */
1410  decNumber bufw[D2N(10)];         /* working 2-10 digit number  */
1411  decNumber *w=bufw;               /* ..  */
1412  #if DECSUBSET
1413  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1414  #endif
1415
1416  decContext aset;                 /* working context  */
1417
1418  #if DECCHECK
1419  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1420  #endif
1421
1422  /* Check restrictions; this is a math function; if not violated  */
1423  /* then carry out the operation.  */
1424  if (!decCheckMath(rhs, set, &status)) do { /* protect malloc  */
1425    #if DECSUBSET
1426    if (!set->extended) {
1427      /* reduce operand and set lostDigits status, as needed  */
1428      if (rhs->digits>set->digits) {
1429        allocrhs=decRoundOperand(rhs, set, &status);
1430        if (allocrhs==NULL) break;
1431        rhs=allocrhs;
1432        }
1433      /* special check in subset for rhs=0  */
1434      if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1435        status|=DEC_Invalid_operation;
1436        break;}
1437      } /* extended=0  */
1438    #endif
1439
1440    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
1441
1442    /* handle exact powers of 10; only check if +ve finite  */
1443    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1444      Int residue=0;               /* (no residue)  */
1445      uInt copystat=0;             /* clean status  */
1446
1447      /* round to a single digit...  */
1448      aset.digits=1;
1449      decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten  */
1450      /* if exact and the digit is 1, rhs is a power of 10  */
1451      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1452        /* the exponent, conveniently, is the power of 10; making  */
1453        /* this the result needs a little care as it might not fit,  */
1454        /* so first convert it into the working number, and then move  */
1455        /* to res  */
1456        uprv_decNumberFromInt32(w, w->exponent);
1457        residue=0;
1458        decCopyFit(res, w, set, &residue, &status); /* copy & round  */
1459        decFinish(res, set, &residue, &status);     /* cleanup/set flags  */
1460        break;
1461        } /* not a power of 10  */
1462      } /* not a candidate for exact  */
1463
1464    /* simplify the information-content calculation to use 'total  */
1465    /* number of digits in a, including exponent' as compared to the  */
1466    /* requested digits, as increasing this will only rarely cost an  */
1467    /* iteration in ln(a) anyway  */
1468    t=6;                                /* it can never be >6  */
1469
1470    /* allocate space when needed...  */
1471    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1472    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1473    if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1474      allocbufa=(decNumber *)malloc(needbytes);
1475      if (allocbufa==NULL) {            /* hopeless -- abandon  */
1476        status|=DEC_Insufficient_storage;
1477        break;}
1478      a=allocbufa;                      /* use the allocated space  */
1479      }
1480    aset.digits=p;                      /* as calculated  */
1481    aset.emax=DEC_MAX_MATH;             /* usual bounds  */
1482    aset.emin=-DEC_MAX_MATH;            /* ..  */
1483    aset.clamp=0;                       /* and no concrete format  */
1484    decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs)  */
1485
1486    /* skip the division if the result so far is infinite, NaN, or  */
1487    /* zero, or there was an error; note NaN from sNaN needs copy  */
1488    if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1489    if (a->bits&DECSPECIAL || ISZERO(a)) {
1490      uprv_decNumberCopy(res, a);            /* [will fit]  */
1491      break;}
1492
1493    /* for ln(10) an extra 3 digits of precision are needed  */
1494    p=set->digits+3;
1495    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1496    if (needbytes>sizeof(bufb)) {       /* need malloc space  */
1497      allocbufb=(decNumber *)malloc(needbytes);
1498      if (allocbufb==NULL) {            /* hopeless -- abandon  */
1499        status|=DEC_Insufficient_storage;
1500        break;}
1501      b=allocbufb;                      /* use the allocated space  */
1502      }
1503    uprv_decNumberZero(w);                   /* set up 10...  */
1504    #if DECDPUN==1
1505    w->lsu[1]=1; w->lsu[0]=0;           /* ..  */
1506    #else
1507    w->lsu[0]=10;                       /* ..  */
1508    #endif
1509    w->digits=2;                        /* ..  */
1510
1511    aset.digits=p;
1512    decLnOp(b, w, &aset, &ignore);      /* b=ln(10)  */
1513
1514    aset.digits=set->digits;            /* for final divide  */
1515    decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result  */
1516    } while(0);                         /* [for break]  */
1517
1518  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1519  if (allocbufb!=NULL) free(allocbufb); /* ..  */
1520  #if DECSUBSET
1521  if (allocrhs !=NULL) free(allocrhs);  /* ..  */
1522  #endif
1523  /* apply significant status  */
1524  if (status!=0) decStatus(res, status, set);
1525  #if DECCHECK
1526  decCheckInexact(res, set);
1527  #endif
1528  return res;
1529  } /* decNumberLog10  */
1530
1531/* ------------------------------------------------------------------ */
1532/* decNumberMax -- compare two Numbers and return the maximum         */
1533/*                                                                    */
1534/*   This computes C = A ? B, returning the maximum by 754 rules      */
1535/*                                                                    */
1536/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1537/*   lhs is A                                                         */
1538/*   rhs is B                                                         */
1539/*   set is the context                                               */
1540/*                                                                    */
1541/* C must have space for set->digits digits.                          */
1542/* ------------------------------------------------------------------ */
1543U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1544                         const decNumber *rhs, decContext *set) {
1545  uInt status=0;                        /* accumulator  */
1546  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1547  if (status!=0) decStatus(res, status, set);
1548  #if DECCHECK
1549  decCheckInexact(res, set);
1550  #endif
1551  return res;
1552  } /* decNumberMax  */
1553
1554/* ------------------------------------------------------------------ */
1555/* decNumberMaxMag -- compare and return the maximum by magnitude     */
1556/*                                                                    */
1557/*   This computes C = A ? B, returning the maximum by 754 rules      */
1558/*                                                                    */
1559/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1560/*   lhs is A                                                         */
1561/*   rhs is B                                                         */
1562/*   set is the context                                               */
1563/*                                                                    */
1564/* C must have space for set->digits digits.                          */
1565/* ------------------------------------------------------------------ */
1566U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1567                         const decNumber *rhs, decContext *set) {
1568  uInt status=0;                        /* accumulator  */
1569  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1570  if (status!=0) decStatus(res, status, set);
1571  #if DECCHECK
1572  decCheckInexact(res, set);
1573  #endif
1574  return res;
1575  } /* decNumberMaxMag  */
1576
1577/* ------------------------------------------------------------------ */
1578/* decNumberMin -- compare two Numbers and return the minimum         */
1579/*                                                                    */
1580/*   This computes C = A ? B, returning the minimum by 754 rules      */
1581/*                                                                    */
1582/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1583/*   lhs is A                                                         */
1584/*   rhs is B                                                         */
1585/*   set is the context                                               */
1586/*                                                                    */
1587/* C must have space for set->digits digits.                          */
1588/* ------------------------------------------------------------------ */
1589U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1590                         const decNumber *rhs, decContext *set) {
1591  uInt status=0;                        /* accumulator  */
1592  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1593  if (status!=0) decStatus(res, status, set);
1594  #if DECCHECK
1595  decCheckInexact(res, set);
1596  #endif
1597  return res;
1598  } /* decNumberMin  */
1599
1600/* ------------------------------------------------------------------ */
1601/* decNumberMinMag -- compare and return the minimum by magnitude     */
1602/*                                                                    */
1603/*   This computes C = A ? B, returning the minimum by 754 rules      */
1604/*                                                                    */
1605/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1606/*   lhs is A                                                         */
1607/*   rhs is B                                                         */
1608/*   set is the context                                               */
1609/*                                                                    */
1610/* C must have space for set->digits digits.                          */
1611/* ------------------------------------------------------------------ */
1612U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1613                         const decNumber *rhs, decContext *set) {
1614  uInt status=0;                        /* accumulator  */
1615  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1616  if (status!=0) decStatus(res, status, set);
1617  #if DECCHECK
1618  decCheckInexact(res, set);
1619  #endif
1620  return res;
1621  } /* decNumberMinMag  */
1622
1623/* ------------------------------------------------------------------ */
1624/* decNumberMinus -- prefix minus operator                            */
1625/*                                                                    */
1626/*   This computes C = 0 - A                                          */
1627/*                                                                    */
1628/*   res is C, the result.  C may be A                                */
1629/*   rhs is A                                                         */
1630/*   set is the context                                               */
1631/*                                                                    */
1632/* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1633/* C must have space for set->digits digits.                          */
1634/* ------------------------------------------------------------------ */
1635/* Simply use AddOp for the subtract, which will do the necessary.    */
1636/* ------------------------------------------------------------------ */
1637U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1638                           decContext *set) {
1639  decNumber dzero;
1640  uInt status=0;                        /* accumulator  */
1641
1642  #if DECCHECK
1643  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1644  #endif
1645
1646  uprv_decNumberZero(&dzero);                /* make 0  */
1647  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1648  decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1649  if (status!=0) decStatus(res, status, set);
1650  #if DECCHECK
1651  decCheckInexact(res, set);
1652  #endif
1653  return res;
1654  } /* decNumberMinus  */
1655
1656/* ------------------------------------------------------------------ */
1657/* decNumberNextMinus -- next towards -Infinity                       */
1658/*                                                                    */
1659/*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1660/*                                                                    */
1661/*   res is C, the result.  C may be A                                */
1662/*   rhs is A                                                         */
1663/*   set is the context                                               */
1664/*                                                                    */
1665/* This is a generalization of 754 NextDown.                          */
1666/* ------------------------------------------------------------------ */
1667U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1668                               decContext *set) {
1669  decNumber dtiny;                           /* constant  */
1670  decContext workset=*set;                   /* work  */
1671  uInt status=0;                             /* accumulator  */
1672  #if DECCHECK
1673  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1674  #endif
1675
1676  /* +Infinity is the special case  */
1677  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1678    decSetMaxValue(res, set);                /* is +ve  */
1679    /* there is no status to set  */
1680    return res;
1681    }
1682  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1683  dtiny.lsu[0]=1;                            /* make number that is ..  */
1684  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1685  workset.round=DEC_ROUND_FLOOR;
1686  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1687  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1688  if (status!=0) decStatus(res, status, set);
1689  return res;
1690  } /* decNumberNextMinus  */
1691
1692/* ------------------------------------------------------------------ */
1693/* decNumberNextPlus -- next towards +Infinity                        */
1694/*                                                                    */
1695/*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1696/*                                                                    */
1697/*   res is C, the result.  C may be A                                */
1698/*   rhs is A                                                         */
1699/*   set is the context                                               */
1700/*                                                                    */
1701/* This is a generalization of 754 NextUp.                            */
1702/* ------------------------------------------------------------------ */
1703U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1704                              decContext *set) {
1705  decNumber dtiny;                           /* constant  */
1706  decContext workset=*set;                   /* work  */
1707  uInt status=0;                             /* accumulator  */
1708  #if DECCHECK
1709  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1710  #endif
1711
1712  /* -Infinity is the special case  */
1713  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1714    decSetMaxValue(res, set);
1715    res->bits=DECNEG;                        /* negative  */
1716    /* there is no status to set  */
1717    return res;
1718    }
1719  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1720  dtiny.lsu[0]=1;                            /* make number that is ..  */
1721  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1722  workset.round=DEC_ROUND_CEILING;
1723  decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1724  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1725  if (status!=0) decStatus(res, status, set);
1726  return res;
1727  } /* decNumberNextPlus  */
1728
1729/* ------------------------------------------------------------------ */
1730/* decNumberNextToward -- next towards rhs                            */
1731/*                                                                    */
1732/*   This computes C = A +/- infinitesimal, rounded towards           */
1733/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1734/*   modified during revision but dropped from 754-2008.              */
1735/*                                                                    */
1736/*   res is C, the result.  C may be A or B.                          */
1737/*   lhs is A                                                         */
1738/*   rhs is B                                                         */
1739/*   set is the context                                               */
1740/*                                                                    */
1741/* This is a generalization of 754-1985 NextAfter.                    */
1742/* ------------------------------------------------------------------ */
1743U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1744                                const decNumber *rhs, decContext *set) {
1745  decNumber dtiny;                           /* constant  */
1746  decContext workset=*set;                   /* work  */
1747  Int result;                                /* ..  */
1748  uInt status=0;                             /* accumulator  */
1749  #if DECCHECK
1750  if (decCheckOperands(res, lhs, rhs, set)) return res;
1751  #endif
1752
1753  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1754    decNaNs(res, lhs, rhs, set, &status);
1755    }
1756   else { /* Is numeric, so no chance of sNaN Invalid, etc.  */
1757    result=decCompare(lhs, rhs, 0);     /* sign matters  */
1758    if (result==BADINT) status|=DEC_Insufficient_storage; /* rare  */
1759     else { /* valid compare  */
1760      if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy  */
1761       else { /* differ: need NextPlus or NextMinus  */
1762        uByte sub;                      /* add or subtract  */
1763        if (result<0) {                 /* lhs<rhs, do nextplus  */
1764          /* -Infinity is the special case  */
1765          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1766            decSetMaxValue(res, set);
1767            res->bits=DECNEG;           /* negative  */
1768            return res;                 /* there is no status to set  */
1769            }
1770          workset.round=DEC_ROUND_CEILING;
1771          sub=0;                        /* add, please  */
1772          } /* plus  */
1773         else {                         /* lhs>rhs, do nextminus  */
1774          /* +Infinity is the special case  */
1775          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1776            decSetMaxValue(res, set);
1777            return res;                 /* there is no status to set  */
1778            }
1779          workset.round=DEC_ROUND_FLOOR;
1780          sub=DECNEG;                   /* subtract, please  */
1781          } /* minus  */
1782        uprv_decNumberZero(&dtiny);          /* start with 0  */
1783        dtiny.lsu[0]=1;                 /* make number that is ..  */
1784        dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest  */
1785        decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or -  */
1786        /* turn off exceptions if the result is a normal number  */
1787        /* (including Nmin), otherwise let all status through  */
1788        if (uprv_decNumberIsNormal(res, set)) status=0;
1789        } /* unequal  */
1790      } /* compare OK  */
1791    } /* numeric  */
1792  if (status!=0) decStatus(res, status, set);
1793  return res;
1794  } /* decNumberNextToward  */
1795
1796/* ------------------------------------------------------------------ */
1797/* decNumberOr -- OR two Numbers, digitwise                           */
1798/*                                                                    */
1799/*   This computes C = A | B                                          */
1800/*                                                                    */
1801/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1802/*   lhs is A                                                         */
1803/*   rhs is B                                                         */
1804/*   set is the context (used for result length and error report)     */
1805/*                                                                    */
1806/* C must have space for set->digits digits.                          */
1807/*                                                                    */
1808/* Logical function restrictions apply (see above); a NaN is          */
1809/* returned with Invalid_operation if a restriction is violated.      */
1810/* ------------------------------------------------------------------ */
1811U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1812                        const decNumber *rhs, decContext *set) {
1813  const Unit *ua, *ub;                  /* -> operands  */
1814  const Unit *msua, *msub;              /* -> operand msus  */
1815  Unit  *uc, *msuc;                     /* -> result and its msu  */
1816  Int   msudigs;                        /* digits in res msu  */
1817  #if DECCHECK
1818  if (decCheckOperands(res, lhs, rhs, set)) return res;
1819  #endif
1820
1821  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1822   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1823    decStatus(res, DEC_Invalid_operation, set);
1824    return res;
1825    }
1826  /* operands are valid  */
1827  ua=lhs->lsu;                          /* bottom-up  */
1828  ub=rhs->lsu;                          /* ..  */
1829  uc=res->lsu;                          /* ..  */
1830  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
1831  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1832  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1833  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1834  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
1835    Unit a, b;                          /* extract units  */
1836    if (ua>msua) a=0;
1837     else a=*ua;
1838    if (ub>msub) b=0;
1839     else b=*ub;
1840    *uc=0;                              /* can now write back  */
1841    if (a|b) {                          /* maybe 1 bits to examine  */
1842      Int i, j;
1843      /* This loop could be unrolled and/or use BIN2BCD tables  */
1844      for (i=0; i<DECDPUN; i++) {
1845        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR  */
1846        j=a%10;
1847        a=a/10;
1848        j|=b%10;
1849        b=b/10;
1850        if (j>1) {
1851          decStatus(res, DEC_Invalid_operation, set);
1852          return res;
1853          }
1854        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
1855        } /* each digit  */
1856      } /* non-zero  */
1857    } /* each unit  */
1858  /* [here uc-1 is the msu of the result]  */
1859  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1860  res->exponent=0;                      /* integer  */
1861  res->bits=0;                          /* sign=0  */
1862  return res;  /* [no status to set]  */
1863  } /* decNumberOr  */
1864
1865/* ------------------------------------------------------------------ */
1866/* decNumberPlus -- prefix plus operator                              */
1867/*                                                                    */
1868/*   This computes C = 0 + A                                          */
1869/*                                                                    */
1870/*   res is C, the result.  C may be A                                */
1871/*   rhs is A                                                         */
1872/*   set is the context                                               */
1873/*                                                                    */
1874/* See also decNumberCopy for a quiet bitwise version of this.        */
1875/* C must have space for set->digits digits.                          */
1876/* ------------------------------------------------------------------ */
1877/* This simply uses AddOp; Add will take fast path after preparing A. */
1878/* Performance is a concern here, as this routine is often used to    */
1879/* check operands and apply rounding and overflow/underflow testing.  */
1880/* ------------------------------------------------------------------ */
1881U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1882                          decContext *set) {
1883  decNumber dzero;
1884  uInt status=0;                        /* accumulator  */
1885  #if DECCHECK
1886  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1887  #endif
1888
1889  uprv_decNumberZero(&dzero);                /* make 0  */
1890  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1891  decAddOp(res, &dzero, rhs, set, 0, &status);
1892  if (status!=0) decStatus(res, status, set);
1893  #if DECCHECK
1894  decCheckInexact(res, set);
1895  #endif
1896  return res;
1897  } /* decNumberPlus  */
1898
1899/* ------------------------------------------------------------------ */
1900/* decNumberMultiply -- multiply two Numbers                          */
1901/*                                                                    */
1902/*   This computes C = A x B                                          */
1903/*                                                                    */
1904/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1905/*   lhs is A                                                         */
1906/*   rhs is B                                                         */
1907/*   set is the context                                               */
1908/*                                                                    */
1909/* C must have space for set->digits digits.                          */
1910/* ------------------------------------------------------------------ */
1911U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1912                              const decNumber *rhs, decContext *set) {
1913  uInt status=0;                   /* accumulator  */
1914  decMultiplyOp(res, lhs, rhs, set, &status);
1915  if (status!=0) decStatus(res, status, set);
1916  #if DECCHECK
1917  decCheckInexact(res, set);
1918  #endif
1919  return res;
1920  } /* decNumberMultiply  */
1921
1922/* ------------------------------------------------------------------ */
1923/* decNumberPower -- raise a number to a power                        */
1924/*                                                                    */
1925/*   This computes C = A ** B                                         */
1926/*                                                                    */
1927/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1928/*   lhs is A                                                         */
1929/*   rhs is B                                                         */
1930/*   set is the context                                               */
1931/*                                                                    */
1932/* C must have space for set->digits digits.                          */
1933/*                                                                    */
1934/* Mathematical function restrictions apply (see above); a NaN is     */
1935/* returned with Invalid_operation if a restriction is violated.      */
1936/*                                                                    */
1937/* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1938/* restrictions on A and the context are relaxed to the usual bounds, */
1939/* for compatibility with the earlier (integer power only) version    */
1940/* of this function.                                                  */
1941/*                                                                    */
1942/* When B is an integer, the result may be exact, even if rounded.    */
1943/*                                                                    */
1944/* The final result is rounded according to the context; it will      */
1945/* almost always be correctly rounded, but may be up to 1 ulp in      */
1946/* error in rare cases.                                               */
1947/* ------------------------------------------------------------------ */
1948U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1949                           const decNumber *rhs, decContext *set) {
1950  #if DECSUBSET
1951  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
1952  decNumber *allocrhs=NULL;        /* .., rhs  */
1953  #endif
1954  decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used  */
1955  decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used  */
1956  Int   reqdigits=set->digits;     /* requested DIGITS  */
1957  Int   n;                         /* rhs in binary  */
1958  Flag  rhsint=0;                  /* 1 if rhs is an integer  */
1959  Flag  useint=0;                  /* 1 if can use integer calculation  */
1960  Flag  isoddint=0;                /* 1 if rhs is an integer and odd  */
1961  Int   i;                         /* work  */
1962  #if DECSUBSET
1963  Int   dropped;                   /* ..  */
1964  #endif
1965  uInt  needbytes;                 /* buffer size needed  */
1966  Flag  seenbit;                   /* seen a bit while powering  */
1967  Int   residue=0;                 /* rounding residue  */
1968  uInt  status=0;                  /* accumulators  */
1969  uByte bits=0;                    /* result sign if errors  */
1970  decContext aset;                 /* working context  */
1971  decNumber dnOne;                 /* work value 1...  */
1972  /* local accumulator buffer [a decNumber, with digits+elength+1 digits]  */
1973  decNumber dacbuff[D2N(DECBUFFER+9)];
1974  decNumber *dac=dacbuff;          /* -> result accumulator  */
1975  /* same again for possible 1/lhs calculation  */
1976  decNumber invbuff[D2N(DECBUFFER+9)];
1977
1978  #if DECCHECK
1979  if (decCheckOperands(res, lhs, rhs, set)) return res;
1980  #endif
1981
1982  do {                             /* protect allocated storage  */
1983    #if DECSUBSET
1984    if (!set->extended) { /* reduce operands and set status, as needed  */
1985      if (lhs->digits>reqdigits) {
1986        alloclhs=decRoundOperand(lhs, set, &status);
1987        if (alloclhs==NULL) break;
1988        lhs=alloclhs;
1989        }
1990      if (rhs->digits>reqdigits) {
1991        allocrhs=decRoundOperand(rhs, set, &status);
1992        if (allocrhs==NULL) break;
1993        rhs=allocrhs;
1994        }
1995      }
1996    #endif
1997    /* [following code does not require input rounding]  */
1998
1999    /* handle NaNs and rhs Infinity (lhs infinity is harder)  */
2000    if (SPECIALARGS) {
2001      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs  */
2002        decNaNs(res, lhs, rhs, set, &status);
2003        break;}
2004      if (decNumberIsInfinite(rhs)) {   /* rhs Infinity  */
2005        Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign  */
2006        if (decNumberIsNegative(lhs)    /* lhs<0  */
2007         && !decNumberIsZero(lhs))      /* ..  */
2008          status|=DEC_Invalid_operation;
2009         else {                         /* lhs >=0  */
2010          uprv_decNumberZero(&dnOne);        /* set up 1  */
2011          dnOne.lsu[0]=1;
2012          uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1  */
2013          uprv_decNumberZero(res);           /* prepare for 0/1/Infinity  */
2014          if (decNumberIsNegative(dac)) {    /* lhs<1  */
2015            if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0]  */
2016            }
2017           else if (dac->lsu[0]==0) {        /* lhs=1  */
2018            /* 1**Infinity is inexact, so return fully-padded 1.0000  */
2019            Int shift=set->digits-1;
2020            *res->lsu=1;                     /* was 0, make int 1  */
2021            res->digits=decShiftToMost(res->lsu, 1, shift);
2022            res->exponent=-shift;            /* make 1.0000...  */
2023            status|=DEC_Inexact|DEC_Rounded; /* deemed inexact  */
2024            }
2025           else {                            /* lhs>1  */
2026            if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0]  */
2027            }
2028          } /* lhs>=0  */
2029        break;}
2030      /* [lhs infinity drops through]  */
2031      } /* specials  */
2032
2033    /* Original rhs may be an integer that fits and is in range  */
2034    n=decGetInt(rhs);
2035    if (n!=BADINT) {                    /* it is an integer  */
2036      rhsint=1;                         /* record the fact for 1**n  */
2037      isoddint=(Flag)n&1;               /* [works even if big]  */
2038      if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path?  */
2039        useint=1;                       /* looks good  */
2040      }
2041
2042    if (decNumberIsNegative(lhs)        /* -x ..  */
2043      && isoddint) bits=DECNEG;         /* .. to an odd power  */
2044
2045    /* handle LHS infinity  */
2046    if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled]  */
2047      uByte rbits=rhs->bits;            /* save  */
2048      uprv_decNumberZero(res);               /* prepare  */
2049      if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1  */
2050       else {
2051        /* -Inf**nonint -> error  */
2052        if (!rhsint && decNumberIsNegative(lhs)) {
2053          status|=DEC_Invalid_operation;     /* -Inf**nonint is error  */
2054          break;}
2055        if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n  */
2056        /* [otherwise will be 0 or -0]  */
2057        res->bits=bits;
2058        }
2059      break;}
2060
2061    /* similarly handle LHS zero  */
2062    if (decNumberIsZero(lhs)) {
2063      if (n==0) {                            /* 0**0 => Error  */
2064        #if DECSUBSET
2065        if (!set->extended) {                /* [unless subset]  */
2066          uprv_decNumberZero(res);
2067          *res->lsu=1;                       /* return 1  */
2068          break;}
2069        #endif
2070        status|=DEC_Invalid_operation;
2071        }
2072       else {                                /* 0**x  */
2073        uByte rbits=rhs->bits;               /* save  */
2074        if (rbits & DECNEG) {                /* was a 0**(-n)  */
2075          #if DECSUBSET
2076          if (!set->extended) {              /* [bad if subset]  */
2077            status|=DEC_Invalid_operation;
2078            break;}
2079          #endif
2080          bits|=DECINF;
2081          }
2082        uprv_decNumberZero(res);                  /* prepare  */
2083        /* [otherwise will be 0 or -0]  */
2084        res->bits=bits;
2085        }
2086      break;}
2087
2088    /* here both lhs and rhs are finite; rhs==0 is handled in the  */
2089    /* integer path.  Next handle the non-integer cases  */
2090    if (!useint) {                      /* non-integral rhs  */
2091      /* any -ve lhs is bad, as is either operand or context out of  */
2092      /* bounds  */
2093      if (decNumberIsNegative(lhs)) {
2094        status|=DEC_Invalid_operation;
2095        break;}
2096      if (decCheckMath(lhs, set, &status)
2097       || decCheckMath(rhs, set, &status)) break; /* variable status  */
2098
2099      uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
2100      aset.emax=DEC_MAX_MATH;           /* usual bounds  */
2101      aset.emin=-DEC_MAX_MATH;          /* ..  */
2102      aset.clamp=0;                     /* and no concrete format  */
2103
2104      /* calculate the result using exp(ln(lhs)*rhs), which can  */
2105      /* all be done into the accumulator, dac.  The precision needed  */
2106      /* is enough to contain the full information in the lhs (which  */
2107      /* is the total digits, including exponent), or the requested  */
2108      /* precision, if larger, + 4; 6 is used for the exponent  */
2109      /* maximum length, and this is also used when it is shorter  */
2110      /* than the requested digits as it greatly reduces the >0.5 ulp  */
2111      /* cases at little cost (because Ln doubles digits each  */
2112      /* iteration so a few extra digits rarely causes an extra  */
2113      /* iteration)  */
2114      aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2115      } /* non-integer rhs  */
2116
2117     else { /* rhs is in-range integer  */
2118      if (n==0) {                       /* x**0 = 1  */
2119        /* (0**0 was handled above)  */
2120        uprv_decNumberZero(res);             /* result=1  */
2121        *res->lsu=1;                    /* ..  */
2122        break;}
2123      /* rhs is a non-zero integer  */
2124      if (n<0) n=-n;                    /* use abs(n)  */
2125
2126      aset=*set;                        /* clone the context  */
2127      aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced  */
2128      /* calculate the working DIGITS  */
2129      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2130      #if DECSUBSET
2131      if (!set->extended) aset.digits--;     /* use classic precision  */
2132      #endif
2133      /* it's an error if this is more than can be handled  */
2134      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2135      } /* integer path  */
2136
2137    /* aset.digits is the count of digits for the accumulator needed  */
2138    /* if accumulator is too long for local storage, then allocate  */
2139    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2140    /* [needbytes also used below if 1/lhs needed]  */
2141    if (needbytes>sizeof(dacbuff)) {
2142      allocdac=(decNumber *)malloc(needbytes);
2143      if (allocdac==NULL) {   /* hopeless -- abandon  */
2144        status|=DEC_Insufficient_storage;
2145        break;}
2146      dac=allocdac;           /* use the allocated space  */
2147      }
2148    /* here, aset is set up and accumulator is ready for use  */
2149
2150    if (!useint) {                           /* non-integral rhs  */
2151      /* x ** y; special-case x=1 here as it will otherwise always  */
2152      /* reduce to integer 1; decLnOp has a fastpath which detects  */
2153      /* the case of x=1  */
2154      decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs)  */
2155      /* [no error possible, as lhs 0 already handled]  */
2156      if (ISZERO(dac)) {                     /* x==1, 1.0, etc.  */
2157        /* need to return fully-padded 1.0000 etc., but rhsint->1  */
2158        *dac->lsu=1;                         /* was 0, make int 1  */
2159        if (!rhsint) {                       /* add padding  */
2160          Int shift=set->digits-1;
2161          dac->digits=decShiftToMost(dac->lsu, 1, shift);
2162          dac->exponent=-shift;              /* make 1.0000...  */
2163          status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact  */
2164          }
2165        }
2166       else {
2167        decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs  */
2168        decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac)  */
2169        }
2170      /* and drop through for final rounding  */
2171      } /* non-integer rhs  */
2172
2173     else {                             /* carry on with integer  */
2174      uprv_decNumberZero(dac);               /* acc=1  */
2175      *dac->lsu=1;                      /* ..  */
2176
2177      /* if a negative power the constant 1 is needed, and if not subset  */
2178      /* invert the lhs now rather than inverting the result later  */
2179      if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0]  */
2180        decNumber *inv=invbuff;         /* asssume use fixed buffer  */
2181        uprv_decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later]  */
2182        #if DECSUBSET
2183        if (set->extended) {            /* need to calculate 1/lhs  */
2184        #endif
2185          /* divide lhs into 1, putting result in dac [dac=1/dac]  */
2186          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2187          /* now locate or allocate space for the inverted lhs  */
2188          if (needbytes>sizeof(invbuff)) {
2189            allocinv=(decNumber *)malloc(needbytes);
2190            if (allocinv==NULL) {       /* hopeless -- abandon  */
2191              status|=DEC_Insufficient_storage;
2192              break;}
2193            inv=allocinv;               /* use the allocated space  */
2194            }
2195          /* [inv now points to big-enough buffer or allocated storage]  */
2196          uprv_decNumberCopy(inv, dac);      /* copy the 1/lhs  */
2197          uprv_decNumberCopy(dac, &dnOne);   /* restore acc=1  */
2198          lhs=inv;                      /* .. and go forward with new lhs  */
2199        #if DECSUBSET
2200          }
2201        #endif
2202        }
2203
2204      /* Raise-to-the-power loop...  */
2205      seenbit=0;                   /* set once a 1-bit is encountered  */
2206      for (i=1;;i++){              /* for each bit [top bit ignored]  */
2207        /* abandon if had overflow or terminal underflow  */
2208        if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
2209          if (status&DEC_Overflow || ISZERO(dac)) break;
2210          }
2211        /* [the following two lines revealed an optimizer bug in a C++  */
2212        /* compiler, with symptom: 5**3 -> 25, when n=n+n was used]  */
2213        n=n<<1;                    /* move next bit to testable position  */
2214        if (n<0) {                 /* top bit is set  */
2215          seenbit=1;               /* OK, significant bit seen  */
2216          decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x  */
2217          }
2218        if (i==31) break;          /* that was the last bit  */
2219        if (!seenbit) continue;    /* no need to square 1  */
2220        decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square]  */
2221        } /*i*/ /* 32 bits  */
2222
2223      /* complete internal overflow or underflow processing  */
2224      if (status & (DEC_Overflow|DEC_Underflow)) {
2225        #if DECSUBSET
2226        /* If subset, and power was negative, reverse the kind of -erflow  */
2227        /* [1/x not yet done]  */
2228        if (!set->extended && decNumberIsNegative(rhs)) {
2229          if (status & DEC_Overflow)
2230            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2231           else { /* trickier -- Underflow may or may not be set  */
2232            status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both]  */
2233            status|=DEC_Overflow;
2234            }
2235          }
2236        #endif
2237        dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign  */
2238        /* round subnormals [to set.digits rather than aset.digits]  */
2239        /* or set overflow result similarly as required  */
2240        decFinalize(dac, set, &residue, &status);
2241        uprv_decNumberCopy(res, dac);   /* copy to result (is now OK length)  */
2242        break;
2243        }
2244
2245      #if DECSUBSET
2246      if (!set->extended &&                  /* subset math  */
2247          decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0]  */
2248        /* so divide result into 1 [dac=1/dac]  */
2249        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2250        }
2251      #endif
2252      } /* rhs integer path  */
2253
2254    /* reduce result to the requested length and copy to result  */
2255    decCopyFit(res, dac, set, &residue, &status);
2256    decFinish(res, set, &residue, &status);  /* final cleanup  */
2257    #if DECSUBSET
2258    if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros  */
2259    #endif
2260    } while(0);                         /* end protected  */
2261
2262  if (allocdac!=NULL) free(allocdac);   /* drop any storage used  */
2263  if (allocinv!=NULL) free(allocinv);   /* ..  */
2264  #if DECSUBSET
2265  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
2266  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
2267  #endif
2268  if (status!=0) decStatus(res, status, set);
2269  #if DECCHECK
2270  decCheckInexact(res, set);
2271  #endif
2272  return res;
2273  } /* decNumberPower  */
2274
2275/* ------------------------------------------------------------------ */
2276/* decNumberQuantize -- force exponent to requested value             */
2277/*                                                                    */
2278/*   This computes C = op(A, B), where op adjusts the coefficient     */
2279/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2280/*   of C has exponent of B.  The numerical value of C will equal A,  */
2281/*   except for the effects of any rounding that occurred.            */
2282/*                                                                    */
2283/*   res is C, the result.  C may be A or B                           */
2284/*   lhs is A, the number to adjust                                   */
2285/*   rhs is B, the number with exponent to match                      */
2286/*   set is the context                                               */
2287/*                                                                    */
2288/* C must have space for set->digits digits.                          */
2289/*                                                                    */
2290/* Unless there is an error or the result is infinite, the exponent   */
2291/* after the operation is guaranteed to be equal to that of B.        */
2292/* ------------------------------------------------------------------ */
2293U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2294                              const decNumber *rhs, decContext *set) {
2295  uInt status=0;                        /* accumulator  */
2296  decQuantizeOp(res, lhs, rhs, set, 1, &status);
2297  if (status!=0) decStatus(res, status, set);
2298  return res;
2299  } /* decNumberQuantize  */
2300
2301/* ------------------------------------------------------------------ */
2302/* decNumberReduce -- remove trailing zeros                           */
2303/*                                                                    */
2304/*   This computes C = 0 + A, and normalizes the result               */
2305/*                                                                    */
2306/*   res is C, the result.  C may be A                                */
2307/*   rhs is A                                                         */
2308/*   set is the context                                               */
2309/*                                                                    */
2310/* C must have space for set->digits digits.                          */
2311/* ------------------------------------------------------------------ */
2312/* Previously known as Normalize  */
2313U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2314                               decContext *set) {
2315  return uprv_decNumberReduce(res, rhs, set);
2316  } /* decNumberNormalize  */
2317
2318U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2319                            decContext *set) {
2320  #if DECSUBSET
2321  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2322  #endif
2323  uInt status=0;                   /* as usual  */
2324  Int  residue=0;                  /* as usual  */
2325  Int  dropped;                    /* work  */
2326
2327  #if DECCHECK
2328  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2329  #endif
2330
2331  do {                             /* protect allocated storage  */
2332    #if DECSUBSET
2333    if (!set->extended) {
2334      /* reduce operand and set lostDigits status, as needed  */
2335      if (rhs->digits>set->digits) {
2336        allocrhs=decRoundOperand(rhs, set, &status);
2337        if (allocrhs==NULL) break;
2338        rhs=allocrhs;
2339        }
2340      }
2341    #endif
2342    /* [following code does not require input rounding]  */
2343
2344    /* Infinities copy through; NaNs need usual treatment  */
2345    if (decNumberIsNaN(rhs)) {
2346      decNaNs(res, rhs, NULL, set, &status);
2347      break;
2348      }
2349
2350    /* reduce result to the requested length and copy to result  */
2351    decCopyFit(res, rhs, set, &residue, &status); /* copy & round  */
2352    decFinish(res, set, &residue, &status);       /* cleanup/set flags  */
2353    decTrim(res, set, 1, 0, &dropped);            /* normalize in place  */
2354                                                  /* [may clamp]  */
2355    } while(0);                              /* end protected  */
2356
2357  #if DECSUBSET
2358  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
2359  #endif
2360  if (status!=0) decStatus(res, status, set);/* then report status  */
2361  return res;
2362  } /* decNumberReduce  */
2363
2364/* ------------------------------------------------------------------ */
2365/* decNumberRescale -- force exponent to requested value              */
2366/*                                                                    */
2367/*   This computes C = op(A, B), where op adjusts the coefficient     */
2368/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2369/*   of C has the value B.  The numerical value of C will equal A,    */
2370/*   except for the effects of any rounding that occurred.            */
2371/*                                                                    */
2372/*   res is C, the result.  C may be A or B                           */
2373/*   lhs is A, the number to adjust                                   */
2374/*   rhs is B, the requested exponent                                 */
2375/*   set is the context                                               */
2376/*                                                                    */
2377/* C must have space for set->digits digits.                          */
2378/*                                                                    */
2379/* Unless there is an error or the result is infinite, the exponent   */
2380/* after the operation is guaranteed to be equal to B.                */
2381/* ------------------------------------------------------------------ */
2382U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2383                             const decNumber *rhs, decContext *set) {
2384  uInt status=0;                        /* accumulator  */
2385  decQuantizeOp(res, lhs, rhs, set, 0, &status);
2386  if (status!=0) decStatus(res, status, set);
2387  return res;
2388  } /* decNumberRescale  */
2389
2390/* ------------------------------------------------------------------ */
2391/* decNumberRemainder -- divide and return remainder                  */
2392/*                                                                    */
2393/*   This computes C = A % B                                          */
2394/*                                                                    */
2395/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2396/*   lhs is A                                                         */
2397/*   rhs is B                                                         */
2398/*   set is the context                                               */
2399/*                                                                    */
2400/* C must have space for set->digits digits.                          */
2401/* ------------------------------------------------------------------ */
2402U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2403                               const decNumber *rhs, decContext *set) {
2404  uInt status=0;                        /* accumulator  */
2405  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2406  if (status!=0) decStatus(res, status, set);
2407  #if DECCHECK
2408  decCheckInexact(res, set);
2409  #endif
2410  return res;
2411  } /* decNumberRemainder  */
2412
2413/* ------------------------------------------------------------------ */
2414/* decNumberRemainderNear -- divide and return remainder from nearest */
2415/*                                                                    */
2416/*   This computes C = A % B, where % is the IEEE remainder operator  */
2417/*                                                                    */
2418/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2419/*   lhs is A                                                         */
2420/*   rhs is B                                                         */
2421/*   set is the context                                               */
2422/*                                                                    */
2423/* C must have space for set->digits digits.                          */
2424/* ------------------------------------------------------------------ */
2425U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2426                                   const decNumber *rhs, decContext *set) {
2427  uInt status=0;                        /* accumulator  */
2428  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2429  if (status!=0) decStatus(res, status, set);
2430  #if DECCHECK
2431  decCheckInexact(res, set);
2432  #endif
2433  return res;
2434  } /* decNumberRemainderNear  */
2435
2436/* ------------------------------------------------------------------ */
2437/* decNumberRotate -- rotate the coefficient of a Number left/right   */
2438/*                                                                    */
2439/*   This computes C = A rot B  (in base ten and rotating set->digits */
2440/*   digits).                                                         */
2441/*                                                                    */
2442/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2443/*   lhs is A                                                         */
2444/*   rhs is B, the number of digits to rotate (-ve to right)          */
2445/*   set is the context                                               */
2446/*                                                                    */
2447/* The digits of the coefficient of A are rotated to the left (if B   */
2448/* is positive) or to the right (if B is negative) without adjusting  */
2449/* the exponent or the sign of A.  If lhs->digits is less than        */
2450/* set->digits the coefficient is padded with zeros on the left       */
2451/* before the rotate.  Any leading zeros in the result are removed    */
2452/* as usual.                                                          */
2453/*                                                                    */
2454/* B must be an integer (q=0) and in the range -set->digits through   */
2455/* +set->digits.                                                      */
2456/* C must have space for set->digits digits.                          */
2457/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2458/* B must be valid).  No status is set unless B is invalid or an      */
2459/* operand is an sNaN.                                                */
2460/* ------------------------------------------------------------------ */
2461U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2462                           const decNumber *rhs, decContext *set) {
2463  uInt status=0;              /* accumulator  */
2464  Int  rotate;                /* rhs as an Int  */
2465
2466  #if DECCHECK
2467  if (decCheckOperands(res, lhs, rhs, set)) return res;
2468  #endif
2469
2470  /* NaNs propagate as normal  */
2471  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2472    decNaNs(res, lhs, rhs, set, &status);
2473   /* rhs must be an integer  */
2474   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2475    status=DEC_Invalid_operation;
2476   else { /* both numeric, rhs is an integer  */
2477    rotate=decGetInt(rhs);                   /* [cannot fail]  */
2478    if (rotate==BADINT                       /* something bad ..  */
2479     || rotate==BIGODD || rotate==BIGEVEN    /* .. very big ..  */
2480     || abs(rotate)>set->digits)             /* .. or out of range  */
2481      status=DEC_Invalid_operation;
2482     else {                                  /* rhs is OK  */
2483      uprv_decNumberCopy(res, lhs);
2484      /* convert -ve rotate to equivalent positive rotation  */
2485      if (rotate<0) rotate=set->digits+rotate;
2486      if (rotate!=0 && rotate!=set->digits   /* zero or full rotation  */
2487       && !decNumberIsInfinite(res)) {       /* lhs was infinite  */
2488        /* left-rotate to do; 0 < rotate < set->digits  */
2489        uInt units, shift;                   /* work  */
2490        uInt msudigits;                      /* digits in result msu  */
2491        Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu  */
2492        Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu  */
2493        for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0  */
2494        res->digits=set->digits;                  /* now full-length  */
2495        msudigits=MSUDIGITS(res->digits);         /* actual digits in msu  */
2496
2497        /* rotation here is done in-place, in three steps  */
2498        /* 1. shift all to least up to one unit to unit-align final  */
2499        /*    lsd [any digits shifted out are rotated to the left,  */
2500        /*    abutted to the original msd (which may require split)]  */
2501        /*  */
2502        /*    [if there are no whole units left to rotate, the  */
2503        /*    rotation is now complete]  */
2504        /*  */
2505        /* 2. shift to least, from below the split point only, so that  */
2506        /*    the final msd is in the right place in its Unit [any  */
2507        /*    digits shifted out will fit exactly in the current msu,  */
2508        /*    left aligned, no split required]  */
2509        /*  */
2510        /* 3. rotate all the units by reversing left part, right  */
2511        /*    part, and then whole  */
2512        /*  */
2513        /* example: rotate right 8 digits (2 units + 2), DECDPUN=3.  */
2514        /*  */
2515        /*   start: 00a bcd efg hij klm npq  */
2516        /*  */
2517        /*      1a  000 0ab cde fgh|ijk lmn [pq saved]  */
2518        /*      1b  00p qab cde fgh|ijk lmn  */
2519        /*  */
2520        /*      2a  00p qab cde fgh|00i jkl [mn saved]  */
2521        /*      2b  mnp qab cde fgh|00i jkl  */
2522        /*  */
2523        /*      3a  fgh cde qab mnp|00i jkl  */
2524        /*      3b  fgh cde qab mnp|jkl 00i  */
2525        /*      3c  00i jkl mnp qab cde fgh  */
2526
2527        /* Step 1: amount to shift is the partial right-rotate count  */
2528        rotate=set->digits-rotate;      /* make it right-rotate  */
2529        units=rotate/DECDPUN;           /* whole units to rotate  */
2530        shift=rotate%DECDPUN;           /* left-over digits count  */
2531        if (shift>0) {                  /* not an exact number of units  */
2532          uInt save=res->lsu[0]%powers[shift];    /* save low digit(s)  */
2533          decShiftToLeast(res->lsu, D2U(res->digits), shift);
2534          if (shift>msudigits) {        /* msumax-1 needs >0 digits  */
2535            uInt rem=save%powers[shift-msudigits];/* split save  */
2536            *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert  */
2537            *(msumax-1)=*(msumax-1)
2538                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* ..  */
2539            }
2540           else { /* all fits in msumax  */
2541            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1]  */
2542            }
2543          } /* digits shift needed  */
2544
2545        /* If whole units to rotate...  */
2546        if (units>0) {                  /* some to do  */
2547          /* Step 2: the units to touch are the whole ones in rotate,  */
2548          /*   if any, and the shift is DECDPUN-msudigits (which may be  */
2549          /*   0, again)  */
2550          shift=DECDPUN-msudigits;
2551          if (shift>0) {                /* not an exact number of units  */
2552            uInt save=res->lsu[0]%powers[shift];  /* save low digit(s)  */
2553            decShiftToLeast(res->lsu, units, shift);
2554            *msumax=*msumax+(Unit)(save*powers[msudigits]);
2555            } /* partial shift needed  */
2556
2557          /* Step 3: rotate the units array using triple reverse  */
2558          /* (reversing is easy and fast)  */
2559          decReverse(res->lsu+units, msumax);     /* left part  */
2560          decReverse(res->lsu, res->lsu+units-1); /* right part  */
2561          decReverse(res->lsu, msumax);           /* whole  */
2562          } /* whole units to rotate  */
2563        /* the rotation may have left an undetermined number of zeros  */
2564        /* on the left, so true length needs to be calculated  */
2565        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2566        } /* rotate needed  */
2567      } /* rhs OK  */
2568    } /* numerics  */
2569  if (status!=0) decStatus(res, status, set);
2570  return res;
2571  } /* decNumberRotate  */
2572
2573/* ------------------------------------------------------------------ */
2574/* decNumberSameQuantum -- test for equal exponents                   */
2575/*                                                                    */
2576/*   res is the result number, which will contain either 0 or 1       */
2577/*   lhs is a number to test                                          */
2578/*   rhs is the second (usually a pattern)                            */
2579/*                                                                    */
2580/* No errors are possible and no context is needed.                   */
2581/* ------------------------------------------------------------------ */
2582U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2583                                 const decNumber *rhs) {
2584  Unit ret=0;                      /* return value  */
2585
2586  #if DECCHECK
2587  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2588  #endif
2589
2590  if (SPECIALARGS) {
2591    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2592     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2593     /* [anything else with a special gives 0]  */
2594    }
2595   else if (lhs->exponent==rhs->exponent) ret=1;
2596
2597  uprv_decNumberZero(res);              /* OK to overwrite an operand now  */
2598  *res->lsu=ret;
2599  return res;
2600  } /* decNumberSameQuantum  */
2601
2602/* ------------------------------------------------------------------ */
2603/* decNumberScaleB -- multiply by a power of 10                       */
2604/*                                                                    */
2605/* This computes C = A x 10**B where B is an integer (q=0) with       */
2606/* maximum magnitude 2*(emax+digits)                                  */
2607/*                                                                    */
2608/*   res is C, the result.  C may be A or B                           */
2609/*   lhs is A, the number to adjust                                   */
2610/*   rhs is B, the requested power of ten to use                      */
2611/*   set is the context                                               */
2612/*                                                                    */
2613/* C must have space for set->digits digits.                          */
2614/*                                                                    */
2615/* The result may underflow or overflow.                              */
2616/* ------------------------------------------------------------------ */
2617U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2618                            const decNumber *rhs, decContext *set) {
2619  Int  reqexp;                /* requested exponent change [B]  */
2620  uInt status=0;              /* accumulator  */
2621  Int  residue;               /* work  */
2622
2623  #if DECCHECK
2624  if (decCheckOperands(res, lhs, rhs, set)) return res;
2625  #endif
2626
2627  /* Handle special values except lhs infinite  */
2628  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2629    decNaNs(res, lhs, rhs, set, &status);
2630    /* rhs must be an integer  */
2631   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2632    status=DEC_Invalid_operation;
2633   else {
2634    /* lhs is a number; rhs is a finite with q==0  */
2635    reqexp=decGetInt(rhs);                   /* [cannot fail]  */
2636    if (reqexp==BADINT                       /* something bad ..  */
2637     || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big ..  */
2638     || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range  */
2639      status=DEC_Invalid_operation;
2640     else {                                  /* rhs is OK  */
2641      uprv_decNumberCopy(res, lhs);               /* all done if infinite lhs  */
2642      if (!decNumberIsInfinite(res)) {       /* prepare to scale  */
2643        res->exponent+=reqexp;               /* adjust the exponent  */
2644        residue=0;
2645        decFinalize(res, set, &residue, &status); /* .. and check  */
2646        } /* finite LHS  */
2647      } /* rhs OK  */
2648    } /* rhs finite  */
2649  if (status!=0) decStatus(res, status, set);
2650  return res;
2651  } /* decNumberScaleB  */
2652
2653/* ------------------------------------------------------------------ */
2654/* decNumberShift -- shift the coefficient of a Number left or right  */
2655/*                                                                    */
2656/*   This computes C = A << B or C = A >> -B  (in base ten).          */
2657/*                                                                    */
2658/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2659/*   lhs is A                                                         */
2660/*   rhs is B, the number of digits to shift (-ve to right)           */
2661/*   set is the context                                               */
2662/*                                                                    */
2663/* The digits of the coefficient of A are shifted to the left (if B   */
2664/* is positive) or to the right (if B is negative) without adjusting  */
2665/* the exponent or the sign of A.                                     */
2666/*                                                                    */
2667/* B must be an integer (q=0) and in the range -set->digits through   */
2668/* +set->digits.                                                      */
2669/* C must have space for set->digits digits.                          */
2670/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2671/* B must be valid).  No status is set unless B is invalid or an      */
2672/* operand is an sNaN.                                                */
2673/* ------------------------------------------------------------------ */
2674U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2675                           const decNumber *rhs, decContext *set) {
2676  uInt status=0;              /* accumulator  */
2677  Int  shift;                 /* rhs as an Int  */
2678
2679  #if DECCHECK
2680  if (decCheckOperands(res, lhs, rhs, set)) return res;
2681  #endif
2682
2683  /* NaNs propagate as normal  */
2684  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2685    decNaNs(res, lhs, rhs, set, &status);
2686   /* rhs must be an integer  */
2687   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2688    status=DEC_Invalid_operation;
2689   else { /* both numeric, rhs is an integer  */
2690    shift=decGetInt(rhs);                    /* [cannot fail]  */
2691    if (shift==BADINT                        /* something bad ..  */
2692     || shift==BIGODD || shift==BIGEVEN      /* .. very big ..  */
2693     || abs(shift)>set->digits)              /* .. or out of range  */
2694      status=DEC_Invalid_operation;
2695     else {                                  /* rhs is OK  */
2696      uprv_decNumberCopy(res, lhs);
2697      if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do  */
2698        if (shift>0) {                       /* to left  */
2699          if (shift==set->digits) {          /* removing all  */
2700            *res->lsu=0;                     /* so place 0  */
2701            res->digits=1;                   /* ..  */
2702            }
2703           else {                            /*  */
2704            /* first remove leading digits if necessary  */
2705            if (res->digits+shift>set->digits) {
2706              decDecap(res, res->digits+shift-set->digits);
2707              /* that updated res->digits; may have gone to 1 (for a  */
2708              /* single digit or for zero  */
2709              }
2710            if (res->digits>1 || *res->lsu)  /* if non-zero..  */
2711              res->digits=decShiftToMost(res->lsu, res->digits, shift);
2712            } /* partial left  */
2713          } /* left  */
2714         else { /* to right  */
2715          if (-shift>=res->digits) {         /* discarding all  */
2716            *res->lsu=0;                     /* so place 0  */
2717            res->digits=1;                   /* ..  */
2718            }
2719           else {
2720            decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2721            res->digits-=(-shift);
2722            }
2723          } /* to right  */
2724        } /* non-0 non-Inf shift  */
2725      } /* rhs OK  */
2726    } /* numerics  */
2727  if (status!=0) decStatus(res, status, set);
2728  return res;
2729  } /* decNumberShift  */
2730
2731/* ------------------------------------------------------------------ */
2732/* decNumberSquareRoot -- square root operator                        */
2733/*                                                                    */
2734/*   This computes C = squareroot(A)                                  */
2735/*                                                                    */
2736/*   res is C, the result.  C may be A                                */
2737/*   rhs is A                                                         */
2738/*   set is the context; note that rounding mode has no effect        */
2739/*                                                                    */
2740/* C must have space for set->digits digits.                          */
2741/* ------------------------------------------------------------------ */
2742/* This uses the following varying-precision algorithm in:            */
2743/*                                                                    */
2744/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2745/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2746/*   pp229-237, ACM, September 1985.                                  */
2747/*                                                                    */
2748/* The square-root is calculated using Newton's method, after which   */
2749/* a check is made to ensure the result is correctly rounded.         */
2750/*                                                                    */
2751/* % [Reformatted original Numerical Turing source code follows.]     */
2752/* function sqrt(x : real) : real                                     */
2753/* % sqrt(x) returns the properly rounded approximation to the square */
2754/* % root of x, in the precision of the calling environment, or it    */
2755/* % fails if x < 0.                                                  */
2756/* % t e hull and a abrham, august, 1984                              */
2757/* if x <= 0 then                                                     */
2758/*   if x < 0 then                                                    */
2759/*     assert false                                                   */
2760/*   else                                                             */
2761/*     result 0                                                       */
2762/*   end if                                                           */
2763/* end if                                                             */
2764/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2765/* var e := getexp(x)     % exponent part of x                        */
2766/* var approx : real                                                  */
2767/* if e mod 2 = 0  then                                               */
2768/*   approx := .259 + .819 * f   % approx to root of f                */
2769/* else                                                               */
2770/*   f := f/l0                   % adjustments                        */
2771/*   e := e + 1                  %   for odd                          */
2772/*   approx := .0819 + 2.59 * f  %   exponent                         */
2773/* end if                                                             */
2774/*                                                                    */
2775/* var p:= 3                                                          */
2776/* const maxp := currentprecision + 2                                 */
2777/* loop                                                               */
2778/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2779/*   precision p                                                      */
2780/*   approx := .5 * (approx + f/approx)                               */
2781/*   exit when p = maxp                                               */
2782/* end loop                                                           */
2783/*                                                                    */
2784/* % approx is now within 1 ulp of the properly rounded square root   */
2785/* % of f; to ensure proper rounding, compare squares of (approx -    */
2786/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2787/* p := currentprecision                                              */
2788/* begin                                                              */
2789/*   precision p + 2                                                  */
2790/*   const approxsubhalf := approx - setexp(.5, -p)                   */
2791/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2792/*     approx := approx - setexp(.l, -p + 1)                          */
2793/*   else                                                             */
2794/*     const approxaddhalf := approx + setexp(.5, -p)                 */
2795/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2796/*       approx := approx + setexp(.l, -p + 1)                        */
2797/*     end if                                                         */
2798/*   end if                                                           */
2799/* end                                                                */
2800/* result setexp(approx, e div 2)  % fix exponent                     */
2801/* end sqrt                                                           */
2802/* ------------------------------------------------------------------ */
2803U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2804                                decContext *set) {
2805  decContext workset, approxset;   /* work contexts  */
2806  decNumber dzero;                 /* used for constant zero  */
2807  Int  maxp;                       /* largest working precision  */
2808  Int  workp;                      /* working precision  */
2809  Int  residue=0;                  /* rounding residue  */
2810  uInt status=0, ignore=0;         /* status accumulators  */
2811  uInt rstatus;                    /* ..  */
2812  Int  exp;                        /* working exponent  */
2813  Int  ideal;                      /* ideal (preferred) exponent  */
2814  Int  needbytes;                  /* work  */
2815  Int  dropped;                    /* ..  */
2816
2817  #if DECSUBSET
2818  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2819  #endif
2820  /* buffer for f [needs +1 in case DECBUFFER 0]  */
2821  decNumber buff[D2N(DECBUFFER+1)];
2822  /* buffer for a [needs +2 to match likely maxp]  */
2823  decNumber bufa[D2N(DECBUFFER+2)];
2824  /* buffer for temporary, b [must be same size as a]  */
2825  decNumber bufb[D2N(DECBUFFER+2)];
2826  decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated  */
2827  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
2828  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
2829  decNumber *f=buff;               /* reduced fraction  */
2830  decNumber *a=bufa;               /* approximation to result  */
2831  decNumber *b=bufb;               /* intermediate result  */
2832  /* buffer for temporary variable, up to 3 digits  */
2833  decNumber buft[D2N(3)];
2834  decNumber *t=buft;               /* up-to-3-digit constant or work  */
2835
2836  #if DECCHECK
2837  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2838  #endif
2839
2840  do {                             /* protect allocated storage  */
2841    #if DECSUBSET
2842    if (!set->extended) {
2843      /* reduce operand and set lostDigits status, as needed  */
2844      if (rhs->digits>set->digits) {
2845        allocrhs=decRoundOperand(rhs, set, &status);
2846        if (allocrhs==NULL) break;
2847        /* [Note: 'f' allocation below could reuse this buffer if  */
2848        /* used, but as this is rare they are kept separate for clarity.]  */
2849        rhs=allocrhs;
2850        }
2851      }
2852    #endif
2853    /* [following code does not require input rounding]  */
2854
2855    /* handle infinities and NaNs  */
2856    if (SPECIALARG) {
2857      if (decNumberIsInfinite(rhs)) {         /* an infinity  */
2858        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2859         else uprv_decNumberCopy(res, rhs);        /* +Infinity  */
2860        }
2861       else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
2862      break;
2863      }
2864
2865    /* calculate the ideal (preferred) exponent [floor(exp/2)]  */
2866    /* [It would be nicer to write: ideal=rhs->exponent>>1, but this  */
2867    /* generates a compiler warning.  Generated code is the same.]  */
2868    ideal=(rhs->exponent&~1)/2;         /* target  */
2869
2870    /* handle zeros  */
2871    if (ISZERO(rhs)) {
2872      uprv_decNumberCopy(res, rhs);          /* could be 0 or -0  */
2873      res->exponent=ideal;              /* use the ideal [safe]  */
2874      /* use decFinish to clamp any out-of-range exponent, etc.  */
2875      decFinish(res, set, &residue, &status);
2876      break;
2877      }
2878
2879    /* any other -x is an oops  */
2880    if (decNumberIsNegative(rhs)) {
2881      status|=DEC_Invalid_operation;
2882      break;
2883      }
2884
2885    /* space is needed for three working variables  */
2886    /*   f -- the same precision as the RHS, reduced to 0.01->0.99...  */
2887    /*   a -- Hull's approximation -- precision, when assigned, is  */
2888    /*        currentprecision+1 or the input argument precision,  */
2889    /*        whichever is larger (+2 for use as temporary)  */
2890    /*   b -- intermediate temporary result (same size as a)  */
2891    /* if any is too long for local storage, then allocate  */
2892    workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision  */
2893    workp=MAXI(workp, 7);                    /* at least 7 for low cases  */
2894    maxp=workp+2;                            /* largest working precision  */
2895
2896    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2897    if (needbytes>(Int)sizeof(buff)) {
2898      allocbuff=(decNumber *)malloc(needbytes);
2899      if (allocbuff==NULL) {  /* hopeless -- abandon  */
2900        status|=DEC_Insufficient_storage;
2901        break;}
2902      f=allocbuff;            /* use the allocated space  */
2903      }
2904    /* a and b both need to be able to hold a maxp-length number  */
2905    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2906    if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b]  */
2907      allocbufa=(decNumber *)malloc(needbytes);
2908      allocbufb=(decNumber *)malloc(needbytes);
2909      if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless  */
2910        status|=DEC_Insufficient_storage;
2911        break;}
2912      a=allocbufa;            /* use the allocated spaces  */
2913      b=allocbufb;            /* ..  */
2914      }
2915
2916    /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1  */
2917    uprv_decNumberCopy(f, rhs);
2918    exp=f->exponent+f->digits;               /* adjusted to Hull rules  */
2919    f->exponent=-(f->digits);                /* to range  */
2920
2921    /* set up working context  */
2922    uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2923    workset.emax=DEC_MAX_EMAX;
2924    workset.emin=DEC_MIN_EMIN;
2925
2926    /* [Until further notice, no error is possible and status bits  */
2927    /* (Rounded, etc.) should be ignored, not accumulated.]  */
2928
2929    /* Calculate initial approximation, and allow for odd exponent  */
2930    workset.digits=workp;                    /* p for initial calculation  */
2931    t->bits=0; t->digits=3;
2932    a->bits=0; a->digits=3;
2933    if ((exp & 1)==0) {                      /* even exponent  */
2934      /* Set t=0.259, a=0.819  */
2935      t->exponent=-3;
2936      a->exponent=-3;
2937      #if DECDPUN>=3
2938        t->lsu[0]=259;
2939        a->lsu[0]=819;
2940      #elif DECDPUN==2
2941        t->lsu[0]=59; t->lsu[1]=2;
2942        a->lsu[0]=19; a->lsu[1]=8;
2943      #else
2944        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2945        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2946      #endif
2947      }
2948     else {                                  /* odd exponent  */
2949      /* Set t=0.0819, a=2.59  */
2950      f->exponent--;                         /* f=f/10  */
2951      exp++;                                 /* e=e+1  */
2952      t->exponent=-4;
2953      a->exponent=-2;
2954      #if DECDPUN>=3
2955        t->lsu[0]=819;
2956        a->lsu[0]=259;
2957      #elif DECDPUN==2
2958        t->lsu[0]=19; t->lsu[1]=8;
2959        a->lsu[0]=59; a->lsu[1]=2;
2960      #else
2961        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2962        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2963      #endif
2964      }
2965
2966    decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f  */
2967    decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t  */
2968    /* [a is now the initial approximation for sqrt(f), calculated with  */
2969    /* currentprecision, which is also a's precision.]  */
2970
2971    /* the main calculation loop  */
2972    uprv_decNumberZero(&dzero);                   /* make 0  */
2973    uprv_decNumberZero(t);                        /* set t = 0.5  */
2974    t->lsu[0]=5;                             /* ..  */
2975    t->exponent=-1;                          /* ..  */
2976    workset.digits=3;                        /* initial p  */
2977    for (; workset.digits<maxp;) {
2978      /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]  */
2979      workset.digits=MINI(workset.digits*2-2, maxp);
2980      /* a = 0.5 * (a + f/a)  */
2981      /* [calculated at p then rounded to currentprecision]  */
2982      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a  */
2983      decAddOp(b, b, a, &workset, 0, &ignore);         /* b=b+a  */
2984      decMultiplyOp(a, b, t, &workset, &ignore);       /* a=b*0.5  */
2985      } /* loop  */
2986
2987    /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits  */
2988    /* now reduce to length, etc.; this needs to be done with a  */
2989    /* having the correct exponent so as to handle subnormals  */
2990    /* correctly  */
2991    approxset=*set;                          /* get emin, emax, etc.  */
2992    approxset.round=DEC_ROUND_HALF_EVEN;
2993    a->exponent+=exp/2;                      /* set correct exponent  */
2994    rstatus=0;                               /* clear status  */
2995    residue=0;                               /* .. and accumulator  */
2996    decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed)  */
2997    decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize  */
2998
2999    /* Overflow was possible if the input exponent was out-of-range,  */
3000    /* in which case quit  */
3001    if (rstatus&DEC_Overflow) {
3002      status=rstatus;                        /* use the status as-is  */
3003      uprv_decNumberCopy(res, a);                 /* copy to result  */
3004      break;
3005      }
3006
3007    /* Preserve status except Inexact/Rounded  */
3008    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3009
3010    /* Carry out the Hull correction  */
3011    a->exponent-=exp/2;                      /* back to 0.1->1  */
3012
3013    /* a is now at final precision and within 1 ulp of the properly  */
3014    /* rounded square root of f; to ensure proper rounding, compare  */
3015    /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f.  */
3016    /* Here workset.digits=maxp and t=0.5, and a->digits determines  */
3017    /* the ulp  */
3018    workset.digits--;                             /* maxp-1 is OK now  */
3019    t->exponent=-a->digits-1;                     /* make 0.5 ulp  */
3020    decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp  */
3021    workset.round=DEC_ROUND_UP;
3022    decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b)  */
3023    decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed  */
3024    if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f]  */
3025      /* this is the more common adjustment, though both are rare  */
3026      t->exponent++;                              /* make 1.0 ulp  */
3027      t->lsu[0]=1;                                /* ..  */
3028      decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp  */
3029      /* assign to approx [round to length]  */
3030      approxset.emin-=exp/2;                      /* adjust to match a  */
3031      approxset.emax-=exp/2;
3032      decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3033      }
3034     else {
3035      decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp  */
3036      workset.round=DEC_ROUND_DOWN;
3037      decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b)  */
3038      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f  */
3039      if (decNumberIsNegative(b)) {               /* b < f  */
3040        t->exponent++;                            /* make 1.0 ulp  */
3041        t->lsu[0]=1;                              /* ..  */
3042        decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp  */
3043        /* assign to approx [round to length]  */
3044        approxset.emin-=exp/2;                    /* adjust to match a  */
3045        approxset.emax-=exp/2;
3046        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3047        }
3048      }
3049    /* [no errors are possible in the above, and rounding/inexact during  */
3050    /* estimation are irrelevant, so status was not accumulated]  */
3051
3052    /* Here, 0.1 <= a < 1  (still), so adjust back  */
3053    a->exponent+=exp/2;                      /* set correct exponent  */
3054
3055    /* count droppable zeros [after any subnormal rounding] by  */
3056    /* trimming a copy  */
3057    uprv_decNumberCopy(b, a);
3058    decTrim(b, set, 1, 1, &dropped);         /* [drops trailing zeros]  */
3059
3060    /* Set Inexact and Rounded.  The answer can only be exact if  */
3061    /* it is short enough so that squaring it could fit in workp  */
3062    /* digits, so this is the only (relatively rare) condition that  */
3063    /* a careful check is needed  */
3064    if (b->digits*2-1 > workp) {             /* cannot fit  */
3065      status|=DEC_Inexact|DEC_Rounded;
3066      }
3067     else {                                  /* could be exact/unrounded  */
3068      uInt mstatus=0;                        /* local status  */
3069      decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply  */
3070      if (mstatus&DEC_Overflow) {            /* result just won't fit  */
3071        status|=DEC_Inexact|DEC_Rounded;
3072        }
3073       else {                                /* plausible  */
3074        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs  */
3075        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal  */
3076         else {                              /* is Exact  */
3077          /* here, dropped is the count of trailing zeros in 'a'  */
3078          /* use closest exponent to ideal...  */
3079          Int todrop=ideal-a->exponent;      /* most that can be dropped  */
3080          if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s  */
3081           else {                            /* unrounded  */
3082            /* there are some to drop, but emax may not allow all  */
3083            Int maxexp=set->emax-set->digits+1;
3084            Int maxdrop=maxexp-a->exponent;
3085            if (todrop>maxdrop && set->clamp) { /* apply clamping  */
3086              todrop=maxdrop;
3087              status|=DEC_Clamped;
3088              }
3089            if (dropped<todrop) {            /* clamp to those available  */
3090              todrop=dropped;
3091              status|=DEC_Clamped;
3092              }
3093            if (todrop>0) {                  /* have some to drop  */
3094              decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3095              a->exponent+=todrop;           /* maintain numerical value  */
3096              a->digits-=todrop;             /* new length  */
3097              }
3098            }
3099          }
3100        }
3101      }
3102
3103    /* double-check Underflow, as perhaps the result could not have  */
3104    /* been subnormal (initial argument too big), or it is now Exact  */
3105    if (status&DEC_Underflow) {
3106      Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent  */
3107      /* check if truly subnormal  */
3108      #if DECEXTFLAG                         /* DEC_Subnormal too  */
3109        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3110      #else
3111        if (ae>=set->emin*2) status&=~DEC_Underflow;
3112      #endif
3113      /* check if truly inexact  */
3114      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3115      }
3116
3117    uprv_decNumberCopy(res, a);                   /* a is now the result  */
3118    } while(0);                              /* end protected  */
3119
3120  if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used  */
3121  if (allocbufa!=NULL) free(allocbufa);      /* ..  */
3122  if (allocbufb!=NULL) free(allocbufb);      /* ..  */
3123  #if DECSUBSET
3124  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
3125  #endif
3126  if (status!=0) decStatus(res, status, set);/* then report status  */
3127  #if DECCHECK
3128  decCheckInexact(res, set);
3129  #endif
3130  return res;
3131  } /* decNumberSquareRoot  */
3132
3133/* ------------------------------------------------------------------ */
3134/* decNumberSubtract -- subtract two Numbers                          */
3135/*                                                                    */
3136/*   This computes C = A - B                                          */
3137/*                                                                    */
3138/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3139/*   lhs is A                                                         */
3140/*   rhs is B                                                         */
3141/*   set is the context                                               */
3142/*                                                                    */
3143/* C must have space for set->digits digits.                          */
3144/* ------------------------------------------------------------------ */
3145U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3146                              const decNumber *rhs, decContext *set) {
3147  uInt status=0;                        /* accumulator  */
3148
3149  decAddOp(res, lhs, rhs, set, DECNEG, &status);
3150  if (status!=0) decStatus(res, status, set);
3151  #if DECCHECK
3152  decCheckInexact(res, set);
3153  #endif
3154  return res;
3155  } /* decNumberSubtract  */
3156
3157/* ------------------------------------------------------------------ */
3158/* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3159/* decNumberToIntegralValue -- round-to-integral-value                */
3160/*                                                                    */
3161/*   res is the result                                                */
3162/*   rhs is input number                                              */
3163/*   set is the context                                               */
3164/*                                                                    */
3165/* res must have space for any value of rhs.                          */
3166/*                                                                    */
3167/* This implements the IEEE special operators and therefore treats    */
3168/* special values as valid.  For finite numbers it returns            */
3169/* rescale(rhs, 0) if rhs->exponent is <0.                            */
3170/* Otherwise the result is rhs (so no error is possible, except for   */
3171/* sNaN).                                                             */
3172/*                                                                    */
3173/* The context is used for rounding mode and status after sNaN, but   */
3174/* the digits setting is ignored.  The Exact version will signal      */
3175/* Inexact if the result differs numerically from rhs; the other      */
3176/* never signals Inexact.                                             */
3177/* ------------------------------------------------------------------ */
3178U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3179                                     decContext *set) {
3180  decNumber dn;
3181  decContext workset;              /* working context  */
3182  uInt status=0;                   /* accumulator  */
3183
3184  #if DECCHECK
3185  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3186  #endif
3187
3188  /* handle infinities and NaNs  */
3189  if (SPECIALARG) {
3190    if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity  */
3191     else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
3192    }
3193   else { /* finite  */
3194    /* have a finite number; no error possible (res must be big enough)  */
3195    if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3196    /* that was easy, but if negative exponent there is work to do...  */
3197    workset=*set;                  /* clone rounding, etc.  */
3198    workset.digits=rhs->digits;    /* no length rounding  */
3199    workset.traps=0;               /* no traps  */
3200    uprv_decNumberZero(&dn);            /* make a number with exponent 0  */
3201    uprv_decNumberQuantize(res, rhs, &dn, &workset);
3202    status|=workset.status;
3203    }
3204  if (status!=0) decStatus(res, status, set);
3205  return res;
3206  } /* decNumberToIntegralExact  */
3207
3208U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3209                                     decContext *set) {
3210  decContext workset=*set;         /* working context  */
3211  workset.traps=0;                 /* no traps  */
3212  uprv_decNumberToIntegralExact(res, rhs, &workset);
3213  /* this never affects set, except for sNaNs; NaN will have been set  */
3214  /* or propagated already, so no need to call decStatus  */
3215  set->status|=workset.status&DEC_Invalid_operation;
3216  return res;
3217  } /* decNumberToIntegralValue  */
3218
3219/* ------------------------------------------------------------------ */
3220/* decNumberXor -- XOR two Numbers, digitwise                         */
3221/*                                                                    */
3222/*   This computes C = A ^ B                                          */
3223/*                                                                    */
3224/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3225/*   lhs is A                                                         */
3226/*   rhs is B                                                         */
3227/*   set is the context (used for result length and error report)     */
3228/*                                                                    */
3229/* C must have space for set->digits digits.                          */
3230/*                                                                    */
3231/* Logical function restrictions apply (see above); a NaN is          */
3232/* returned with Invalid_operation if a restriction is violated.      */
3233/* ------------------------------------------------------------------ */
3234U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3235                         const decNumber *rhs, decContext *set) {
3236  const Unit *ua, *ub;                  /* -> operands  */
3237  const Unit *msua, *msub;              /* -> operand msus  */
3238  Unit  *uc, *msuc;                     /* -> result and its msu  */
3239  Int   msudigs;                        /* digits in res msu  */
3240  #if DECCHECK
3241  if (decCheckOperands(res, lhs, rhs, set)) return res;
3242  #endif
3243
3244  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3245   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3246    decStatus(res, DEC_Invalid_operation, set);
3247    return res;
3248    }
3249  /* operands are valid  */
3250  ua=lhs->lsu;                          /* bottom-up  */
3251  ub=rhs->lsu;                          /* ..  */
3252  uc=res->lsu;                          /* ..  */
3253  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
3254  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
3255  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
3256  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
3257  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
3258    Unit a, b;                          /* extract units  */
3259    if (ua>msua) a=0;
3260     else a=*ua;
3261    if (ub>msub) b=0;
3262     else b=*ub;
3263    *uc=0;                              /* can now write back  */
3264    if (a|b) {                          /* maybe 1 bits to examine  */
3265      Int i, j;
3266      /* This loop could be unrolled and/or use BIN2BCD tables  */
3267      for (i=0; i<DECDPUN; i++) {
3268        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR  */
3269        j=a%10;
3270        a=a/10;
3271        j|=b%10;
3272        b=b/10;
3273        if (j>1) {
3274          decStatus(res, DEC_Invalid_operation, set);
3275          return res;
3276          }
3277        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
3278        } /* each digit  */
3279      } /* non-zero  */
3280    } /* each unit  */
3281  /* [here uc-1 is the msu of the result]  */
3282  res->digits=decGetDigits(res->lsu, uc-res->lsu);
3283  res->exponent=0;                      /* integer  */
3284  res->bits=0;                          /* sign=0  */
3285  return res;  /* [no status to set]  */
3286  } /* decNumberXor  */
3287
3288
3289/* ================================================================== */
3290/* Utility routines                                                   */
3291/* ================================================================== */
3292
3293/* ------------------------------------------------------------------ */
3294/* decNumberClass -- return the decClass of a decNumber               */
3295/*   dn -- the decNumber to test                                      */
3296/*   set -- the context to use for Emin                               */
3297/*   returns the decClass enum                                        */
3298/* ------------------------------------------------------------------ */
3299enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3300  if (decNumberIsSpecial(dn)) {
3301    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3302    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3303    /* must be an infinity  */
3304    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3305    return DEC_CLASS_POS_INF;
3306    }
3307  /* is finite  */
3308  if (uprv_decNumberIsNormal(dn, set)) { /* most common  */
3309    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3310    return DEC_CLASS_POS_NORMAL;
3311    }
3312  /* is subnormal or zero  */
3313  if (decNumberIsZero(dn)) {    /* most common  */
3314    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3315    return DEC_CLASS_POS_ZERO;
3316    }
3317  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3318  return DEC_CLASS_POS_SUBNORMAL;
3319  } /* decNumberClass  */
3320
3321/* ------------------------------------------------------------------ */
3322/* decNumberClassToString -- convert decClass to a string             */
3323/*                                                                    */
3324/*  eclass is a valid decClass                                        */
3325/*  returns a constant string describing the class (max 13+1 chars)   */
3326/* ------------------------------------------------------------------ */
3327const char *uprv_decNumberClassToString(enum decClass eclass) {
3328  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3329  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3330  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3331  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3332  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3333  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3334  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3335  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3336  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3337  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3338  return DEC_ClassString_UN;           /* Unknown  */
3339  } /* decNumberClassToString  */
3340
3341/* ------------------------------------------------------------------ */
3342/* decNumberCopy -- copy a number                                     */
3343/*                                                                    */
3344/*   dest is the target decNumber                                     */
3345/*   src  is the source decNumber                                     */
3346/*   returns dest                                                     */
3347/*                                                                    */
3348/* (dest==src is allowed and is a no-op)                              */
3349/* All fields are updated as required.  This is a utility operation,  */
3350/* so special values are unchanged and no error is possible.          */
3351/* ------------------------------------------------------------------ */
3352U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3353
3354  #if DECCHECK
3355  if (src==NULL) return uprv_decNumberZero(dest);
3356  #endif
3357
3358  if (dest==src) return dest;                /* no copy required  */
3359
3360  /* Use explicit assignments here as structure assignment could copy  */
3361  /* more than just the lsu (for small DECDPUN).  This would not affect  */
3362  /* the value of the results, but could disturb test harness spill  */
3363  /* checking.  */
3364  dest->bits=src->bits;
3365  dest->exponent=src->exponent;
3366  dest->digits=src->digits;
3367  dest->lsu[0]=src->lsu[0];
3368  if (src->digits>DECDPUN) {                 /* more Units to come  */
3369    const Unit *smsup, *s;                   /* work  */
3370    Unit  *d;                                /* ..  */
3371    /* memcpy for the remaining Units would be safe as they cannot  */
3372    /* overlap.  However, this explicit loop is faster in short cases.  */
3373    d=dest->lsu+1;                           /* -> first destination  */
3374    smsup=src->lsu+D2U(src->digits);         /* -> source msu+1  */
3375    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3376    }
3377  return dest;
3378  } /* decNumberCopy  */
3379
3380/* ------------------------------------------------------------------ */
3381/* decNumberCopyAbs -- quiet absolute value operator                  */
3382/*                                                                    */
3383/*   This sets C = abs(A)                                             */
3384/*                                                                    */
3385/*   res is C, the result.  C may be A                                */
3386/*   rhs is A                                                         */
3387/*                                                                    */
3388/* C must have space for set->digits digits.                          */
3389/* No exception or error can occur; this is a quiet bitwise operation.*/
3390/* See also decNumberAbs for a checking version of this.              */
3391/* ------------------------------------------------------------------ */
3392U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3393  #if DECCHECK
3394  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3395  #endif
3396  uprv_decNumberCopy(res, rhs);
3397  res->bits&=~DECNEG;                   /* turn off sign  */
3398  return res;
3399  } /* decNumberCopyAbs  */
3400
3401/* ------------------------------------------------------------------ */
3402/* decNumberCopyNegate -- quiet negate value operator                 */
3403/*                                                                    */
3404/*   This sets C = negate(A)                                          */
3405/*                                                                    */
3406/*   res is C, the result.  C may be A                                */
3407/*   rhs is A                                                         */
3408/*                                                                    */
3409/* C must have space for set->digits digits.                          */
3410/* No exception or error can occur; this is a quiet bitwise operation.*/
3411/* See also decNumberMinus for a checking version of this.            */
3412/* ------------------------------------------------------------------ */
3413U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3414  #if DECCHECK
3415  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3416  #endif
3417  uprv_decNumberCopy(res, rhs);
3418  res->bits^=DECNEG;                    /* invert the sign  */
3419  return res;
3420  } /* decNumberCopyNegate  */
3421
3422/* ------------------------------------------------------------------ */
3423/* decNumberCopySign -- quiet copy and set sign operator              */
3424/*                                                                    */
3425/*   This sets C = A with the sign of B                               */
3426/*                                                                    */
3427/*   res is C, the result.  C may be A                                */
3428/*   lhs is A                                                         */
3429/*   rhs is B                                                         */
3430/*                                                                    */
3431/* C must have space for set->digits digits.                          */
3432/* No exception or error can occur; this is a quiet bitwise operation.*/
3433/* ------------------------------------------------------------------ */
3434U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3435                              const decNumber *rhs) {
3436  uByte sign;                           /* rhs sign  */
3437  #if DECCHECK
3438  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3439  #endif
3440  sign=rhs->bits & DECNEG;              /* save sign bit  */
3441  uprv_decNumberCopy(res, lhs);
3442  res->bits&=~DECNEG;                   /* clear the sign  */
3443  res->bits|=sign;                      /* set from rhs  */
3444  return res;
3445  } /* decNumberCopySign  */
3446
3447/* ------------------------------------------------------------------ */
3448/* decNumberGetBCD -- get the coefficient in BCD8                     */
3449/*   dn is the source decNumber                                       */
3450/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3451/*     most-significant at offset 0                                   */
3452/*   returns bcd                                                      */
3453/*                                                                    */
3454/* bcd must have at least dn->digits bytes.  No error is possible; if */
3455/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3456/* ------------------------------------------------------------------ */
3457U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3458  uByte *ub=bcd+dn->digits-1;      /* -> lsd  */
3459  const Unit *up=dn->lsu;          /* Unit pointer, -> lsu  */
3460
3461  #if DECDPUN==1                   /* trivial simple copy  */
3462    for (; ub>=bcd; ub--, up++) *ub=*up;
3463  #else                            /* chopping needed  */
3464    uInt u=*up;                    /* work  */
3465    uInt cut=DECDPUN;              /* downcounter through unit  */
3466    for (; ub>=bcd; ub--) {
3467      *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here]  */
3468      u=u/10;
3469      cut--;
3470      if (cut>0) continue;         /* more in this unit  */
3471      up++;
3472      u=*up;
3473      cut=DECDPUN;
3474      }
3475  #endif
3476  return bcd;
3477  } /* decNumberGetBCD  */
3478
3479/* ------------------------------------------------------------------ */
3480/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3481/*   dn is the target decNumber                                       */
3482/*   bcd is the uInt array that will source n BCD bytes, most-        */
3483/*     significant at offset 0                                        */
3484/*   n is the number of digits in the source BCD array (bcd)          */
3485/*   returns dn                                                       */
3486/*                                                                    */
3487/* dn must have space for at least n digits.  No error is possible;   */
3488/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3489/* and bcd[0] zero.                                                   */
3490/* ------------------------------------------------------------------ */
3491U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3492  Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer]  */
3493  const uByte *ub=bcd;                  /* -> source msd  */
3494
3495  #if DECDPUN==1                        /* trivial simple copy  */
3496    for (; ub<bcd+n; ub++, up--) *up=*ub;
3497  #else                                 /* some assembly needed  */
3498    /* calculate how many digits in msu, and hence first cut  */
3499    Int cut=MSUDIGITS(n);               /* [faster than remainder]  */
3500    for (;up>=dn->lsu; up--) {          /* each Unit from msu  */
3501      *up=0;                            /* will take <=DECDPUN digits  */
3502      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3503      cut=DECDPUN;                      /* next Unit has all digits  */
3504      }
3505  #endif
3506  dn->digits=n;                         /* set digit count  */
3507  return dn;
3508  } /* decNumberSetBCD  */
3509
3510/* ------------------------------------------------------------------ */
3511/* decNumberIsNormal -- test normality of a decNumber                 */
3512/*   dn is the decNumber to test                                      */
3513/*   set is the context to use for Emin                               */
3514/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3515/* ------------------------------------------------------------------ */
3516Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3517  Int ae;                               /* adjusted exponent  */
3518  #if DECCHECK
3519  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3520  #endif
3521
3522  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3523  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3524
3525  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3526  if (ae<set->emin) return 0;           /* is subnormal  */
3527  return 1;
3528  } /* decNumberIsNormal  */
3529
3530/* ------------------------------------------------------------------ */
3531/* decNumberIsSubnormal -- test subnormality of a decNumber           */
3532/*   dn is the decNumber to test                                      */
3533/*   set is the context to use for Emin                               */
3534/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3535/* ------------------------------------------------------------------ */
3536Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3537  Int ae;                               /* adjusted exponent  */
3538  #if DECCHECK
3539  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3540  #endif
3541
3542  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3543  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3544
3545  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3546  if (ae<set->emin) return 1;           /* is subnormal  */
3547  return 0;
3548  } /* decNumberIsSubnormal  */
3549
3550/* ------------------------------------------------------------------ */
3551/* decNumberTrim -- remove insignificant zeros                        */
3552/*                                                                    */
3553/*   dn is the number to trim                                         */
3554/*   returns dn                                                       */
3555/*                                                                    */
3556/* All fields are updated as required.  This is a utility operation,  */
3557/* so special values are unchanged and no error is possible.  The     */
3558/* zeros are removed unconditionally.                                 */
3559/* ------------------------------------------------------------------ */
3560U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3561  Int  dropped;                    /* work  */
3562  decContext set;                  /* ..  */
3563  #if DECCHECK
3564  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3565  #endif
3566  uprv_decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0  */
3567  return decTrim(dn, &set, 0, 1, &dropped);
3568  } /* decNumberTrim  */
3569
3570/* ------------------------------------------------------------------ */
3571/* decNumberVersion -- return the name and version of this module     */
3572/*                                                                    */
3573/* No error is possible.                                              */
3574/* ------------------------------------------------------------------ */
3575const char * uprv_decNumberVersion(void) {
3576  return DECVERSION;
3577  } /* decNumberVersion  */
3578
3579/* ------------------------------------------------------------------ */
3580/* decNumberZero -- set a number to 0                                 */
3581/*                                                                    */
3582/*   dn is the number to set, with space for one digit                */
3583/*   returns dn                                                       */
3584/*                                                                    */
3585/* No error is possible.                                              */
3586/* ------------------------------------------------------------------ */
3587/* Memset is not used as it is much slower in some environments.  */
3588U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3589
3590  #if DECCHECK
3591  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3592  #endif
3593
3594  dn->bits=0;
3595  dn->exponent=0;
3596  dn->digits=1;
3597  dn->lsu[0]=0;
3598  return dn;
3599  } /* decNumberZero  */
3600
3601/* ================================================================== */
3602/* Local routines                                                     */
3603/* ================================================================== */
3604
3605/* ------------------------------------------------------------------ */
3606/* decToString -- lay out a number into a string                      */
3607/*                                                                    */
3608/*   dn     is the number to lay out                                  */
3609/*   string is where to lay out the number                            */
3610/*   eng    is 1 if Engineering, 0 if Scientific                      */
3611/*                                                                    */
3612/* string must be at least dn->digits+14 characters long              */
3613/* No error is possible.                                              */
3614/*                                                                    */
3615/* Note that this routine can generate a -0 or 0.000.  These are      */
3616/* never generated in subset to-number or arithmetic, but can occur   */
3617/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3618/* ------------------------------------------------------------------ */
3619/* If DECCHECK is enabled the string "?" is returned if a number is  */
3620/* invalid.  */
3621static void decToString(const decNumber *dn, char *string, Flag eng) {
3622  Int exp=dn->exponent;       /* local copy  */
3623  Int e;                      /* E-part value  */
3624  Int pre;                    /* digits before the '.'  */
3625  Int cut;                    /* for counting digits in a Unit  */
3626  char *c=string;             /* work [output pointer]  */
3627  const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer]  */
3628  uInt u, pow;                /* work  */
3629
3630  #if DECCHECK
3631  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3632    strcpy(string, "?");
3633    return;}
3634  #endif
3635
3636  if (decNumberIsNegative(dn)) {   /* Negatives get a minus  */
3637    *c='-';
3638    c++;
3639    }
3640  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
3641    if (decNumberIsInfinite(dn)) {
3642      strcpy(c,   "Inf");
3643      strcpy(c+3, "inity");
3644      return;}
3645    /* a NaN  */
3646    if (dn->bits&DECSNAN) {        /* signalling NaN  */
3647      *c='s';
3648      c++;
3649      }
3650    strcpy(c, "NaN");
3651    c+=3;                          /* step past  */
3652    /* if not a clean non-zero coefficient, that's all there is in a  */
3653    /* NaN string  */
3654    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3655    /* [drop through to add integer]  */
3656    }
3657
3658  /* calculate how many digits in msu, and hence first cut  */
3659  cut=MSUDIGITS(dn->digits);       /* [faster than remainder]  */
3660  cut--;                           /* power of ten for digit  */
3661
3662  if (exp==0) {                    /* simple integer [common fastpath]  */
3663    for (;up>=dn->lsu; up--) {     /* each Unit from msu  */
3664      u=*up;                       /* contains DECDPUN digits to lay out  */
3665      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3666      cut=DECDPUN-1;               /* next Unit has all digits  */
3667      }
3668    *c='\0';                       /* terminate the string  */
3669    return;}
3670
3671  /* non-0 exponent -- assume plain form */
3672  pre=dn->digits+exp;              /* digits before '.'  */
3673  e=0;                             /* no E  */
3674  if ((exp>0) || (pre<-5)) {       /* need exponential form  */
3675    e=exp+dn->digits-1;            /* calculate E value  */
3676    pre=1;                         /* assume one digit before '.'  */
3677    if (eng && (e!=0)) {           /* engineering: may need to adjust  */
3678      Int adj;                     /* adjustment  */
3679      /* The C remainder operator is undefined for negative numbers, so  */
3680      /* a positive remainder calculation must be used here  */
3681      if (e<0) {
3682        adj=(-e)%3;
3683        if (adj!=0) adj=3-adj;
3684        }
3685       else { /* e>0  */
3686        adj=e%3;
3687        }
3688      e=e-adj;
3689      /* if dealing with zero still produce an exponent which is a  */
3690      /* multiple of three, as expected, but there will only be the  */
3691      /* one zero before the E, still.  Otherwise note the padding.  */
3692      if (!ISZERO(dn)) pre+=adj;
3693       else {  /* is zero  */
3694        if (adj!=0) {              /* 0.00Esnn needed  */
3695          e=e+3;
3696          pre=-(2-adj);
3697          }
3698        } /* zero  */
3699      } /* eng  */
3700    } /* need exponent  */
3701
3702  /* lay out the digits of the coefficient, adding 0s and . as needed */
3703  u=*up;
3704  if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form  */
3705    Int n=pre;
3706    for (; pre>0; pre--, c++, cut--) {
3707      if (cut<0) {                 /* need new Unit  */
3708        if (up==dn->lsu) break;    /* out of input digits (pre>digits)  */
3709        up--;
3710        cut=DECDPUN-1;
3711        u=*up;
3712        }
3713      TODIGIT(u, cut, c, pow);
3714      }
3715    if (n<dn->digits) {            /* more to come, after '.'  */
3716      *c='.'; c++;
3717      for (;; c++, cut--) {
3718        if (cut<0) {               /* need new Unit  */
3719          if (up==dn->lsu) break;  /* out of input digits  */
3720          up--;
3721          cut=DECDPUN-1;
3722          u=*up;
3723          }
3724        TODIGIT(u, cut, c, pow);
3725        }
3726      }
3727     else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed  */
3728    }
3729   else {                          /* 0.xxx or 0.000xxx form  */
3730    *c='0'; c++;
3731    *c='.'; c++;
3732    for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.'  */
3733    for (; ; c++, cut--) {
3734      if (cut<0) {                 /* need new Unit  */
3735        if (up==dn->lsu) break;    /* out of input digits  */
3736        up--;
3737        cut=DECDPUN-1;
3738        u=*up;
3739        }
3740      TODIGIT(u, cut, c, pow);
3741      }
3742    }
3743
3744  /* Finally add the E-part, if needed.  It will never be 0, has a
3745     base maximum and minimum of +999999999 through -999999999, but
3746     could range down to -1999999998 for anormal numbers */
3747  if (e!=0) {
3748    Flag had=0;               /* 1=had non-zero  */
3749    *c='E'; c++;
3750    *c='+'; c++;              /* assume positive  */
3751    u=e;                      /* ..  */
3752    if (e<0) {
3753      *(c-1)='-';             /* oops, need -  */
3754      u=-e;                   /* uInt, please  */
3755      }
3756    /* lay out the exponent [_itoa or equivalent is not ANSI C]  */
3757    for (cut=9; cut>=0; cut--) {
3758      TODIGIT(u, cut, c, pow);
3759      if (*c=='0' && !had) continue;    /* skip leading zeros  */
3760      had=1;                            /* had non-0  */
3761      c++;                              /* step for next  */
3762      } /* cut  */
3763    }
3764  *c='\0';          /* terminate the string (all paths)  */
3765  return;
3766  } /* decToString  */
3767
3768/* ------------------------------------------------------------------ */
3769/* decAddOp -- add/subtract operation                                 */
3770/*                                                                    */
3771/*   This computes C = A + B                                          */
3772/*                                                                    */
3773/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3774/*   lhs is A                                                         */
3775/*   rhs is B                                                         */
3776/*   set is the context                                               */
3777/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3778/*   status accumulates status for the caller                         */
3779/*                                                                    */
3780/* C must have space for set->digits digits.                          */
3781/* Inexact in status must be 0 for correct Exact zero sign in result  */
3782/* ------------------------------------------------------------------ */
3783/* If possible, the coefficient is calculated directly into C.        */
3784/* However, if:                                                       */
3785/*   -- a digits+1 calculation is needed because the numbers are      */
3786/*      unaligned and span more than set->digits digits               */
3787/*   -- a carry to digits+1 digits looks possible                     */
3788/*   -- C is the same as A or B, and the result would destructively   */
3789/*      overlap the A or B coefficient                                */
3790/* then the result must be calculated into a temporary buffer.  In    */
3791/* this case a local (stack) buffer is used if possible, and only if  */
3792/* too long for that does malloc become the final resort.             */
3793/*                                                                    */
3794/* Misalignment is handled as follows:                                */
3795/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3796/*   BPad: Apply the padding by a combination of shifting (whole      */
3797/*         units) and multiplication (part units).                    */
3798/*                                                                    */
3799/* Addition, especially x=x+1, is speed-critical.                     */
3800/* The static buffer is larger than might be expected to allow for    */
3801/* calls from higher-level funtions (notable exp).                    */
3802/* ------------------------------------------------------------------ */
3803static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3804                            const decNumber *rhs, decContext *set,
3805                            uByte negate, uInt *status) {
3806  #if DECSUBSET
3807  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
3808  decNumber *allocrhs=NULL;        /* .., rhs  */
3809  #endif
3810  Int   rhsshift;                  /* working shift (in Units)  */
3811  Int   maxdigits;                 /* longest logical length  */
3812  Int   mult;                      /* multiplier  */
3813  Int   residue;                   /* rounding accumulator  */
3814  uByte bits;                      /* result bits  */
3815  Flag  diffsign;                  /* non-0 if arguments have different sign  */
3816  Unit  *acc;                      /* accumulator for result  */
3817  Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many  */
3818                                   /* allocations when called from  */
3819                                   /* other operations, notable exp]  */
3820  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
3821  Int   reqdigits=set->digits;     /* local copy; requested DIGITS  */
3822  Int   padding;                   /* work  */
3823
3824  #if DECCHECK
3825  if (decCheckOperands(res, lhs, rhs, set)) return res;
3826  #endif
3827
3828  do {                             /* protect allocated storage  */
3829    #if DECSUBSET
3830    if (!set->extended) {
3831      /* reduce operands and set lostDigits status, as needed  */
3832      if (lhs->digits>reqdigits) {
3833        alloclhs=decRoundOperand(lhs, set, status);
3834        if (alloclhs==NULL) break;
3835        lhs=alloclhs;
3836        }
3837      if (rhs->digits>reqdigits) {
3838        allocrhs=decRoundOperand(rhs, set, status);
3839        if (allocrhs==NULL) break;
3840        rhs=allocrhs;
3841        }
3842      }
3843    #endif
3844    /* [following code does not require input rounding]  */
3845
3846    /* note whether signs differ [used all paths]  */
3847    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3848
3849    /* handle infinities and NaNs  */
3850    if (SPECIALARGS) {                  /* a special bit set  */
3851      if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN  */
3852        decNaNs(res, lhs, rhs, set, status);
3853       else { /* one or two infinities  */
3854        if (decNumberIsInfinite(lhs)) { /* LHS is infinity  */
3855          /* two infinities with different signs is invalid  */
3856          if (decNumberIsInfinite(rhs) && diffsign) {
3857            *status|=DEC_Invalid_operation;
3858            break;
3859            }
3860          bits=lhs->bits & DECNEG;      /* get sign from LHS  */
3861          }
3862         else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity  */
3863        bits|=DECINF;
3864        uprv_decNumberZero(res);
3865        res->bits=bits;                 /* set +/- infinity  */
3866        } /* an infinity  */
3867      break;
3868      }
3869
3870    /* Quick exit for add 0s; return the non-0, modified as need be  */
3871    if (ISZERO(lhs)) {
3872      Int adjust;                       /* work  */
3873      Int lexp=lhs->exponent;           /* save in case LHS==RES  */
3874      bits=lhs->bits;                   /* ..  */
3875      residue=0;                        /* clear accumulator  */
3876      decCopyFit(res, rhs, set, &residue, status); /* copy (as needed)  */
3877      res->bits^=negate;                /* flip if rhs was negated  */
3878      #if DECSUBSET
3879      if (set->extended) {              /* exponents on zeros count  */
3880      #endif
3881        /* exponent will be the lower of the two  */
3882        adjust=lexp-res->exponent;      /* adjustment needed [if -ve]  */
3883        if (ISZERO(res)) {              /* both 0: special IEEE 754 rules  */
3884          if (adjust<0) res->exponent=lexp;  /* set exponent  */
3885          /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0  */
3886          if (diffsign) {
3887            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3888             else res->bits=DECNEG;     /* preserve 0 sign  */
3889            }
3890          }
3891         else { /* non-0 res  */
3892          if (adjust<0) {     /* 0-padding needed  */
3893            if ((res->digits-adjust)>set->digits) {
3894              adjust=res->digits-set->digits;     /* to fit exactly  */
3895              *status|=DEC_Rounded;               /* [but exact]  */
3896              }
3897            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3898            res->exponent+=adjust;                /* set the exponent.  */
3899            }
3900          } /* non-0 res  */
3901      #if DECSUBSET
3902        } /* extended  */
3903      #endif
3904      decFinish(res, set, &residue, status);      /* clean and finalize  */
3905      break;}
3906
3907    if (ISZERO(rhs)) {                  /* [lhs is non-zero]  */
3908      Int adjust;                       /* work  */
3909      Int rexp=rhs->exponent;           /* save in case RHS==RES  */
3910      bits=rhs->bits;                   /* be clean  */
3911      residue=0;                        /* clear accumulator  */
3912      decCopyFit(res, lhs, set, &residue, status); /* copy (as needed)  */
3913      #if DECSUBSET
3914      if (set->extended) {              /* exponents on zeros count  */
3915      #endif
3916        /* exponent will be the lower of the two  */
3917        /* [0-0 case handled above]  */
3918        adjust=rexp-res->exponent;      /* adjustment needed [if -ve]  */
3919        if (adjust<0) {     /* 0-padding needed  */
3920          if ((res->digits-adjust)>set->digits) {
3921            adjust=res->digits-set->digits;     /* to fit exactly  */
3922            *status|=DEC_Rounded;               /* [but exact]  */
3923            }
3924          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3925          res->exponent+=adjust;                /* set the exponent.  */
3926          }
3927      #if DECSUBSET
3928        } /* extended  */
3929      #endif
3930      decFinish(res, set, &residue, status);      /* clean and finalize  */
3931      break;}
3932
3933    /* [NB: both fastpath and mainpath code below assume these cases  */
3934    /* (notably 0-0) have already been handled]  */
3935
3936    /* calculate the padding needed to align the operands  */
3937    padding=rhs->exponent-lhs->exponent;
3938
3939    /* Fastpath cases where the numbers are aligned and normal, the RHS  */
3940    /* is all in one unit, no operand rounding is needed, and no carry,  */
3941    /* lengthening, or borrow is needed  */
3942    if (padding==0
3943        && rhs->digits<=DECDPUN
3944        && rhs->exponent>=set->emin     /* [some normals drop through]  */
3945        && rhs->exponent<=set->emax-set->digits+1 /* [could clamp]  */
3946        && rhs->digits<=reqdigits
3947        && lhs->digits<=reqdigits) {
3948      Int partial=*lhs->lsu;
3949      if (!diffsign) {                  /* adding  */
3950        partial+=*rhs->lsu;
3951        if ((partial<=DECDPUNMAX)       /* result fits in unit  */
3952         && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change  */
3953             partial<(Int)powers[lhs->digits])) { /* ..  */
3954          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3955          *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS]  */
3956          break;
3957          }
3958        /* else drop out for careful add  */
3959        }
3960       else {                           /* signs differ  */
3961        partial-=*rhs->lsu;
3962        if (partial>0) { /* no borrow needed, and non-0 result  */
3963          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3964          *res->lsu=(Unit)partial;
3965          /* this could have reduced digits [but result>0]  */
3966          res->digits=decGetDigits(res->lsu, D2U(res->digits));
3967          break;
3968          }
3969        /* else drop out for careful subtract  */
3970        }
3971      }
3972
3973    /* Now align (pad) the lhs or rhs so they can be added or  */
3974    /* subtracted, as necessary.  If one number is much larger than  */
3975    /* the other (that is, if in plain form there is a least one  */
3976    /* digit between the lowest digit of one and the highest of the  */
3977    /* other) padding with up to DIGITS-1 trailing zeros may be  */
3978    /* needed; then apply rounding (as exotic rounding modes may be  */
3979    /* affected by the residue).  */
3980    rhsshift=0;               /* rhs shift to left (padding) in Units  */
3981    bits=lhs->bits;           /* assume sign is that of LHS  */
3982    mult=1;                   /* likely multiplier  */
3983
3984    /* [if padding==0 the operands are aligned; no padding is needed]  */
3985    if (padding!=0) {
3986      /* some padding needed; always pad the RHS, as any required  */
3987      /* padding can then be effected by a simple combination of  */
3988      /* shifts and a multiply  */
3989      Flag swapped=0;
3990      if (padding<0) {                  /* LHS needs the padding  */
3991        const decNumber *t;
3992        padding=-padding;               /* will be +ve  */
3993        bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS  */
3994        t=lhs; lhs=rhs; rhs=t;
3995        swapped=1;
3996        }
3997
3998      /* If, after pad, rhs would be longer than lhs by digits+1 or  */
3999      /* more then lhs cannot affect the answer, except as a residue,  */
4000      /* so only need to pad up to a length of DIGITS+1.  */
4001      if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4002        /* The RHS is sufficient  */
4003        /* for residue use the relative sign indication...  */
4004        Int shift=reqdigits-rhs->digits;     /* left shift needed  */
4005        residue=1;                           /* residue for rounding  */
4006        if (diffsign) residue=-residue;      /* signs differ  */
4007        /* copy, shortening if necessary  */
4008        decCopyFit(res, rhs, set, &residue, status);
4009        /* if it was already shorter, then need to pad with zeros  */
4010        if (shift>0) {
4011          res->digits=decShiftToMost(res->lsu, res->digits, shift);
4012          res->exponent-=shift;              /* adjust the exponent.  */
4013          }
4014        /* flip the result sign if unswapped and rhs was negated  */
4015        if (!swapped) res->bits^=negate;
4016        decFinish(res, set, &residue, status);    /* done  */
4017        break;}
4018
4019      /* LHS digits may affect result  */
4020      rhsshift=D2U(padding+1)-1;        /* this much by Unit shift ..  */
4021      mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication  */
4022      } /* padding needed  */
4023
4024    if (diffsign) mult=-mult;           /* signs differ  */
4025
4026    /* determine the longer operand  */
4027    maxdigits=rhs->digits+padding;      /* virtual length of RHS  */
4028    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4029
4030    /* Decide on the result buffer to use; if possible place directly  */
4031    /* into result.  */
4032    acc=res->lsu;                       /* assume add direct to result  */
4033    /* If destructive overlap, or the number is too long, or a carry or  */
4034    /* borrow to DIGITS+1 might be possible, a buffer must be used.  */
4035    /* [Might be worth more sophisticated tests when maxdigits==reqdigits]  */
4036    if ((maxdigits>=reqdigits)          /* is, or could be, too large  */
4037     || (res==rhs && rhsshift>0)) {     /* destructive overlap  */
4038      /* buffer needed, choose it; units for maxdigits digits will be  */
4039      /* needed, +1 Unit for carry or borrow  */
4040      Int need=D2U(maxdigits)+1;
4041      acc=accbuff;                      /* assume use local buffer  */
4042      if (need*sizeof(Unit)>sizeof(accbuff)) {
4043        /* printf("malloc add %ld %ld\n", need, sizeof(accbuff));  */
4044        allocacc=(Unit *)malloc(need*sizeof(Unit));
4045        if (allocacc==NULL) {           /* hopeless -- abandon  */
4046          *status|=DEC_Insufficient_storage;
4047          break;}
4048        acc=allocacc;
4049        }
4050      }
4051
4052    res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite..  */
4053    res->exponent=lhs->exponent;        /* .. operands (even if aliased)  */
4054
4055    #if DECTRACE
4056      decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4057      decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4058      printf("  :h: %ld %ld\n", rhsshift, mult);
4059    #endif
4060
4061    /* add [A+B*m] or subtract [A+B*(-m)]  */
4062    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4063                              rhs->lsu, D2U(rhs->digits),
4064                              rhsshift, acc, mult)
4065               *DECDPUN;           /* [units -> digits]  */
4066    if (res->digits<0) {           /* borrowed...  */
4067      res->digits=-res->digits;
4068      res->bits^=DECNEG;           /* flip the sign  */
4069      }
4070    #if DECTRACE
4071      decDumpAr('+', acc, D2U(res->digits));
4072    #endif
4073
4074    /* If a buffer was used the result must be copied back, possibly  */
4075    /* shortening.  (If no buffer was used then the result must have  */
4076    /* fit, so can't need rounding and residue must be 0.)  */
4077    residue=0;                     /* clear accumulator  */
4078    if (acc!=res->lsu) {
4079      #if DECSUBSET
4080      if (set->extended) {         /* round from first significant digit  */
4081      #endif
4082        /* remove leading zeros that were added due to rounding up to  */
4083        /* integral Units -- before the test for rounding.  */
4084        if (res->digits>reqdigits)
4085          res->digits=decGetDigits(acc, D2U(res->digits));
4086        decSetCoeff(res, set, acc, res->digits, &residue, status);
4087      #if DECSUBSET
4088        }
4089       else { /* subset arithmetic rounds from original significant digit  */
4090        /* May have an underestimate.  This only occurs when both  */
4091        /* numbers fit in DECDPUN digits and are padding with a  */
4092        /* negative multiple (-10, -100...) and the top digit(s) become  */
4093        /* 0.  (This only matters when using X3.274 rules where the  */
4094        /* leading zero could be included in the rounding.)  */
4095        if (res->digits<maxdigits) {
4096          *(acc+D2U(res->digits))=0; /* ensure leading 0 is there  */
4097          res->digits=maxdigits;
4098          }
4099         else {
4100          /* remove leading zeros that added due to rounding up to  */
4101          /* integral Units (but only those in excess of the original  */
4102          /* maxdigits length, unless extended) before test for rounding.  */
4103          if (res->digits>reqdigits) {
4104            res->digits=decGetDigits(acc, D2U(res->digits));
4105            if (res->digits<maxdigits) res->digits=maxdigits;
4106            }
4107          }
4108        decSetCoeff(res, set, acc, res->digits, &residue, status);
4109        /* Now apply rounding if needed before removing leading zeros.  */
4110        /* This is safe because subnormals are not a possibility  */
4111        if (residue!=0) {
4112          decApplyRound(res, set, residue, status);
4113          residue=0;                 /* did what needed to be done  */
4114          }
4115        } /* subset  */
4116      #endif
4117      } /* used buffer  */
4118
4119    /* strip leading zeros [these were left on in case of subset subtract]  */
4120    res->digits=decGetDigits(res->lsu, D2U(res->digits));
4121
4122    /* apply checks and rounding  */
4123    decFinish(res, set, &residue, status);
4124
4125    /* "When the sum of two operands with opposite signs is exactly  */
4126    /* zero, the sign of that sum shall be '+' in all rounding modes  */
4127    /* except round toward -Infinity, in which mode that sign shall be  */
4128    /* '-'."  [Subset zeros also never have '-', set by decFinish.]  */
4129    if (ISZERO(res) && diffsign
4130     #if DECSUBSET
4131     && set->extended
4132     #endif
4133     && (*status&DEC_Inexact)==0) {
4134      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign -  */
4135                                  else res->bits&=~DECNEG;  /* sign +  */
4136      }
4137    } while(0);                              /* end protected  */
4138
4139  if (allocacc!=NULL) free(allocacc);        /* drop any storage used  */
4140  #if DECSUBSET
4141  if (allocrhs!=NULL) free(allocrhs);        /* ..  */
4142  if (alloclhs!=NULL) free(alloclhs);        /* ..  */
4143  #endif
4144  return res;
4145  } /* decAddOp  */
4146
4147/* ------------------------------------------------------------------ */
4148/* decDivideOp -- division operation                                  */
4149/*                                                                    */
4150/*  This routine performs the calculations for all four division      */
4151/*  operators (divide, divideInteger, remainder, remainderNear).      */
4152/*                                                                    */
4153/*  C=A op B                                                          */
4154/*                                                                    */
4155/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4156/*   lhs is A                                                         */
4157/*   rhs is B                                                         */
4158/*   set is the context                                               */
4159/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4160/*   status is the usual accumulator                                  */
4161/*                                                                    */
4162/* C must have space for set->digits digits.                          */
4163/*                                                                    */
4164/* ------------------------------------------------------------------ */
4165/*   The underlying algorithm of this routine is the same as in the   */
4166/*   1981 S/370 implementation, that is, non-restoring long division  */
4167/*   with bi-unit (rather than bi-digit) estimation for each unit     */
4168/*   multiplier.  In this pseudocode overview, complications for the  */
4169/*   Remainder operators and division residues for exact rounding are */
4170/*   omitted for clarity.                                             */
4171/*                                                                    */
4172/*     Prepare operands and handle special values                     */
4173/*     Test for x/0 and then 0/x                                      */
4174/*     Exp =Exp1 - Exp2                                               */
4175/*     Exp =Exp +len(var1) -len(var2)                                 */
4176/*     Sign=Sign1 * Sign2                                             */
4177/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4178/*     Pad Var2 to same length as Var1                                */
4179/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4180/*     have=0                                                         */
4181/*     Do until (have=digits+1 OR residue=0)                          */
4182/*       if exp<0 then if integer divide/residue then leave           */
4183/*       this_unit=0                                                  */
4184/*       Do forever                                                   */
4185/*          compare numbers                                           */
4186/*          if <0 then leave inner_loop                               */
4187/*          if =0 then (* quick exit without subtract *) do           */
4188/*             this_unit=this_unit+1; output this_unit                */
4189/*             leave outer_loop; end                                  */
4190/*          Compare lengths of numbers (mantissae):                   */
4191/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4192/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4193/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4194/*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4195/*          if mult=0 then mult=1                                     */
4196/*          this_unit=this_unit+mult                                  */
4197/*          subtract                                                  */
4198/*          end inner_loop                                            */
4199/*        if have\=0 | this_unit\=0 then do                           */
4200/*          output this_unit                                          */
4201/*          have=have+1; end                                          */
4202/*        var2=var2/10                                                */
4203/*        exp=exp-1                                                   */
4204/*        end outer_loop                                              */
4205/*     exp=exp+1   -- set the proper exponent                         */
4206/*     if have=0 then generate answer=0                               */
4207/*     Return (Result is defined by Var1)                             */
4208/*                                                                    */
4209/* ------------------------------------------------------------------ */
4210/* Two working buffers are needed during the division; one (digits+   */
4211/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4212/* long subtractions.  These are acc and var1 respectively.           */
4213/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4214/* The static buffers may be larger than might be expected to allow   */
4215/* for calls from higher-level funtions (notable exp).                */
4216/* ------------------------------------------------------------------ */
4217static decNumber * decDivideOp(decNumber *res,
4218                               const decNumber *lhs, const decNumber *rhs,
4219                               decContext *set, Flag op, uInt *status) {
4220  #if DECSUBSET
4221  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
4222  decNumber *allocrhs=NULL;        /* .., rhs  */
4223  #endif
4224  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer  */
4225  Unit  *acc=accbuff;              /* -> accumulator array for result  */
4226  Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated  */
4227  Unit  *accnext;                  /* -> where next digit will go  */
4228  Int   acclength;                 /* length of acc needed [Units]  */
4229  Int   accunits;                  /* count of units accumulated  */
4230  Int   accdigits;                 /* count of digits accumulated  */
4231
4232  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  /* buffer for var1  */
4233  Unit  *var1=varbuff;             /* -> var1 array for long subtraction  */
4234  Unit  *varalloc=NULL;            /* -> allocated buffer, iff used  */
4235  Unit  *msu1;                     /* -> msu of var1  */
4236
4237  const Unit *var2;                /* -> var2 array  */
4238  const Unit *msu2;                /* -> msu of var2  */
4239  Int   msu2plus;                  /* msu2 plus one [does not vary]  */
4240  eInt  msu2pair;                  /* msu2 pair plus one [does not vary]  */
4241
4242  Int   var1units, var2units;      /* actual lengths  */
4243  Int   var2ulen;                  /* logical length (units)  */
4244  Int   var1initpad=0;             /* var1 initial padding (digits)  */
4245  Int   maxdigits;                 /* longest LHS or required acc length  */
4246  Int   mult;                      /* multiplier for subtraction  */
4247  Unit  thisunit;                  /* current unit being accumulated  */
4248  Int   residue;                   /* for rounding  */
4249  Int   reqdigits=set->digits;     /* requested DIGITS  */
4250  Int   exponent;                  /* working exponent  */
4251  Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded  */
4252  uByte bits;                      /* working sign  */
4253  Unit  *target;                   /* work  */
4254  const Unit *source;              /* ..  */
4255  uInt  const *pow;                /* ..  */
4256  Int   shift, cut;                /* ..  */
4257  #if DECSUBSET
4258  Int   dropped;                   /* work  */
4259  #endif
4260
4261  #if DECCHECK
4262  if (decCheckOperands(res, lhs, rhs, set)) return res;
4263  #endif
4264
4265  do {                             /* protect allocated storage  */
4266    #if DECSUBSET
4267    if (!set->extended) {
4268      /* reduce operands and set lostDigits status, as needed  */
4269      if (lhs->digits>reqdigits) {
4270        alloclhs=decRoundOperand(lhs, set, status);
4271        if (alloclhs==NULL) break;
4272        lhs=alloclhs;
4273        }
4274      if (rhs->digits>reqdigits) {
4275        allocrhs=decRoundOperand(rhs, set, status);
4276        if (allocrhs==NULL) break;
4277        rhs=allocrhs;
4278        }
4279      }
4280    #endif
4281    /* [following code does not require input rounding]  */
4282
4283    bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions  */
4284
4285    /* handle infinities and NaNs  */
4286    if (SPECIALARGS) {                  /* a special bit set  */
4287      if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4288        decNaNs(res, lhs, rhs, set, status);
4289        break;
4290        }
4291      /* one or two infinities  */
4292      if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite  */
4293        if (decNumberIsInfinite(rhs) || /* two infinities are invalid ..  */
4294            op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity  */
4295          *status|=DEC_Invalid_operation;
4296          break;
4297          }
4298        /* [Note that infinity/0 raises no exceptions]  */
4299        uprv_decNumberZero(res);
4300        res->bits=bits|DECINF;          /* set +/- infinity  */
4301        break;
4302        }
4303       else {                           /* RHS (divisor) is infinite  */
4304        residue=0;
4305        if (op&(REMAINDER|REMNEAR)) {
4306          /* result is [finished clone of] lhs  */
4307          decCopyFit(res, lhs, set, &residue, status);
4308          }
4309         else {  /* a division  */
4310          uprv_decNumberZero(res);
4311          res->bits=bits;               /* set +/- zero  */
4312          /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result  */
4313          /* is a 0 with infinitely negative exponent, clamped to minimum  */
4314          if (op&DIVIDE) {
4315            res->exponent=set->emin-set->digits+1;
4316            *status|=DEC_Clamped;
4317            }
4318          }
4319        decFinish(res, set, &residue, status);
4320        break;
4321        }
4322      }
4323
4324    /* handle 0 rhs (x/0)  */
4325    if (ISZERO(rhs)) {                  /* x/0 is always exceptional  */
4326      if (ISZERO(lhs)) {
4327        uprv_decNumberZero(res);             /* [after lhs test]  */
4328        *status|=DEC_Division_undefined;/* 0/0 will become NaN  */
4329        }
4330       else {
4331        uprv_decNumberZero(res);
4332        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4333         else {
4334          *status|=DEC_Division_by_zero; /* x/0  */
4335          res->bits=bits|DECINF;         /* .. is +/- Infinity  */
4336          }
4337        }
4338      break;}
4339
4340    /* handle 0 lhs (0/x)  */
4341    if (ISZERO(lhs)) {                  /* 0/x [x!=0]  */
4342      #if DECSUBSET
4343      if (!set->extended) uprv_decNumberZero(res);
4344       else {
4345      #endif
4346        if (op&DIVIDE) {
4347          residue=0;
4348          exponent=lhs->exponent-rhs->exponent; /* ideal exponent  */
4349          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4350          res->bits=bits;               /* sign as computed  */
4351          res->exponent=exponent;       /* exponent, too  */
4352          decFinalize(res, set, &residue, status);   /* check exponent  */
4353          }
4354         else if (op&DIVIDEINT) {
4355          uprv_decNumberZero(res);           /* integer 0  */
4356          res->bits=bits;               /* sign as computed  */
4357          }
4358         else {                         /* a remainder  */
4359          exponent=rhs->exponent;       /* [save in case overwrite]  */
4360          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4361          if (exponent<res->exponent) res->exponent=exponent; /* use lower  */
4362          }
4363      #if DECSUBSET
4364        }
4365      #endif
4366      break;}
4367
4368    /* Precalculate exponent.  This starts off adjusted (and hence fits  */
4369    /* in 31 bits) and becomes the usual unadjusted exponent as the  */
4370    /* division proceeds.  The order of evaluation is important, here,  */
4371    /* to avoid wrap.  */
4372    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4373
4374    /* If the working exponent is -ve, then some quick exits are  */
4375    /* possible because the quotient is known to be <1  */
4376    /* [for REMNEAR, it needs to be < -1, as -0.5 could need work]  */
4377    if (exponent<0 && !(op==DIVIDE)) {
4378      if (op&DIVIDEINT) {
4379        uprv_decNumberZero(res);                  /* integer part is 0  */
4380        #if DECSUBSET
4381        if (set->extended)
4382        #endif
4383          res->bits=bits;                    /* set +/- zero  */
4384        break;}
4385      /* fastpath remainders so long as the lhs has the smaller  */
4386      /* (or equal) exponent  */
4387      if (lhs->exponent<=rhs->exponent) {
4388        if (op&REMAINDER || exponent<-1) {
4389          /* It is REMAINDER or safe REMNEAR; result is [finished  */
4390          /* clone of] lhs  (r = x - 0*y)  */
4391          residue=0;
4392          decCopyFit(res, lhs, set, &residue, status);
4393          decFinish(res, set, &residue, status);
4394          break;
4395          }
4396        /* [unsafe REMNEAR drops through]  */
4397        }
4398      } /* fastpaths  */
4399
4400    /* Long (slow) division is needed; roll up the sleeves... */
4401
4402    /* The accumulator will hold the quotient of the division.  */
4403    /* If it needs to be too long for stack storage, then allocate.  */
4404    acclength=D2U(reqdigits+DECDPUN);   /* in Units  */
4405    if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4406      /* printf("malloc dvacc %ld units\n", acclength);  */
4407      allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4408      if (allocacc==NULL) {             /* hopeless -- abandon  */
4409        *status|=DEC_Insufficient_storage;
4410        break;}
4411      acc=allocacc;                     /* use the allocated space  */
4412      }
4413
4414    /* var1 is the padded LHS ready for subtractions.  */
4415    /* If it needs to be too long for stack storage, then allocate.  */
4416    /* The maximum units needed for var1 (long subtraction) is:  */
4417    /* Enough for  */
4418    /*     (rhs->digits+reqdigits-1) -- to allow full slide to right  */
4419    /* or  (lhs->digits)             -- to allow for long lhs  */
4420    /* whichever is larger  */
4421    /*   +1                -- for rounding of slide to right  */
4422    /*   +1                -- for leading 0s  */
4423    /*   +1                -- for pre-adjust if a remainder or DIVIDEINT  */
4424    /* [Note: unused units do not participate in decUnitAddSub data]  */
4425    maxdigits=rhs->digits+reqdigits-1;
4426    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4427    var1units=D2U(maxdigits)+2;
4428    /* allocate a guard unit above msu1 for REMAINDERNEAR  */
4429    if (!(op&DIVIDE)) var1units++;
4430    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4431      /* printf("malloc dvvar %ld units\n", var1units+1);  */
4432      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4433      if (varalloc==NULL) {             /* hopeless -- abandon  */
4434        *status|=DEC_Insufficient_storage;
4435        break;}
4436      var1=varalloc;                    /* use the allocated space  */
4437      }
4438
4439    /* Extend the lhs and rhs to full long subtraction length.  The lhs  */
4440    /* is truly extended into the var1 buffer, with 0 padding, so a  */
4441    /* subtract in place is always possible.  The rhs (var2) has  */
4442    /* virtual padding (implemented by decUnitAddSub).  */
4443    /* One guard unit was allocated above msu1 for rem=rem+rem in  */
4444    /* REMAINDERNEAR.  */
4445    msu1=var1+var1units-1;              /* msu of var1  */
4446    source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array  */
4447    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4448    for (; target>=var1; target--) *target=0;
4449
4450    /* rhs (var2) is left-aligned with var1 at the start  */
4451    var2ulen=var1units;                 /* rhs logical length (units)  */
4452    var2units=D2U(rhs->digits);         /* rhs actual length (units)  */
4453    var2=rhs->lsu;                      /* -> rhs array  */
4454    msu2=var2+var2units-1;              /* -> msu of var2 [never changes]  */
4455    /* now set up the variables which will be used for estimating the  */
4456    /* multiplication factor.  If these variables are not exact, add  */
4457    /* 1 to make sure that the multiplier is never overestimated.  */
4458    msu2plus=*msu2;                     /* it's value ..  */
4459    if (var2units>1) msu2plus++;        /* .. +1 if any more  */
4460    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair ..  */
4461    if (var2units>1) {                  /* .. [else treat 2nd as 0]  */
4462      msu2pair+=*(msu2-1);              /* ..  */
4463      if (var2units>2) msu2pair++;      /* .. +1 if any more  */
4464      }
4465
4466    /* The calculation is working in units, which may have leading zeros,  */
4467    /* but the exponent was calculated on the assumption that they are  */
4468    /* both left-aligned.  Adjust the exponent to compensate: add the  */
4469    /* number of leading zeros in var1 msu and subtract those in var2 msu.  */
4470    /* [This is actually done by counting the digits and negating, as  */
4471    /* lead1=DECDPUN-digits1, and similarly for lead2.]  */
4472    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4473    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4474
4475    /* Now, if doing an integer divide or remainder, ensure that  */
4476    /* the result will be Unit-aligned.  To do this, shift the var1  */
4477    /* accumulator towards least if need be.  (It's much easier to  */
4478    /* do this now than to reassemble the residue afterwards, if  */
4479    /* doing a remainder.)  Also ensure the exponent is not negative.  */
4480    if (!(op&DIVIDE)) {
4481      Unit *u;                          /* work  */
4482      /* save the initial 'false' padding of var1, in digits  */
4483      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4484      /* Determine the shift to do.  */
4485      if (exponent<0) cut=-exponent;
4486       else cut=DECDPUN-exponent%DECDPUN;
4487      decShiftToLeast(var1, var1units, cut);
4488      exponent+=cut;                    /* maintain numerical value  */
4489      var1initpad-=cut;                 /* .. and reduce padding  */
4490      /* clean any most-significant units which were just emptied  */
4491      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4492      } /* align  */
4493     else { /* is DIVIDE  */
4494      maxexponent=lhs->exponent-rhs->exponent;    /* save  */
4495      /* optimization: if the first iteration will just produce 0,  */
4496      /* preadjust to skip it [valid for DIVIDE only]  */
4497      if (*msu1<*msu2) {
4498        var2ulen--;                     /* shift down  */
4499        exponent-=DECDPUN;              /* update the exponent  */
4500        }
4501      }
4502
4503    /* ---- start the long-division loops ------------------------------  */
4504    accunits=0;                         /* no units accumulated yet  */
4505    accdigits=0;                        /* .. or digits  */
4506    accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1]  */
4507    for (;;) {                          /* outer forever loop  */
4508      thisunit=0;                       /* current unit assumed 0  */
4509      /* find the next unit  */
4510      for (;;) {                        /* inner forever loop  */
4511        /* strip leading zero units [from either pre-adjust or from  */
4512        /* subtract last time around].  Leave at least one unit.  */
4513        for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4514
4515        if (var1units<var2ulen) break;       /* var1 too low for subtract  */
4516        if (var1units==var2ulen) {           /* unit-by-unit compare needed  */
4517          /* compare the two numbers, from msu  */
4518          const Unit *pv1, *pv2;
4519          Unit v2;                           /* units to compare  */
4520          pv2=msu2;                          /* -> msu  */
4521          for (pv1=msu1; ; pv1--, pv2--) {
4522            /* v1=*pv1 -- always OK  */
4523            v2=0;                            /* assume in padding  */
4524            if (pv2>=var2) v2=*pv2;          /* in range  */
4525            if (*pv1!=v2) break;             /* no longer the same  */
4526            if (pv1==var1) break;            /* done; leave pv1 as is  */
4527            }
4528          /* here when all inspected or a difference seen  */
4529          if (*pv1<v2) break;                /* var1 too low to subtract  */
4530          if (*pv1==v2) {                    /* var1 == var2  */
4531            /* reach here if var1 and var2 are identical; subtraction  */
4532            /* would increase digit by one, and the residue will be 0 so  */
4533            /* the calculation is done; leave the loop with residue=0.  */
4534            thisunit++;                      /* as though subtracted  */
4535            *var1=0;                         /* set var1 to 0  */
4536            var1units=1;                     /* ..  */
4537            break;  /* from inner  */
4538            } /* var1 == var2  */
4539          /* *pv1>v2.  Prepare for real subtraction; the lengths are equal  */
4540          /* Estimate the multiplier (there's always a msu1-1)...  */
4541          /* Bring in two units of var2 to provide a good estimate.  */
4542          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4543          } /* lengths the same  */
4544         else { /* var1units > var2ulen, so subtraction is safe  */
4545          /* The var2 msu is one unit towards the lsu of the var1 msu,  */
4546          /* so only one unit for var2 can be used.  */
4547          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4548          }
4549        if (mult==0) mult=1;                 /* must always be at least 1  */
4550        /* subtraction needed; var1 is > var2  */
4551        thisunit=(Unit)(thisunit+mult);      /* accumulate  */
4552        /* subtract var1-var2, into var1; only the overlap needs  */
4553        /* processing, as this is an in-place calculation  */
4554        shift=var2ulen-var2units;
4555        #if DECTRACE
4556          decDumpAr('1', &var1[shift], var1units-shift);
4557          decDumpAr('2', var2, var2units);
4558          printf("m=%ld\n", -mult);
4559        #endif
4560        decUnitAddSub(&var1[shift], var1units-shift,
4561                      var2, var2units, 0,
4562                      &var1[shift], -mult);
4563        #if DECTRACE
4564          decDumpAr('#', &var1[shift], var1units-shift);
4565        #endif
4566        /* var1 now probably has leading zeros; these are removed at the  */
4567        /* top of the inner loop.  */
4568        } /* inner loop  */
4569
4570      /* The next unit has been calculated in full; unless it's a  */
4571      /* leading zero, add to acc  */
4572      if (accunits!=0 || thisunit!=0) {      /* is first or non-zero  */
4573        *accnext=thisunit;                   /* store in accumulator  */
4574        /* account exactly for the new digits  */
4575        if (accunits==0) {
4576          accdigits++;                       /* at least one  */
4577          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4578          }
4579         else accdigits+=DECDPUN;
4580        accunits++;                          /* update count  */
4581        accnext--;                           /* ready for next  */
4582        if (accdigits>reqdigits) break;      /* have enough digits  */
4583        }
4584
4585      /* if the residue is zero, the operation is done (unless divide  */
4586      /* or divideInteger and still not enough digits yet)  */
4587      if (*var1==0 && var1units==1) {        /* residue is 0  */
4588        if (op&(REMAINDER|REMNEAR)) break;
4589        if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4590        /* [drop through if divideInteger]  */
4591        }
4592      /* also done enough if calculating remainder or integer  */
4593      /* divide and just did the last ('units') unit  */
4594      if (exponent==0 && !(op&DIVIDE)) break;
4595
4596      /* to get here, var1 is less than var2, so divide var2 by the per-  */
4597      /* Unit power of ten and go for the next digit  */
4598      var2ulen--;                            /* shift down  */
4599      exponent-=DECDPUN;                     /* update the exponent  */
4600      } /* outer loop  */
4601
4602    /* ---- division is complete ---------------------------------------  */
4603    /* here: acc      has at least reqdigits+1 of good results (or fewer  */
4604    /*                if early stop), starting at accnext+1 (its lsu)  */
4605    /*       var1     has any residue at the stopping point  */
4606    /*       accunits is the number of digits collected in acc  */
4607    if (accunits==0) {             /* acc is 0  */
4608      accunits=1;                  /* show have a unit ..  */
4609      accdigits=1;                 /* ..  */
4610      *accnext=0;                  /* .. whose value is 0  */
4611      }
4612     else accnext++;               /* back to last placed  */
4613    /* accnext now -> lowest unit of result  */
4614
4615    residue=0;                     /* assume no residue  */
4616    if (op&DIVIDE) {
4617      /* record the presence of any residue, for rounding  */
4618      if (*var1!=0 || var1units>1) residue=1;
4619       else { /* no residue  */
4620        /* Had an exact division; clean up spurious trailing 0s.  */
4621        /* There will be at most DECDPUN-1, from the final multiply,  */
4622        /* and then only if the result is non-0 (and even) and the  */
4623        /* exponent is 'loose'.  */
4624        #if DECDPUN>1
4625        Unit lsu=*accnext;
4626        if (!(lsu&0x01) && (lsu!=0)) {
4627          /* count the trailing zeros  */
4628          Int drop=0;
4629          for (;; drop++) {    /* [will terminate because lsu!=0]  */
4630            if (exponent>=maxexponent) break;     /* don't chop real 0s  */
4631            #if DECDPUN<=4
4632              if ((lsu-QUOT10(lsu, drop+1)
4633                  *powers[drop+1])!=0) break;     /* found non-0 digit  */
4634            #else
4635              if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit  */
4636            #endif
4637            exponent++;
4638            }
4639          if (drop>0) {
4640            accunits=decShiftToLeast(accnext, accunits, drop);
4641            accdigits=decGetDigits(accnext, accunits);
4642            accunits=D2U(accdigits);
4643            /* [exponent was adjusted in the loop]  */
4644            }
4645          } /* neither odd nor 0  */
4646        #endif
4647        } /* exact divide  */
4648      } /* divide  */
4649     else /* op!=DIVIDE */ {
4650      /* check for coefficient overflow  */
4651      if (accdigits+exponent>reqdigits) {
4652        *status|=DEC_Division_impossible;
4653        break;
4654        }
4655      if (op & (REMAINDER|REMNEAR)) {
4656        /* [Here, the exponent will be 0, because var1 was adjusted  */
4657        /* appropriately.]  */
4658        Int postshift;                       /* work  */
4659        Flag wasodd=0;                       /* integer was odd  */
4660        Unit *quotlsu;                       /* for save  */
4661        Int  quotdigits;                     /* ..  */
4662
4663        bits=lhs->bits;                      /* remainder sign is always as lhs  */
4664
4665        /* Fastpath when residue is truly 0 is worthwhile [and  */
4666        /* simplifies the code below]  */
4667        if (*var1==0 && var1units==1) {      /* residue is 0  */
4668          Int exp=lhs->exponent;             /* save min(exponents)  */
4669          if (rhs->exponent<exp) exp=rhs->exponent;
4670          uprv_decNumberZero(res);                /* 0 coefficient  */
4671          #if DECSUBSET
4672          if (set->extended)
4673          #endif
4674          res->exponent=exp;                 /* .. with proper exponent  */
4675          res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4676          decFinish(res, set, &residue, status);   /* might clamp  */
4677          break;
4678          }
4679        /* note if the quotient was odd  */
4680        if (*accnext & 0x01) wasodd=1;       /* acc is odd  */
4681        quotlsu=accnext;                     /* save in case need to reinspect  */
4682        quotdigits=accdigits;                /* ..  */
4683
4684        /* treat the residue, in var1, as the value to return, via acc  */
4685        /* calculate the unused zero digits.  This is the smaller of:  */
4686        /*   var1 initial padding (saved above)  */
4687        /*   var2 residual padding, which happens to be given by:  */
4688        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4689        /* [the 'exponent' term accounts for the shifts during divide]  */
4690        if (var1initpad<postshift) postshift=var1initpad;
4691
4692        /* shift var1 the requested amount, and adjust its digits  */
4693        var1units=decShiftToLeast(var1, var1units, postshift);
4694        accnext=var1;
4695        accdigits=decGetDigits(var1, var1units);
4696        accunits=D2U(accdigits);
4697
4698        exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs  */
4699        if (rhs->exponent<exponent) exponent=rhs->exponent;
4700
4701        /* Now correct the result if doing remainderNear; if it  */
4702        /* (looking just at coefficients) is > rhs/2, or == rhs/2 and  */
4703        /* the integer was odd then the result should be rem-rhs.  */
4704        if (op&REMNEAR) {
4705          Int compare, tarunits;        /* work  */
4706          Unit *up;                     /* ..  */
4707          /* calculate remainder*2 into the var1 buffer (which has  */
4708          /* 'headroom' of an extra unit and hence enough space)  */
4709          /* [a dedicated 'double' loop would be faster, here]  */
4710          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4711                                 0, accnext, 1);
4712          /* decDumpAr('r', accnext, tarunits);  */
4713
4714          /* Here, accnext (var1) holds tarunits Units with twice the  */
4715          /* remainder's coefficient, which must now be compared to the  */
4716          /* RHS.  The remainder's exponent may be smaller than the RHS's.  */
4717          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4718                                 rhs->exponent-exponent);
4719          if (compare==BADINT) {             /* deep trouble  */
4720            *status|=DEC_Insufficient_storage;
4721            break;}
4722
4723          /* now restore the remainder by dividing by two; the lsu  */
4724          /* is known to be even.  */
4725          for (up=accnext; up<accnext+tarunits; up++) {
4726            Int half;              /* half to add to lower unit  */
4727            half=*up & 0x01;
4728            *up/=2;                /* [shift]  */
4729            if (!half) continue;
4730            *(up-1)+=(DECDPUNMAX+1)/2;
4731            }
4732          /* [accunits still describes the original remainder length]  */
4733
4734          if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed  */
4735            Int exp, expunits, exprem;       /* work  */
4736            /* This is effectively causing round-up of the quotient,  */
4737            /* so if it was the rare case where it was full and all  */
4738            /* nines, it would overflow and hence division-impossible  */
4739            /* should be raised  */
4740            Flag allnines=0;                 /* 1 if quotient all nines  */
4741            if (quotdigits==reqdigits) {     /* could be borderline  */
4742              for (up=quotlsu; ; up++) {
4743                if (quotdigits>DECDPUN) {
4744                  if (*up!=DECDPUNMAX) break;/* non-nines  */
4745                  }
4746                 else {                      /* this is the last Unit  */
4747                  if (*up==powers[quotdigits]-1) allnines=1;
4748                  break;
4749                  }
4750                quotdigits-=DECDPUN;         /* checked those digits  */
4751                } /* up  */
4752              } /* borderline check  */
4753            if (allnines) {
4754              *status|=DEC_Division_impossible;
4755              break;}
4756
4757            /* rem-rhs is needed; the sign will invert.  Again, var1  */
4758            /* can safely be used for the working Units array.  */
4759            exp=rhs->exponent-exponent;      /* RHS padding needed  */
4760            /* Calculate units and remainder from exponent.  */
4761            expunits=exp/DECDPUN;
4762            exprem=exp%DECDPUN;
4763            /* subtract [A+B*(-m)]; the result will always be negative  */
4764            accunits=-decUnitAddSub(accnext, accunits,
4765                                    rhs->lsu, D2U(rhs->digits),
4766                                    expunits, accnext, -(Int)powers[exprem]);
4767            accdigits=decGetDigits(accnext, accunits); /* count digits exactly  */
4768            accunits=D2U(accdigits);    /* and recalculate the units for copy  */
4769            /* [exponent is as for original remainder]  */
4770            bits^=DECNEG;               /* flip the sign  */
4771            }
4772          } /* REMNEAR  */
4773        } /* REMAINDER or REMNEAR  */
4774      } /* not DIVIDE  */
4775
4776    /* Set exponent and bits  */
4777    res->exponent=exponent;
4778    res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4779
4780    /* Now the coefficient.  */
4781    decSetCoeff(res, set, accnext, accdigits, &residue, status);
4782
4783    decFinish(res, set, &residue, status);   /* final cleanup  */
4784
4785    #if DECSUBSET
4786    /* If a divide then strip trailing zeros if subset [after round]  */
4787    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4788    #endif
4789    } while(0);                              /* end protected  */
4790
4791  if (varalloc!=NULL) free(varalloc);   /* drop any storage used  */
4792  if (allocacc!=NULL) free(allocacc);   /* ..  */
4793  #if DECSUBSET
4794  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
4795  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
4796  #endif
4797  return res;
4798  } /* decDivideOp  */
4799
4800/* ------------------------------------------------------------------ */
4801/* decMultiplyOp -- multiplication operation                          */
4802/*                                                                    */
4803/*  This routine performs the multiplication C=A x B.                 */
4804/*                                                                    */
4805/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4806/*   lhs is A                                                         */
4807/*   rhs is B                                                         */
4808/*   set is the context                                               */
4809/*   status is the usual accumulator                                  */
4810/*                                                                    */
4811/* C must have space for set->digits digits.                          */
4812/*                                                                    */
4813/* ------------------------------------------------------------------ */
4814/* 'Classic' multiplication is used rather than Karatsuba, as the     */
4815/* latter would give only a minor improvement for the short numbers   */
4816/* expected to be handled most (and uses much more memory).           */
4817/*                                                                    */
4818/* There are two major paths here: the general-purpose ('old code')   */
4819/* path which handles all DECDPUN values, and a fastpath version      */
4820/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4821/* than two calls to decUnitAddSub would be made.                     */
4822/*                                                                    */
4823/* The fastpath version lumps units together into 8-digit or 9-digit  */
4824/* chunks, and also uses a lazy carry strategy to minimise expensive  */
4825/* 64-bit divisions.  The chunks are then broken apart again into     */
4826/* units for continuing processing.  Despite this overhead, the       */
4827/* fastpath can speed up some 16-digit operations by 10x (and much    */
4828/* more for higher-precision calculations).                           */
4829/*                                                                    */
4830/* A buffer always has to be used for the accumulator; in the         */
4831/* fastpath, buffers are also always needed for the chunked copies of */
4832/* of the operand coefficients.                                       */
4833/* Static buffers are larger than needed just for multiply, to allow  */
4834/* for calls from other operations (notably exp).                     */
4835/* ------------------------------------------------------------------ */
4836#define FASTMUL (DECUSE64 && DECDPUN<5)
4837static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4838                                 const decNumber *rhs, decContext *set,
4839                                 uInt *status) {
4840  Int    accunits;                 /* Units of accumulator in use  */
4841  Int    exponent;                 /* work  */
4842  Int    residue=0;                /* rounding residue  */
4843  uByte  bits;                     /* result sign  */
4844  Unit  *acc;                      /* -> accumulator Unit array  */
4845  Int    needbytes;                /* size calculator  */
4846  void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated  */
4847  Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0,  */
4848                                   /* *4 for calls from other operations)  */
4849  const Unit *mer, *mermsup;       /* work  */
4850  Int   madlength;                 /* Units in multiplicand  */
4851  Int   shift;                     /* Units to shift multiplicand by  */
4852
4853  #if FASTMUL
4854    /* if DECDPUN is 1 or 3 work in base 10**9, otherwise  */
4855    /* (DECDPUN is 2 or 4) then work in base 10**8  */
4856    #if DECDPUN & 1                /* odd  */
4857      #define FASTBASE 1000000000  /* base  */
4858      #define FASTDIGS          9  /* digits in base  */
4859      #define FASTLAZY         18  /* carry resolution point [1->18]  */
4860    #else
4861      #define FASTBASE  100000000
4862      #define FASTDIGS          8
4863      #define FASTLAZY       1844  /* carry resolution point [1->1844]  */
4864    #endif
4865    /* three buffers are used, two for chunked copies of the operands  */
4866    /* (base 10**8 or base 10**9) and one base 2**64 accumulator with  */
4867    /* lazy carry evaluation  */
4868    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4869    uInt  *zlhi=zlhibuff;                 /* -> lhs array  */
4870    uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated  */
4871    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4872    uInt  *zrhi=zrhibuff;                 /* -> rhs array  */
4873    uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated  */
4874    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0)  */
4875    /* [allocacc is shared for both paths, as only one will run]  */
4876    uLong *zacc=zaccbuff;          /* -> accumulator array for exact result  */
4877    #if DECDPUN==1
4878    Int    zoff;                   /* accumulator offset  */
4879    #endif
4880    uInt  *lip, *rip;              /* item pointers  */
4881    uInt  *lmsi, *rmsi;            /* most significant items  */
4882    Int    ilhs, irhs, iacc;       /* item counts in the arrays  */
4883    Int    lazy;                   /* lazy carry counter  */
4884    uLong  lcarry;                 /* uLong carry  */
4885    uInt   carry;                  /* carry (NB not uLong)  */
4886    Int    count;                  /* work  */
4887    const  Unit *cup;              /* ..  */
4888    Unit  *up;                     /* ..  */
4889    uLong *lp;                     /* ..  */
4890    Int    p;                      /* ..  */
4891  #endif
4892
4893  #if DECSUBSET
4894    decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated  */
4895    decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated  */
4896  #endif
4897
4898  #if DECCHECK
4899  if (decCheckOperands(res, lhs, rhs, set)) return res;
4900  #endif
4901
4902  /* precalculate result sign  */
4903  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4904
4905  /* handle infinities and NaNs  */
4906  if (SPECIALARGS) {               /* a special bit set  */
4907    if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4908      decNaNs(res, lhs, rhs, set, status);
4909      return res;}
4910    /* one or two infinities; Infinity * 0 is invalid  */
4911    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4912      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4913      *status|=DEC_Invalid_operation;
4914      return res;}
4915    uprv_decNumberZero(res);
4916    res->bits=bits|DECINF;         /* infinity  */
4917    return res;}
4918
4919  /* For best speed, as in DMSRCN [the original Rexx numerics  */
4920  /* module], use the shorter number as the multiplier (rhs) and  */
4921  /* the longer as the multiplicand (lhs) to minimise the number of  */
4922  /* adds (partial products)  */
4923  if (lhs->digits<rhs->digits) {   /* swap...  */
4924    const decNumber *hold=lhs;
4925    lhs=rhs;
4926    rhs=hold;
4927    }
4928
4929  do {                             /* protect allocated storage  */
4930    #if DECSUBSET
4931    if (!set->extended) {
4932      /* reduce operands and set lostDigits status, as needed  */
4933      if (lhs->digits>set->digits) {
4934        alloclhs=decRoundOperand(lhs, set, status);
4935        if (alloclhs==NULL) break;
4936        lhs=alloclhs;
4937        }
4938      if (rhs->digits>set->digits) {
4939        allocrhs=decRoundOperand(rhs, set, status);
4940        if (allocrhs==NULL) break;
4941        rhs=allocrhs;
4942        }
4943      }
4944    #endif
4945    /* [following code does not require input rounding]  */
4946
4947    #if FASTMUL                    /* fastpath can be used  */
4948    /* use the fast path if there are enough digits in the shorter  */
4949    /* operand to make the setup and takedown worthwhile  */
4950    #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls  */
4951    if (rhs->digits>NEEDTWO) {     /* use fastpath...  */
4952      /* calculate the number of elements in each array  */
4953      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling]  */
4954      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* ..  */
4955      iacc=ilhs+irhs;
4956
4957      /* allocate buffers if required, as usual  */
4958      needbytes=ilhs*sizeof(uInt);
4959      if (needbytes>(Int)sizeof(zlhibuff)) {
4960        alloclhi=(uInt *)malloc(needbytes);
4961        zlhi=alloclhi;}
4962      needbytes=irhs*sizeof(uInt);
4963      if (needbytes>(Int)sizeof(zrhibuff)) {
4964        allocrhi=(uInt *)malloc(needbytes);
4965        zrhi=allocrhi;}
4966
4967      /* Allocating the accumulator space needs a special case when  */
4968      /* DECDPUN=1 because when converting the accumulator to Units  */
4969      /* after the multiplication each 8-byte item becomes 9 1-byte  */
4970      /* units.  Therefore iacc extra bytes are needed at the front  */
4971      /* (rounded up to a multiple of 8 bytes), and the uLong  */
4972      /* accumulator starts offset the appropriate number of units  */
4973      /* to the right to avoid overwrite during the unchunking.  */
4974      needbytes=iacc*sizeof(uLong);
4975      #if DECDPUN==1
4976      zoff=(iacc+7)/8;        /* items to offset by  */
4977      needbytes+=zoff*8;
4978      #endif
4979      if (needbytes>(Int)sizeof(zaccbuff)) {
4980        allocacc=(uLong *)malloc(needbytes);
4981        zacc=(uLong *)allocacc;}
4982      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4983        *status|=DEC_Insufficient_storage;
4984        break;}
4985
4986      acc=(Unit *)zacc;       /* -> target Unit array  */
4987      #if DECDPUN==1
4988      zacc+=zoff;             /* start uLong accumulator to right  */
4989      #endif
4990
4991      /* assemble the chunked copies of the left and right sides  */
4992      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4993        for (p=0, *lip=0; p<FASTDIGS && count>0;
4994             p+=DECDPUN, cup++, count-=DECDPUN)
4995          *lip+=*cup*powers[p];
4996      lmsi=lip-1;     /* save -> msi  */
4997      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
4998        for (p=0, *rip=0; p<FASTDIGS && count>0;
4999             p+=DECDPUN, cup++, count-=DECDPUN)
5000          *rip+=*cup*powers[p];
5001      rmsi=rip-1;     /* save -> msi  */
5002
5003      /* zero the accumulator  */
5004      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5005
5006      /* Start the multiplication */
5007      /* Resolving carries can dominate the cost of accumulating the  */
5008      /* partial products, so this is only done when necessary.  */
5009      /* Each uLong item in the accumulator can hold values up to  */
5010      /* 2**64-1, and each partial product can be as large as  */
5011      /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to  */
5012      /* itself 18.4 times in a uLong without overflowing, so during  */
5013      /* the main calculation resolution is carried out every 18th  */
5014      /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the  */
5015      /* partial products can be added to themselves 1844.6 times in  */
5016      /* a uLong without overflowing, so intermediate carry  */
5017      /* resolution occurs only every 14752 digits.  Hence for common  */
5018      /* short numbers usually only the one final carry resolution  */
5019      /* occurs.  */
5020      /* (The count is set via FASTLAZY to simplify experiments to  */
5021      /* measure the value of this approach: a 35% improvement on a  */
5022      /* [34x34] multiply.)  */
5023      lazy=FASTLAZY;                         /* carry delay count  */
5024      for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs  */
5025        lp=zacc+(rip-zrhi);                  /* where to add the lhs  */
5026        for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs  */
5027          *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line]  */
5028          } /* lip loop  */
5029        lazy--;
5030        if (lazy>0 && rip!=rmsi) continue;
5031        lazy=FASTLAZY;                       /* reset delay count  */
5032        /* spin up the accumulator resolving overflows  */
5033        for (lp=zacc; lp<zacc+iacc; lp++) {
5034          if (*lp<FASTBASE) continue;        /* it fits  */
5035          lcarry=*lp/FASTBASE;               /* top part [slow divide]  */
5036          /* lcarry can exceed 2**32-1, so check again; this check  */
5037          /* and occasional extra divide (slow) is well worth it, as  */
5038          /* it allows FASTLAZY to be increased to 18 rather than 4  */
5039          /* in the FASTDIGS=9 case  */
5040          if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual]  */
5041           else { /* two-place carry [fairly rare]  */
5042            uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part  */
5043            *(lp+2)+=carry2;                        /* add to item+2  */
5044            *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow]  */
5045            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline]  */
5046            }
5047          *(lp+1)+=carry;                    /* add to item above [inline]  */
5048          *lp-=((uLong)FASTBASE*carry);      /* [inline]  */
5049          } /* carry resolution  */
5050        } /* rip loop  */
5051
5052      /* The multiplication is complete; time to convert back into  */
5053      /* units.  This can be done in-place in the accumulator and in  */
5054      /* 32-bit operations, because carries were resolved after the  */
5055      /* final add.  This needs N-1 divides and multiplies for  */
5056      /* each item in the accumulator (which will become up to N  */
5057      /* units, where 2<=N<=9).  */
5058      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5059        uInt item=(uInt)*lp;                 /* decapitate to uInt  */
5060        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5061          uInt part=item/(DECDPUNMAX+1);
5062          *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5063          item=part;
5064          } /* p  */
5065        *up=(Unit)item; up++;                /* [final needs no division]  */
5066        } /* lp  */
5067      accunits=up-acc;                       /* count of units  */
5068      }
5069     else { /* here to use units directly, without chunking ['old code']  */
5070    #endif
5071
5072      /* if accumulator will be too long for local storage, then allocate  */
5073      acc=accbuff;                 /* -> assume buffer for accumulator  */
5074      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5075      if (needbytes>(Int)sizeof(accbuff)) {
5076        allocacc=(Unit *)malloc(needbytes);
5077        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5078        acc=(Unit *)allocacc;                /* use the allocated space  */
5079        }
5080
5081      /* Now the main long multiplication loop */
5082      /* Unlike the equivalent in the IBM Java implementation, there  */
5083      /* is no advantage in calculating from msu to lsu.  So, do it  */
5084      /* by the book, as it were.  */
5085      /* Each iteration calculates ACC=ACC+MULTAND*MULT  */
5086      accunits=1;                  /* accumulator starts at '0'  */
5087      *acc=0;                      /* .. (lsu=0)  */
5088      shift=0;                     /* no multiplicand shift at first  */
5089      madlength=D2U(lhs->digits);  /* this won't change  */
5090      mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier  */
5091
5092      for (mer=rhs->lsu; mer<mermsup; mer++) {
5093        /* Here, *mer is the next Unit in the multiplier to use  */
5094        /* If non-zero [optimization] add it...  */
5095        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5096                                            lhs->lsu, madlength, 0,
5097                                            &acc[shift], *mer)
5098                                            + shift;
5099         else { /* extend acc with a 0; it will be used shortly  */
5100          *(acc+accunits)=0;       /* [this avoids length of <=0 later]  */
5101          accunits++;
5102          }
5103        /* multiply multiplicand by 10**DECDPUN for next Unit to left  */
5104        shift++;                   /* add this for 'logical length'  */
5105        } /* n  */
5106    #if FASTMUL
5107      } /* unchunked units  */
5108    #endif
5109    /* common end-path  */
5110    #if DECTRACE
5111      decDumpAr('*', acc, accunits);         /* Show exact result  */
5112    #endif
5113
5114    /* acc now contains the exact result of the multiplication,  */
5115    /* possibly with a leading zero unit; build the decNumber from  */
5116    /* it, noting if any residue  */
5117    res->bits=bits;                          /* set sign  */
5118    res->digits=decGetDigits(acc, accunits); /* count digits exactly  */
5119
5120    /* There can be a 31-bit wrap in calculating the exponent.  */
5121    /* This can only happen if both input exponents are negative and  */
5122    /* both their magnitudes are large.  If there was a wrap, set a  */
5123    /* safe very negative exponent, from which decFinalize() will  */
5124    /* raise a hard underflow shortly.  */
5125    exponent=lhs->exponent+rhs->exponent;    /* calculate exponent  */
5126    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5127      exponent=-2*DECNUMMAXE;                /* force underflow  */
5128    res->exponent=exponent;                  /* OK to overwrite now  */
5129
5130
5131    /* Set the coefficient.  If any rounding, residue records  */
5132    decSetCoeff(res, set, acc, res->digits, &residue, status);
5133    decFinish(res, set, &residue, status);   /* final cleanup  */
5134    } while(0);                         /* end protected  */
5135
5136  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
5137  #if DECSUBSET
5138  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
5139  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5140  #endif
5141  #if FASTMUL
5142  if (allocrhi!=NULL) free(allocrhi);   /* ..  */
5143  if (alloclhi!=NULL) free(alloclhi);   /* ..  */
5144  #endif
5145  return res;
5146  } /* decMultiplyOp  */
5147
5148/* ------------------------------------------------------------------ */
5149/* decExpOp -- effect exponentiation                                  */
5150/*                                                                    */
5151/*   This computes C = exp(A)                                         */
5152/*                                                                    */
5153/*   res is C, the result.  C may be A                                */
5154/*   rhs is A                                                         */
5155/*   set is the context; note that rounding mode has no effect        */
5156/*                                                                    */
5157/* C must have space for set->digits digits. status is updated but    */
5158/* not set.                                                           */
5159/*                                                                    */
5160/* Restrictions:                                                      */
5161/*                                                                    */
5162/*   digits, emax, and -emin in the context must be less than         */
5163/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5164/*   bounds or a zero.  This is an internal routine, so these         */
5165/*   restrictions are contractual and not enforced.                   */
5166/*                                                                    */
5167/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5168/* almost always be correctly rounded, but may be up to 1 ulp in      */
5169/* error in rare cases.                                               */
5170/*                                                                    */
5171/* Finite results will always be full precision and Inexact, except   */
5172/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5173/* ------------------------------------------------------------------ */
5174/* This approach used here is similar to the algorithm described in   */
5175/*                                                                    */
5176/*   Variable Precision Exponential Function, T. E. Hull and          */
5177/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5178/*   pp79-91, ACM, June 1986.                                         */
5179/*                                                                    */
5180/* with the main difference being that the iterations in the series   */
5181/* evaluation are terminated dynamically (which does not require the  */
5182/* extra variable-precision variables which are expensive in this     */
5183/* context).                                                          */
5184/*                                                                    */
5185/* The error analysis in Hull & Abrham's paper applies except for the */
5186/* round-off error accumulation during the series evaluation.  This   */
5187/* code does not precalculate the number of iterations and so cannot  */
5188/* use Horner's scheme.  Instead, the accumulation is done at double- */
5189/* precision, which ensures that the additions of the terms are exact */
5190/* and do not accumulate round-off (and any round-off errors in the   */
5191/* terms themselves move 'to the right' faster than they can          */
5192/* accumulate).  This code also extends the calculation by allowing,  */
5193/* in the spirit of other decNumber operators, the input to be more   */
5194/* precise than the result (the precision used is based on the more   */
5195/* precise of the input or requested result).                         */
5196/*                                                                    */
5197/* Implementation notes:                                              */
5198/*                                                                    */
5199/* 1. This is separated out as decExpOp so it can be called from      */
5200/*    other Mathematical functions (notably Ln) with a wider range    */
5201/*    than normal.  In particular, it can handle the slightly wider   */
5202/*    (double) range needed by Ln (which has to be able to calculate  */
5203/*    exp(-x) where x can be the tiniest number (Ntiny).              */
5204/*                                                                    */
5205/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5206/*    iterations by appoximately a third with additional (although    */
5207/*    diminishing) returns as the range is reduced to even smaller    */
5208/*    fractions.  However, h (the power of 10 used to correct the     */
5209/*    result at the end, see below) must be kept <=8 as otherwise     */
5210/*    the final result cannot be computed.  Hence the leverage is a   */
5211/*    sliding value (8-h), where potentially the range is reduced     */
5212/*    more for smaller values.                                        */
5213/*                                                                    */
5214/*    The leverage that can be applied in this way is severely        */
5215/*    limited by the cost of the raise-to-the power at the end,       */
5216/*    which dominates when the number of iterations is small (less    */
5217/*    than ten) or when rhs is short.  As an example, the adjustment  */
5218/*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5219/*                                                                    */
5220/* 3. The restrictions (especially precision) could be raised with    */
5221/*    care, but the full decNumber range seems very hard within the   */
5222/*    32-bit limits.                                                  */
5223/*                                                                    */
5224/* 4. The working precisions for the static buffers are twice the     */
5225/*    obvious size to allow for calls from decNumberPower.            */
5226/* ------------------------------------------------------------------ */
5227decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5228                         decContext *set, uInt *status) {
5229  uInt ignore=0;                   /* working status  */
5230  Int h;                           /* adjusted exponent for 0.xxxx  */
5231  Int p;                           /* working precision  */
5232  Int residue;                     /* rounding residue  */
5233  uInt needbytes;                  /* for space calculations  */
5234  const decNumber *x=rhs;          /* (may point to safe copy later)  */
5235  decContext aset, tset, dset;     /* working contexts  */
5236  Int comp;                        /* work  */
5237
5238  /* the argument is often copied to normalize it, so (unusually) it  */
5239  /* is treated like other buffers, using DECBUFFER, +1 in case  */
5240  /* DECBUFFER is 0  */
5241  decNumber bufr[D2N(DECBUFFER*2+1)];
5242  decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated  */
5243
5244  /* the working precision will be no more than set->digits+8+1  */
5245  /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER  */
5246  /* is 0 (and twice that for the accumulator)  */
5247
5248  /* buffer for t, term (working precision plus)  */
5249  decNumber buft[D2N(DECBUFFER*2+9+1)];
5250  decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated  */
5251  decNumber *t=buft;               /* term  */
5252  /* buffer for a, accumulator (working precision * 2), at least 9  */
5253  decNumber bufa[D2N(DECBUFFER*4+18+1)];
5254  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5255  decNumber *a=bufa;               /* accumulator  */
5256  /* decNumber for the divisor term; this needs at most 9 digits  */
5257  /* and so can be fixed size [16 so can use standard context]  */
5258  decNumber bufd[D2N(16)];
5259  decNumber *d=bufd;               /* divisor  */
5260  decNumber numone;                /* constant 1  */
5261
5262  #if DECCHECK
5263  Int iterations=0;                /* for later sanity check  */
5264  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5265  #endif
5266
5267  do {                                  /* protect allocated storage  */
5268    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5269      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5270        if (decNumberIsNegative(rhs))   /* -Infinity -> +0  */
5271          uprv_decNumberZero(res);
5272         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5273        }
5274       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5275      break;}
5276
5277    if (ISZERO(rhs)) {                  /* zeros -> exact 1  */
5278      uprv_decNumberZero(res);               /* make clean 1  */
5279      *res->lsu=1;                      /* ..  */
5280      break;}                           /* [no status to set]  */
5281
5282    /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path  */
5283    /* positive and negative tiny cases which will result in inexact  */
5284    /* 1.  This also allows the later add-accumulate to always be  */
5285    /* exact (because its length will never be more than twice the  */
5286    /* working precision).  */
5287    /* The comparator (tiny) needs just one digit, so use the  */
5288    /* decNumber d for it (reused as the divisor, etc., below); its  */
5289    /* exponent is such that if x is positive it will have  */
5290    /* set->digits-1 zeros between the decimal point and the digit,  */
5291    /* which is 4, and if x is negative one more zero there as the  */
5292    /* more precise result will be of the form 0.9999999 rather than  */
5293    /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0  */
5294    /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than  */
5295    /* this then the result will be 1.000000  */
5296    uprv_decNumberZero(d);                   /* clean  */
5297    *d->lsu=4;                          /* set 4 ..  */
5298    d->exponent=-set->digits;           /* * 10**(-d)  */
5299    if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case  */
5300    comp=decCompare(d, rhs, 1);         /* signless compare  */
5301    if (comp==BADINT) {
5302      *status|=DEC_Insufficient_storage;
5303      break;}
5304    if (comp>=0) {                      /* rhs < d  */
5305      Int shift=set->digits-1;
5306      uprv_decNumberZero(res);               /* set 1  */
5307      *res->lsu=1;                      /* ..  */
5308      res->digits=decShiftToMost(res->lsu, 1, shift);
5309      res->exponent=-shift;                  /* make 1.0000...  */
5310      *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly  */
5311      break;} /* tiny  */
5312
5313    /* set up the context to be used for calculating a, as this is  */
5314    /* used on both paths below  */
5315    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5316    /* accumulator bounds are as requested (could underflow)  */
5317    aset.emax=set->emax;                /* usual bounds  */
5318    aset.emin=set->emin;                /* ..  */
5319    aset.clamp=0;                       /* and no concrete format  */
5320
5321    /* calculate the adjusted (Hull & Abrham) exponent (where the  */
5322    /* decimal point is just to the left of the coefficient msd)  */
5323    h=rhs->exponent+rhs->digits;
5324    /* if h>8 then 10**h cannot be calculated safely; however, when  */
5325    /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at  */
5326    /* least 6.59E+4342944, so (due to the restriction on Emax/Emin)  */
5327    /* overflow (or underflow to 0) is guaranteed -- so this case can  */
5328    /* be handled by simply forcing the appropriate excess  */
5329    if (h>8) {                          /* overflow/underflow  */
5330      /* set up here so Power call below will over or underflow to  */
5331      /* zero; set accumulator to either 2 or 0.02  */
5332      /* [stack buffer for a is always big enough for this]  */
5333      uprv_decNumberZero(a);
5334      *a->lsu=2;                        /* not 1 but < exp(1)  */
5335      if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02  */
5336      h=8;                              /* clamp so 10**h computable  */
5337      p=9;                              /* set a working precision  */
5338      }
5339     else {                             /* h<=8  */
5340      Int maxlever=(rhs->digits>8?1:0);
5341      /* [could/should increase this for precisions >40 or so, too]  */
5342
5343      /* if h is 8, cannot normalize to a lower upper limit because  */
5344      /* the final result will not be computable (see notes above),  */
5345      /* but leverage can be applied whenever h is less than 8.  */
5346      /* Apply as much as possible, up to a MAXLEVER digits, which  */
5347      /* sets the tradeoff against the cost of the later a**(10**h).  */
5348      /* As h is increased, the working precision below also  */
5349      /* increases to compensate for the "constant digits at the  */
5350      /* front" effect.  */
5351      Int lever=MINI(8-h, maxlever);    /* leverage attainable  */
5352      Int use=-rhs->digits-lever;       /* exponent to use for RHS  */
5353      h+=lever;                         /* apply leverage selected  */
5354      if (h<0) {                        /* clamp  */
5355        use+=h;                         /* [may end up subnormal]  */
5356        h=0;
5357        }
5358      /* Take a copy of RHS if it needs normalization (true whenever x>=1)  */
5359      if (rhs->exponent!=use) {
5360        decNumber *newrhs=bufr;         /* assume will fit on stack  */
5361        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5362        if (needbytes>sizeof(bufr)) {   /* need malloc space  */
5363          allocrhs=(decNumber *)malloc(needbytes);
5364          if (allocrhs==NULL) {         /* hopeless -- abandon  */
5365            *status|=DEC_Insufficient_storage;
5366            break;}
5367          newrhs=allocrhs;              /* use the allocated space  */
5368          }
5369        uprv_decNumberCopy(newrhs, rhs);     /* copy to safe space  */
5370        newrhs->exponent=use;           /* normalize; now <1  */
5371        x=newrhs;                       /* ready for use  */
5372        /* decNumberShow(x);  */
5373        }
5374
5375      /* Now use the usual power series to evaluate exp(x).  The  */
5376      /* series starts as 1 + x + x^2/2 ... so prime ready for the  */
5377      /* third term by setting the term variable t=x, the accumulator  */
5378      /* a=1, and the divisor d=2.  */
5379
5380      /* First determine the working precision.  From Hull & Abrham  */
5381      /* this is set->digits+h+2.  However, if x is 'over-precise' we  */
5382      /* need to allow for all its digits to potentially participate  */
5383      /* (consider an x where all the excess digits are 9s) so in  */
5384      /* this case use x->digits+h+2  */
5385      p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8]  */
5386
5387      /* a and t are variable precision, and depend on p, so space  */
5388      /* must be allocated for them if necessary  */
5389
5390      /* the accumulator needs to be able to hold 2p digits so that  */
5391      /* the additions on the second and subsequent iterations are  */
5392      /* sufficiently exact.  */
5393      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5394      if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5395        allocbufa=(decNumber *)malloc(needbytes);
5396        if (allocbufa==NULL) {          /* hopeless -- abandon  */
5397          *status|=DEC_Insufficient_storage;
5398          break;}
5399        a=allocbufa;                    /* use the allocated space  */
5400        }
5401      /* the term needs to be able to hold p digits (which is  */
5402      /* guaranteed to be larger than x->digits, so the initial copy  */
5403      /* is safe); it may also be used for the raise-to-power  */
5404      /* calculation below, which needs an extra two digits  */
5405      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5406      if (needbytes>sizeof(buft)) {     /* need malloc space  */
5407        allocbuft=(decNumber *)malloc(needbytes);
5408        if (allocbuft==NULL) {          /* hopeless -- abandon  */
5409          *status|=DEC_Insufficient_storage;
5410          break;}
5411        t=allocbuft;                    /* use the allocated space  */
5412        }
5413
5414      uprv_decNumberCopy(t, x);              /* term=x  */
5415      uprv_decNumberZero(a); *a->lsu=1;      /* accumulator=1  */
5416      uprv_decNumberZero(d); *d->lsu=2;      /* divisor=2  */
5417      uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment  */
5418
5419      /* set up the contexts for calculating a, t, and d  */
5420      uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5421      dset=tset;
5422      /* accumulator bounds are set above, set precision now  */
5423      aset.digits=p*2;                  /* double  */
5424      /* term bounds avoid any underflow or overflow  */
5425      tset.digits=p;
5426      tset.emin=DEC_MIN_EMIN;           /* [emax is plenty]  */
5427      /* [dset.digits=16, etc., are sufficient]  */
5428
5429      /* finally ready to roll  */
5430      for (;;) {
5431        #if DECCHECK
5432        iterations++;
5433        #endif
5434        /* only the status from the accumulation is interesting  */
5435        /* [but it should remain unchanged after first add]  */
5436        decAddOp(a, a, t, &aset, 0, status);           /* a=a+t  */
5437        decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x  */
5438        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d  */
5439        /* the iteration ends when the term cannot affect the result,  */
5440        /* if rounded to p digits, which is when its value is smaller  */
5441        /* than the accumulator by p+1 digits.  There must also be  */
5442        /* full precision in a.  */
5443        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5444            && (a->digits>=p)) break;
5445        decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1  */
5446        } /* iterate  */
5447
5448      #if DECCHECK
5449      /* just a sanity check; comment out test to show always  */
5450      if (iterations>p+3)
5451        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5452               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5453      #endif
5454      } /* h<=8  */
5455
5456    /* apply postconditioning: a=a**(10**h) -- this is calculated  */
5457    /* at a slightly higher precision than Hull & Abrham suggest  */
5458    if (h>0) {
5459      Int seenbit=0;               /* set once a 1-bit is seen  */
5460      Int i;                       /* counter  */
5461      Int n=powers[h];             /* always positive  */
5462      aset.digits=p+2;             /* sufficient precision  */
5463      /* avoid the overhead and many extra digits of decNumberPower  */
5464      /* as all that is needed is the short 'multipliers' loop; here  */
5465      /* accumulate the answer into t  */
5466      uprv_decNumberZero(t); *t->lsu=1; /* acc=1  */
5467      for (i=1;;i++){              /* for each bit [top bit ignored]  */
5468        /* abandon if have had overflow or terminal underflow  */
5469        if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
5470          if (*status&DEC_Overflow || ISZERO(t)) break;}
5471        n=n<<1;                    /* move next bit to testable position  */
5472        if (n<0) {                 /* top bit is set  */
5473          seenbit=1;               /* OK, have a significant bit  */
5474          decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x  */
5475          }
5476        if (i==31) break;          /* that was the last bit  */
5477        if (!seenbit) continue;    /* no need to square 1  */
5478        decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square]  */
5479        } /*i*/ /* 32 bits  */
5480      /* decNumberShow(t);  */
5481      a=t;                         /* and carry on using t instead of a  */
5482      }
5483
5484    /* Copy and round the result to res  */
5485    residue=1;                          /* indicate dirt to right ..  */
5486    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5487    aset.digits=set->digits;            /* [use default rounding]  */
5488    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5489    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5490    } while(0);                         /* end protected  */
5491
5492  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
5493  if (allocbufa!=NULL) free(allocbufa); /* ..  */
5494  if (allocbuft!=NULL) free(allocbuft); /* ..  */
5495  /* [status is handled by caller]  */
5496  return res;
5497  } /* decExpOp  */
5498
5499/* ------------------------------------------------------------------ */
5500/* Initial-estimate natural logarithm table                           */
5501/*                                                                    */
5502/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5503/*           The result is a 4-digit encode of the coefficient (c=the */
5504/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5505/*           exponent (e=the bottom 2 bits encoding 0-3)              */
5506/*                                                                    */
5507/*           The resulting value is given by:                         */
5508/*                                                                    */
5509/*             v = -c * 10**(-e-3)                                    */
5510/*                                                                    */
5511/*           where e and c are extracted from entry k = LNnn[x-10]    */
5512/*           where x is truncated (NB) into the range 10 through 99,  */
5513/*           and then c = k>>2 and e = k&3.                           */
5514/* ------------------------------------------------------------------ */
5515const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5516  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5517  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5518 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5519 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5520 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5521 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5522 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5523  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5524 10130,  6046, 20055};
5525
5526/* ------------------------------------------------------------------ */
5527/* decLnOp -- effect natural logarithm                                */
5528/*                                                                    */
5529/*   This computes C = ln(A)                                          */
5530/*                                                                    */
5531/*   res is C, the result.  C may be A                                */
5532/*   rhs is A                                                         */
5533/*   set is the context; note that rounding mode has no effect        */
5534/*                                                                    */
5535/* C must have space for set->digits digits.                          */
5536/*                                                                    */
5537/* Notable cases:                                                     */
5538/*   A<0 -> Invalid                                                   */
5539/*   A=0 -> -Infinity (Exact)                                         */
5540/*   A=+Infinity -> +Infinity (Exact)                                 */
5541/*   A=1 exactly -> 0 (Exact)                                         */
5542/*                                                                    */
5543/* Restrictions (as for Exp):                                         */
5544/*                                                                    */
5545/*   digits, emax, and -emin in the context must be less than         */
5546/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5547/*   bounds or a zero.  This is an internal routine, so these         */
5548/*   restrictions are contractual and not enforced.                   */
5549/*                                                                    */
5550/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5551/* almost always be correctly rounded, but may be up to 1 ulp in      */
5552/* error in rare cases.                                               */
5553/* ------------------------------------------------------------------ */
5554/* The result is calculated using Newton's method, with each          */
5555/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5556/* Epperson 1989.                                                     */
5557/*                                                                    */
5558/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5559/* This has to be calculated at the sum of the precision of x and the */
5560/* working precision.                                                 */
5561/*                                                                    */
5562/* Implementation notes:                                              */
5563/*                                                                    */
5564/* 1. This is separated out as decLnOp so it can be called from       */
5565/*    other Mathematical functions (e.g., Log 10) with a wider range  */
5566/*    than normal.  In particular, it can handle the slightly wider   */
5567/*    (+9+2) range needed by a power function.                        */
5568/*                                                                    */
5569/* 2. The speed of this function is about 10x slower than exp, as     */
5570/*    it typically needs 4-6 iterations for short numbers, and the    */
5571/*    extra precision needed adds a squaring effect, twice.           */
5572/*                                                                    */
5573/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5574/*    as these are common requests.  ln(10) is used by log10(x).      */
5575/*                                                                    */
5576/* 4. An iteration might be saved by widening the LNnn table, and     */
5577/*    would certainly save at least one if it were made ten times     */
5578/*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5579/*    However, for most practical evaluations, at least four or five  */
5580/*    iterations will be neede -- so this would only speed up by      */
5581/*    20-25% and that probably does not justify increasing the table  */
5582/*    size.                                                           */
5583/*                                                                    */
5584/* 5. The static buffers are larger than might be expected to allow   */
5585/*    for calls from decNumberPower.                                  */
5586/* ------------------------------------------------------------------ */
5587decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5588                    decContext *set, uInt *status) {
5589  uInt ignore=0;                   /* working status accumulator  */
5590  uInt needbytes;                  /* for space calculations  */
5591  Int residue;                     /* rounding residue  */
5592  Int r;                           /* rhs=f*10**r [see below]  */
5593  Int p;                           /* working precision  */
5594  Int pp;                          /* precision for iteration  */
5595  Int t;                           /* work  */
5596
5597  /* buffers for a (accumulator, typically precision+2) and b  */
5598  /* (adjustment calculator, same size)  */
5599  decNumber bufa[D2N(DECBUFFER+12)];
5600  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5601  decNumber *a=bufa;               /* accumulator/work  */
5602  decNumber bufb[D2N(DECBUFFER*2+2)];
5603  decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated  */
5604  decNumber *b=bufb;               /* adjustment/work  */
5605
5606  decNumber  numone;               /* constant 1  */
5607  decNumber  cmp;                  /* work  */
5608  decContext aset, bset;           /* working contexts  */
5609
5610  #if DECCHECK
5611  Int iterations=0;                /* for later sanity check  */
5612  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5613  #endif
5614
5615  do {                                  /* protect allocated storage  */
5616    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5617      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5618        if (decNumberIsNegative(rhs))   /* -Infinity -> error  */
5619          *status|=DEC_Invalid_operation;
5620         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5621        }
5622       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5623      break;}
5624
5625    if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity  */
5626      uprv_decNumberZero(res);               /* make clean  */
5627      res->bits=DECINF|DECNEG;          /* set - infinity  */
5628      break;}                           /* [no status to set]  */
5629
5630    /* Non-zero negatives are bad...  */
5631    if (decNumberIsNegative(rhs)) {     /* -x -> error  */
5632      *status|=DEC_Invalid_operation;
5633      break;}
5634
5635    /* Here, rhs is positive, finite, and in range  */
5636
5637    /* lookaside fastpath code for ln(2) and ln(10) at common lengths  */
5638    if (rhs->exponent==0 && set->digits<=40) {
5639      #if DECDPUN==1
5640      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10)  */
5641      #else
5642      if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10)  */
5643      #endif
5644        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5645        #define LN10 "2.302585092994045684017991454684364207601"
5646        uprv_decNumberFromString(res, LN10, &aset);
5647        *status|=(DEC_Inexact | DEC_Rounded); /* is inexact  */
5648        break;}
5649      if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2)  */
5650        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5651        #define LN2 "0.6931471805599453094172321214581765680755"
5652        uprv_decNumberFromString(res, LN2, &aset);
5653        *status|=(DEC_Inexact | DEC_Rounded);
5654        break;}
5655      } /* integer and short  */
5656
5657    /* Determine the working precision.  This is normally the  */
5658    /* requested precision + 2, with a minimum of 9.  However, if  */
5659    /* the rhs is 'over-precise' then allow for all its digits to  */
5660    /* potentially participate (consider an rhs where all the excess  */
5661    /* digits are 9s) so in this case use rhs->digits+2.  */
5662    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5663
5664    /* Allocate space for the accumulator and the high-precision  */
5665    /* adjustment calculator, if necessary.  The accumulator must  */
5666    /* be able to hold p digits, and the adjustment up to  */
5667    /* rhs->digits+p digits.  They are also made big enough for 16  */
5668    /* digits so that they can be used for calculating the initial  */
5669    /* estimate.  */
5670    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5671    if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5672      allocbufa=(decNumber *)malloc(needbytes);
5673      if (allocbufa==NULL) {          /* hopeless -- abandon  */
5674        *status|=DEC_Insufficient_storage;
5675        break;}
5676      a=allocbufa;                    /* use the allocated space  */
5677      }
5678    pp=p+rhs->digits;
5679    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5680    if (needbytes>sizeof(bufb)) {     /* need malloc space  */
5681      allocbufb=(decNumber *)malloc(needbytes);
5682      if (allocbufb==NULL) {          /* hopeless -- abandon  */
5683        *status|=DEC_Insufficient_storage;
5684        break;}
5685      b=allocbufb;                    /* use the allocated space  */
5686      }
5687
5688    /* Prepare an initial estimate in acc. Calculate this by  */
5689    /* considering the coefficient of x to be a normalized fraction,  */
5690    /* f, with the decimal point at far left and multiplied by  */
5691    /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and  */
5692    /*   ln(x) = ln(f) + ln(10)*r  */
5693    /* Get the initial estimate for ln(f) from a small lookup  */
5694    /* table (see above) indexed by the first two digits of f,  */
5695    /* truncated.  */
5696
5697    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended  */
5698    r=rhs->exponent+rhs->digits;        /* 'normalised' exponent  */
5699    uprv_decNumberFromInt32(a, r);           /* a=r  */
5700    uprv_decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585)  */
5701    b->exponent=-6;                     /*  ..  */
5702    decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b  */
5703    /* now get top two digits of rhs into b by simple truncate and  */
5704    /* force to integer  */
5705    residue=0;                          /* (no residue)  */
5706    aset.digits=2; aset.round=DEC_ROUND_DOWN;
5707    decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten  */
5708    b->exponent=0;                      /* make integer  */
5709    t=decGetInt(b);                     /* [cannot fail]  */
5710    if (t<10) t=X10(t);                 /* adjust single-digit b  */
5711    t=LNnn[t-10];                       /* look up ln(b)  */
5712    uprv_decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient  */
5713    b->exponent=-(t&3)-3;               /* set exponent  */
5714    b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve  */
5715    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore  */
5716    decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b  */
5717    /* the initial estimate is now in a, with up to 4 digits correct.  */
5718    /* When rhs is at or near Nmax the estimate will be low, so we  */
5719    /* will approach it from below, avoiding overflow when calling exp.  */
5720
5721    uprv_decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment  */
5722
5723    /* accumulator bounds are as requested (could underflow, but  */
5724    /* cannot overflow)  */
5725    aset.emax=set->emax;
5726    aset.emin=set->emin;
5727    aset.clamp=0;                       /* no concrete format  */
5728    /* set up a context to be used for the multiply and subtract  */
5729    bset=aset;
5730    bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the  */
5731    bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation  */
5732                                        /* [see decExpOp call below]  */
5733    /* for each iteration double the number of digits to calculate,  */
5734    /* up to a maximum of p  */
5735    pp=9;                               /* initial precision  */
5736    /* [initially 9 as then the sequence starts 7+2, 16+2, and  */
5737    /* 34+2, which is ideal for standard-sized numbers]  */
5738    aset.digits=pp;                     /* working context  */
5739    bset.digits=pp+rhs->digits;         /* wider context  */
5740    for (;;) {                          /* iterate  */
5741      #if DECCHECK
5742      iterations++;
5743      if (iterations>24) break;         /* consider 9 * 2**24  */
5744      #endif
5745      /* calculate the adjustment (exp(-a)*x-1) into b.  This is a  */
5746      /* catastrophic subtraction but it really is the difference  */
5747      /* from 1 that is of interest.  */
5748      /* Use the internal entry point to Exp as it allows the double  */
5749      /* range for calculating exp(-a) when a is the tiniest subnormal.  */
5750      a->bits^=DECNEG;                  /* make -a  */
5751      decExpOp(b, a, &bset, &ignore);   /* b=exp(-a)  */
5752      a->bits^=DECNEG;                  /* restore sign of a  */
5753      /* now multiply by rhs and subtract 1, at the wider precision  */
5754      decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs  */
5755      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1  */
5756
5757      /* the iteration ends when the adjustment cannot affect the  */
5758      /* result by >=0.5 ulp (at the requested digits), which  */
5759      /* is when its value is smaller than the accumulator by  */
5760      /* set->digits+1 digits (or it is zero) -- this is a looser  */
5761      /* requirement than for Exp because all that happens to the  */
5762      /* accumulator after this is the final rounding (but note that  */
5763      /* there must also be full precision in a, or a=0).  */
5764
5765      if (decNumberIsZero(b) ||
5766          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5767        if (a->digits==p) break;
5768        if (decNumberIsZero(a)) {
5769          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ?  */
5770          if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0  */
5771           else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact  */
5772          break;
5773          }
5774        /* force padding if adjustment has gone to 0 before full length  */
5775        if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5776        }
5777
5778      /* not done yet ...  */
5779      decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate  */
5780      if (pp==p) continue;                   /* precision is at maximum  */
5781      /* lengthen the next calculation  */
5782      pp=pp*2;                               /* double precision  */
5783      if (pp>p) pp=p;                        /* clamp to maximum  */
5784      aset.digits=pp;                        /* working context  */
5785      bset.digits=pp+rhs->digits;            /* wider context  */
5786      } /* Newton's iteration  */
5787
5788    #if DECCHECK
5789    /* just a sanity check; remove the test to show always  */
5790    if (iterations>24)
5791      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5792            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5793    #endif
5794
5795    /* Copy and round the result to res  */
5796    residue=1;                          /* indicate dirt to right  */
5797    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5798    aset.digits=set->digits;            /* [use default rounding]  */
5799    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5800    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5801    } while(0);                         /* end protected  */
5802
5803  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
5804  if (allocbufb!=NULL) free(allocbufb); /* ..  */
5805  /* [status is handled by caller]  */
5806  return res;
5807  } /* decLnOp  */
5808
5809/* ------------------------------------------------------------------ */
5810/* decQuantizeOp  -- force exponent to requested value                */
5811/*                                                                    */
5812/*   This computes C = op(A, B), where op adjusts the coefficient     */
5813/*   of C (by rounding or shifting) such that the exponent (-scale)   */
5814/*   of C has the value B or matches the exponent of B.               */
5815/*   The numerical value of C will equal A, except for the effects of */
5816/*   any rounding that occurred.                                      */
5817/*                                                                    */
5818/*   res is C, the result.  C may be A or B                           */
5819/*   lhs is A, the number to adjust                                   */
5820/*   rhs is B, the requested exponent                                 */
5821/*   set is the context                                               */
5822/*   quant is 1 for quantize or 0 for rescale                         */
5823/*   status is the status accumulator (this can be called without     */
5824/*          risk of control loss)                                     */
5825/*                                                                    */
5826/* C must have space for set->digits digits.                          */
5827/*                                                                    */
5828/* Unless there is an error or the result is infinite, the exponent   */
5829/* after the operation is guaranteed to be that requested.            */
5830/* ------------------------------------------------------------------ */
5831static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5832                                 const decNumber *rhs, decContext *set,
5833                                 Flag quant, uInt *status) {
5834  #if DECSUBSET
5835  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
5836  decNumber *allocrhs=NULL;        /* .., rhs  */
5837  #endif
5838  const decNumber *inrhs=rhs;      /* save original rhs  */
5839  Int   reqdigits=set->digits;     /* requested DIGITS  */
5840  Int   reqexp;                    /* requested exponent [-scale]  */
5841  Int   residue=0;                 /* rounding residue  */
5842  Int   etiny=set->emin-(reqdigits-1);
5843
5844  #if DECCHECK
5845  if (decCheckOperands(res, lhs, rhs, set)) return res;
5846  #endif
5847
5848  do {                             /* protect allocated storage  */
5849    #if DECSUBSET
5850    if (!set->extended) {
5851      /* reduce operands and set lostDigits status, as needed  */
5852      if (lhs->digits>reqdigits) {
5853        alloclhs=decRoundOperand(lhs, set, status);
5854        if (alloclhs==NULL) break;
5855        lhs=alloclhs;
5856        }
5857      if (rhs->digits>reqdigits) { /* [this only checks lostDigits]  */
5858        allocrhs=decRoundOperand(rhs, set, status);
5859        if (allocrhs==NULL) break;
5860        rhs=allocrhs;
5861        }
5862      }
5863    #endif
5864    /* [following code does not require input rounding]  */
5865
5866    /* Handle special values  */
5867    if (SPECIALARGS) {
5868      /* NaNs get usual processing  */
5869      if (SPECIALARGS & (DECSNAN | DECNAN))
5870        decNaNs(res, lhs, rhs, set, status);
5871      /* one infinity but not both is bad  */
5872      else if ((lhs->bits ^ rhs->bits) & DECINF)
5873        *status|=DEC_Invalid_operation;
5874      /* both infinity: return lhs  */
5875      else uprv_decNumberCopy(res, lhs);          /* [nop if in place]  */
5876      break;
5877      }
5878
5879    /* set requested exponent  */
5880    if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents  */
5881     else {                             /* rescale -- use value of rhs  */
5882      /* Original rhs must be an integer that fits and is in range,  */
5883      /* which could be from -1999999997 to +999999999, thanks to  */
5884      /* subnormals  */
5885      reqexp=decGetInt(inrhs);               /* [cannot fail]  */
5886      }
5887
5888    #if DECSUBSET
5889    if (!set->extended) etiny=set->emin;     /* no subnormals  */
5890    #endif
5891
5892    if (reqexp==BADINT                       /* bad (rescale only) or ..  */
5893     || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or ..  */
5894     || (reqexp<etiny)                       /* < lowest  */
5895     || (reqexp>set->emax)) {                /* > emax  */
5896      *status|=DEC_Invalid_operation;
5897      break;}
5898
5899    /* the RHS has been processed, so it can be overwritten now if necessary  */
5900    if (ISZERO(lhs)) {                       /* zero coefficient unchanged  */
5901      uprv_decNumberCopy(res, lhs);               /* [nop if in place]  */
5902      res->exponent=reqexp;                  /* .. just set exponent  */
5903      #if DECSUBSET
5904      if (!set->extended) res->bits=0;       /* subset specification; no -0  */
5905      #endif
5906      }
5907     else {                                  /* non-zero lhs  */
5908      Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed  */
5909      /* if adjusted coefficient will definitely not fit, give up now  */
5910      if ((lhs->digits-adjust)>reqdigits) {
5911        *status|=DEC_Invalid_operation;
5912        break;
5913        }
5914
5915      if (adjust>0) {                        /* increasing exponent  */
5916        /* this will decrease the length of the coefficient by adjust  */
5917        /* digits, and must round as it does so  */
5918        decContext workset;                  /* work  */
5919        workset=*set;                        /* clone rounding, etc.  */
5920        workset.digits=lhs->digits-adjust;   /* set requested length  */
5921        /* [note that the latter can be <1, here]  */
5922        decCopyFit(res, lhs, &workset, &residue, status); /* fit to result  */
5923        decApplyRound(res, &workset, residue, status);    /* .. and round  */
5924        residue=0;                                        /* [used]  */
5925        /* If just rounded a 999s case, exponent will be off by one;  */
5926        /* adjust back (after checking space), if so.  */
5927        if (res->exponent>reqexp) {
5928          /* re-check needed, e.g., for quantize(0.9999, 0.001) under  */
5929          /* set->digits==3  */
5930          if (res->digits==reqdigits) {      /* cannot shift by 1  */
5931            *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these]  */
5932            *status|=DEC_Invalid_operation;
5933            break;
5934            }
5935          res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift  */
5936          res->exponent--;                   /* (re)adjust the exponent.  */
5937          }
5938        #if DECSUBSET
5939        if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0  */
5940        #endif
5941        } /* increase  */
5942       else /* adjust<=0 */ {                /* decreasing or = exponent  */
5943        /* this will increase the length of the coefficient by -adjust  */
5944        /* digits, by adding zero or more trailing zeros; this is  */
5945        /* already checked for fit, above  */
5946        uprv_decNumberCopy(res, lhs);             /* [it will fit]  */
5947        /* if padding needed (adjust<0), add it now...  */
5948        if (adjust<0) {
5949          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5950          res->exponent+=adjust;             /* adjust the exponent  */
5951          }
5952        } /* decrease  */
5953      } /* non-zero  */
5954
5955    /* Check for overflow [do not use Finalize in this case, as an  */
5956    /* overflow here is a "don't fit" situation]  */
5957    if (res->exponent>set->emax-res->digits+1) {  /* too big  */
5958      *status|=DEC_Invalid_operation;
5959      break;
5960      }
5961     else {
5962      decFinalize(res, set, &residue, status);    /* set subnormal flags  */
5963      *status&=~DEC_Underflow;          /* suppress Underflow [as per 754]  */
5964      }
5965    } while(0);                         /* end protected  */
5966
5967  #if DECSUBSET
5968  if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used  */
5969  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5970  #endif
5971  return res;
5972  } /* decQuantizeOp  */
5973
5974/* ------------------------------------------------------------------ */
5975/* decCompareOp -- compare, min, or max two Numbers                   */
5976/*                                                                    */
5977/*   This computes C = A ? B and carries out one of four operations:  */
5978/*     COMPARE    -- returns the signum (as a number) giving the      */
5979/*                   result of a comparison unless one or both        */
5980/*                   operands is a NaN (in which case a NaN results)  */
5981/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5982/*                   Invalid operation.                               */
5983/*     COMPMAX    -- returns the larger of the operands, using the    */
5984/*                   754 maxnum operation                             */
5985/*     COMPMAXMAG -- ditto, comparing absolute values                 */
5986/*     COMPMIN    -- the 754 minnum operation                         */
5987/*     COMPMINMAG -- ditto, comparing absolute values                 */
5988/*     COMTOTAL   -- returns the signum (as a number) giving the      */
5989/*                   result of a comparison using 754 total ordering  */
5990/*                                                                    */
5991/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
5992/*   lhs is A                                                         */
5993/*   rhs is B                                                         */
5994/*   set is the context                                               */
5995/*   op  is the operation flag                                        */
5996/*   status is the usual accumulator                                  */
5997/*                                                                    */
5998/* C must have space for one digit for COMPARE or set->digits for     */
5999/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6000/* ------------------------------------------------------------------ */
6001/* The emphasis here is on speed for common cases, and avoiding       */
6002/* coefficient comparison if possible.                                */
6003/* ------------------------------------------------------------------ */
6004static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6005                         const decNumber *rhs, decContext *set,
6006                         Flag op, uInt *status) {
6007  #if DECSUBSET
6008  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
6009  decNumber *allocrhs=NULL;        /* .., rhs  */
6010  #endif
6011  Int   result=0;                  /* default result value  */
6012  uByte merged;                    /* work  */
6013
6014  #if DECCHECK
6015  if (decCheckOperands(res, lhs, rhs, set)) return res;
6016  #endif
6017
6018  do {                             /* protect allocated storage  */
6019    #if DECSUBSET
6020    if (!set->extended) {
6021      /* reduce operands and set lostDigits status, as needed  */
6022      if (lhs->digits>set->digits) {
6023        alloclhs=decRoundOperand(lhs, set, status);
6024        if (alloclhs==NULL) {result=BADINT; break;}
6025        lhs=alloclhs;
6026        }
6027      if (rhs->digits>set->digits) {
6028        allocrhs=decRoundOperand(rhs, set, status);
6029        if (allocrhs==NULL) {result=BADINT; break;}
6030        rhs=allocrhs;
6031        }
6032      }
6033    #endif
6034    /* [following code does not require input rounding]  */
6035
6036    /* If total ordering then handle differing signs 'up front'  */
6037    if (op==COMPTOTAL) {                /* total ordering  */
6038      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6039        result=-1;
6040        break;
6041        }
6042      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6043        result=+1;
6044        break;
6045        }
6046      }
6047
6048    /* handle NaNs specially; let infinities drop through  */
6049    /* This assumes sNaN (even just one) leads to NaN.  */
6050    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6051    if (merged) {                       /* a NaN bit set  */
6052      if (op==COMPARE);                 /* result will be NaN  */
6053       else if (op==COMPSIG)            /* treat qNaN as sNaN  */
6054        *status|=DEC_Invalid_operation | DEC_sNaN;
6055       else if (op==COMPTOTAL) {        /* total ordering, always finite  */
6056        /* signs are known to be the same; compute the ordering here  */
6057        /* as if the signs are both positive, then invert for negatives  */
6058        if (!decNumberIsNaN(lhs)) result=-1;
6059         else if (!decNumberIsNaN(rhs)) result=+1;
6060         /* here if both NaNs  */
6061         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6062         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6063         else { /* both NaN or both sNaN  */
6064          /* now it just depends on the payload  */
6065          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6066                                rhs->lsu, D2U(rhs->digits), 0);
6067          /* [Error not possible, as these are 'aligned']  */
6068          } /* both same NaNs  */
6069        if (decNumberIsNegative(lhs)) result=-result;
6070        break;
6071        } /* total order  */
6072
6073       else if (merged & DECSNAN);           /* sNaN -> qNaN  */
6074       else { /* here if MIN or MAX and one or two quiet NaNs  */
6075        /* min or max -- 754 rules ignore single NaN  */
6076        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6077          /* just one NaN; force choice to be the non-NaN operand  */
6078          op=COMPMAX;
6079          if (lhs->bits & DECNAN) result=-1; /* pick rhs  */
6080                             else result=+1; /* pick lhs  */
6081          break;
6082          }
6083        } /* max or min  */
6084      op=COMPNAN;                            /* use special path  */
6085      decNaNs(res, lhs, rhs, set, status);   /* propagate NaN  */
6086      break;
6087      }
6088    /* have numbers  */
6089    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6090     else result=decCompare(lhs, rhs, 0);    /* sign matters  */
6091    } while(0);                              /* end protected  */
6092
6093  if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare  */
6094   else {
6095    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum  */
6096      if (op==COMPTOTAL && result==0) {
6097        /* operands are numerically equal or same NaN (and same sign,  */
6098        /* tested first); if identical, leave result 0  */
6099        if (lhs->exponent!=rhs->exponent) {
6100          if (lhs->exponent<rhs->exponent) result=-1;
6101           else result=+1;
6102          if (decNumberIsNegative(lhs)) result=-result;
6103          } /* lexp!=rexp  */
6104        } /* total-order by exponent  */
6105      uprv_decNumberZero(res);               /* [always a valid result]  */
6106      if (result!=0) {                  /* must be -1 or +1  */
6107        *res->lsu=1;
6108        if (result<0) res->bits=DECNEG;
6109        }
6110      }
6111     else if (op==COMPNAN);             /* special, drop through  */
6112     else {                             /* MAX or MIN, non-NaN result  */
6113      Int residue=0;                    /* rounding accumulator  */
6114      /* choose the operand for the result  */
6115      const decNumber *choice;
6116      if (result==0) { /* operands are numerically equal  */
6117        /* choose according to sign then exponent (see 754)  */
6118        uByte slhs=(lhs->bits & DECNEG);
6119        uByte srhs=(rhs->bits & DECNEG);
6120        #if DECSUBSET
6121        if (!set->extended) {           /* subset: force left-hand  */
6122          op=COMPMAX;
6123          result=+1;
6124          }
6125        else
6126        #endif
6127        if (slhs!=srhs) {          /* signs differ  */
6128          if (slhs) result=-1;     /* rhs is max  */
6129               else result=+1;     /* lhs is max  */
6130          }
6131         else if (slhs && srhs) {  /* both negative  */
6132          if (lhs->exponent<rhs->exponent) result=+1;
6133                                      else result=-1;
6134          /* [if equal, use lhs, technically identical]  */
6135          }
6136         else {                    /* both positive  */
6137          if (lhs->exponent>rhs->exponent) result=+1;
6138                                      else result=-1;
6139          /* [ditto]  */
6140          }
6141        } /* numerically equal  */
6142      /* here result will be non-0; reverse if looking for MIN  */
6143      if (op==COMPMIN || op==COMPMINMAG) result=-result;
6144      choice=(result>0 ? lhs : rhs);    /* choose  */
6145      /* copy chosen to result, rounding if need be  */
6146      decCopyFit(res, choice, set, &residue, status);
6147      decFinish(res, set, &residue, status);
6148      }
6149    }
6150  #if DECSUBSET
6151  if (allocrhs!=NULL) free(allocrhs);   /* free any storage used  */
6152  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
6153  #endif
6154  return res;
6155  } /* decCompareOp  */
6156
6157/* ------------------------------------------------------------------ */
6158/* decCompare -- compare two decNumbers by numerical value            */
6159/*                                                                    */
6160/*  This routine compares A ? B without altering them.                */
6161/*                                                                    */
6162/*  Arg1 is A, a decNumber which is not a NaN                         */
6163/*  Arg2 is B, a decNumber which is not a NaN                         */
6164/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6165/*                                                                    */
6166/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6167/*  (the only possible failure is an allocation error)                */
6168/* ------------------------------------------------------------------ */
6169static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6170                      Flag abs_c) {
6171  Int   result;                    /* result value  */
6172  Int   sigr;                      /* rhs signum  */
6173  Int   compare;                   /* work  */
6174
6175  result=1;                                  /* assume signum(lhs)  */
6176  if (ISZERO(lhs)) result=0;
6177  if (abs_c) {
6178    if (ISZERO(rhs)) return result;          /* LHS wins or both 0  */
6179    /* RHS is non-zero  */
6180    if (result==0) return -1;                /* LHS is 0; RHS wins  */
6181    /* [here, both non-zero, result=1]  */
6182    }
6183   else {                                    /* signs matter  */
6184    if (result && decNumberIsNegative(lhs)) result=-1;
6185    sigr=1;                                  /* compute signum(rhs)  */
6186    if (ISZERO(rhs)) sigr=0;
6187     else if (decNumberIsNegative(rhs)) sigr=-1;
6188    if (result > sigr) return +1;            /* L > R, return 1  */
6189    if (result < sigr) return -1;            /* L < R, return -1  */
6190    if (result==0) return 0;                   /* both 0  */
6191    }
6192
6193  /* signums are the same; both are non-zero  */
6194  if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities  */
6195    if (decNumberIsInfinite(rhs)) {
6196      if (decNumberIsInfinite(lhs)) result=0;/* both infinite  */
6197       else result=-result;                  /* only rhs infinite  */
6198      }
6199    return result;
6200    }
6201  /* must compare the coefficients, allowing for exponents  */
6202  if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger  */
6203    /* swap sides, and sign  */
6204    const decNumber *temp=lhs;
6205    lhs=rhs;
6206    rhs=temp;
6207    result=-result;
6208    }
6209  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6210                         rhs->lsu, D2U(rhs->digits),
6211                         rhs->exponent-lhs->exponent);
6212  if (compare!=BADINT) compare*=result;      /* comparison succeeded  */
6213  return compare;
6214  } /* decCompare  */
6215
6216/* ------------------------------------------------------------------ */
6217/* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6218/*                                                                    */
6219/*  This routine compares A ? B*10**E where A and B are unit arrays   */
6220/*  A is a plain integer                                              */
6221/*  B has an exponent of E (which must be non-negative)               */
6222/*                                                                    */
6223/*  Arg1 is A first Unit (lsu)                                        */
6224/*  Arg2 is A length in Units                                         */
6225/*  Arg3 is B first Unit (lsu)                                        */
6226/*  Arg4 is B length in Units                                         */
6227/*  Arg5 is E (0 if the units are aligned)                            */
6228/*                                                                    */
6229/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6230/*  (the only possible failure is an allocation error, which can      */
6231/*  only occur if E!=0)                                               */
6232/* ------------------------------------------------------------------ */
6233static Int decUnitCompare(const Unit *a, Int alength,
6234                          const Unit *b, Int blength, Int exp) {
6235  Unit  *acc;                      /* accumulator for result  */
6236  Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer  */
6237  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
6238  Int   accunits, need;            /* units in use or needed for acc  */
6239  const Unit *l, *r, *u;           /* work  */
6240  Int   expunits, exprem, result;  /* ..  */
6241
6242  if (exp==0) {                    /* aligned; fastpath  */
6243    if (alength>blength) return 1;
6244    if (alength<blength) return -1;
6245    /* same number of units in both -- need unit-by-unit compare  */
6246    l=a+alength-1;
6247    r=b+alength-1;
6248    for (;l>=a; l--, r--) {
6249      if (*l>*r) return 1;
6250      if (*l<*r) return -1;
6251      }
6252    return 0;                      /* all units match  */
6253    } /* aligned  */
6254
6255  /* Unaligned.  If one is >1 unit longer than the other, padded  */
6256  /* approximately, then can return easily  */
6257  if (alength>blength+(Int)D2U(exp)) return 1;
6258  if (alength+1<blength+(Int)D2U(exp)) return -1;
6259
6260  /* Need to do a real subtract.  For this, a result buffer is needed  */
6261  /* even though only the sign is of interest.  Its length needs  */
6262  /* to be the larger of alength and padded blength, +2  */
6263  need=blength+D2U(exp);                /* maximum real length of B  */
6264  if (need<alength) need=alength;
6265  need+=2;
6266  acc=accbuff;                          /* assume use local buffer  */
6267  if (need*sizeof(Unit)>sizeof(accbuff)) {
6268    allocacc=(Unit *)malloc(need*sizeof(Unit));
6269    if (allocacc==NULL) return BADINT;  /* hopeless -- abandon  */
6270    acc=allocacc;
6271    }
6272  /* Calculate units and remainder from exponent.  */
6273  expunits=exp/DECDPUN;
6274  exprem=exp%DECDPUN;
6275  /* subtract [A+B*(-m)]  */
6276  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6277                         -(Int)powers[exprem]);
6278  /* [UnitAddSub result may have leading zeros, even on zero]  */
6279  if (accunits<0) result=-1;            /* negative result  */
6280   else {                               /* non-negative result  */
6281    /* check units of the result before freeing any storage  */
6282    for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6283    result=(*u==0 ? 0 : +1);
6284    }
6285  /* clean up and return the result  */
6286  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
6287  return result;
6288  } /* decUnitCompare  */
6289
6290/* ------------------------------------------------------------------ */
6291/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6292/*                                                                    */
6293/*  This routine performs the calculation:                            */
6294/*                                                                    */
6295/*  C=A+(B*M)                                                         */
6296/*                                                                    */
6297/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6298/*                                                                    */
6299/*  A may be shorter or longer than B.                                */
6300/*                                                                    */
6301/*  Leading zeros are not removed after a calculation.  The result is */
6302/*  either the same length as the longer of A and B (adding any       */
6303/*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6304/*                                                                    */
6305/*  A and B content are not altered unless C is also A or B.          */
6306/*  C may be the same array as A or B, but only if no zero padding is */
6307/*  requested (that is, C may be B only if bshift==0).                */
6308/*  C is filled from the lsu; only those units necessary to complete  */
6309/*  the calculation are referenced.                                   */
6310/*                                                                    */
6311/*  Arg1 is A first Unit (lsu)                                        */
6312/*  Arg2 is A length in Units                                         */
6313/*  Arg3 is B first Unit (lsu)                                        */
6314/*  Arg4 is B length in Units                                         */
6315/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6316/*  Arg6 is C first Unit (lsu)                                        */
6317/*  Arg7 is M, the multiplier                                         */
6318/*                                                                    */
6319/*  returns the count of Units written to C, which will be non-zero   */
6320/*  and negated if the result is negative.  That is, the sign of the  */
6321/*  returned Int is the sign of the result (positive for zero) and    */
6322/*  the absolute value of the Int is the count of Units.              */
6323/*                                                                    */
6324/*  It is the caller's responsibility to make sure that C size is     */
6325/*  safe, allowing space if necessary for a one-Unit carry.           */
6326/*                                                                    */
6327/*  This routine is severely performance-critical; *any* change here  */
6328/*  must be measured (timed) to assure no performance degradation.    */
6329/*  In particular, trickery here tends to be counter-productive, as   */
6330/*  increased complexity of code hurts register optimizations on      */
6331/*  register-poor architectures.  Avoiding divisions is nearly        */
6332/*  always a Good Idea, however.                                      */
6333/*                                                                    */
6334/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6335/* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6336/* ------------------------------------------------------------------ */
6337static Int decUnitAddSub(const Unit *a, Int alength,
6338                         const Unit *b, Int blength, Int bshift,
6339                         Unit *c, Int m) {
6340  const Unit *alsu=a;              /* A lsu [need to remember it]  */
6341  Unit *clsu=c;                    /* C ditto  */
6342  Unit *minC;                      /* low water mark for C  */
6343  Unit *maxC;                      /* high water mark for C  */
6344  eInt carry=0;                    /* carry integer (could be Long)  */
6345  Int  add;                        /* work  */
6346  #if DECDPUN<=4                   /* myriadal, millenary, etc.  */
6347  Int  est;                        /* estimated quotient  */
6348  #endif
6349
6350  #if DECTRACE
6351  if (alength<1 || blength<1)
6352    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6353  #endif
6354
6355  maxC=c+alength;                  /* A is usually the longer  */
6356  minC=c+blength;                  /* .. and B the shorter  */
6357  if (bshift!=0) {                 /* B is shifted; low As copy across  */
6358    minC+=bshift;
6359    /* if in place [common], skip copy unless there's a gap [rare]  */
6360    if (a==c && bshift<=alength) {
6361      c+=bshift;
6362      a+=bshift;
6363      }
6364     else for (; c<clsu+bshift; a++, c++) {  /* copy needed  */
6365      if (a<alsu+alength) *c=*a;
6366       else *c=0;
6367      }
6368    }
6369  if (minC>maxC) { /* swap  */
6370    Unit *hold=minC;
6371    minC=maxC;
6372    maxC=hold;
6373    }
6374
6375  /* For speed, do the addition as two loops; the first where both A  */
6376  /* and B contribute, and the second (if necessary) where only one or  */
6377  /* other of the numbers contribute.  */
6378  /* Carry handling is the same (i.e., duplicated) in each case.  */
6379  for (; c<minC; c++) {
6380    carry+=*a;
6381    a++;
6382    carry+=((eInt)*b)*m;                /* [special-casing m=1/-1  */
6383    b++;                                /* here is not a win]  */
6384    /* here carry is new Unit of digits; it could be +ve or -ve  */
6385    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6386      *c=(Unit)carry;
6387      carry=0;
6388      continue;
6389      }
6390    #if DECDPUN==4                           /* use divide-by-multiply  */
6391      if (carry>=0) {
6392        est=(((ueInt)carry>>11)*53687)>>18;
6393        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6394        carry=est;                           /* likely quotient [89%]  */
6395        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6396        carry++;
6397        *c-=DECDPUNMAX+1;
6398        continue;
6399        }
6400      /* negative case  */
6401      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6402      est=(((ueInt)carry>>11)*53687)>>18;
6403      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6404      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6405      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6406      carry++;
6407      *c-=DECDPUNMAX+1;
6408    #elif DECDPUN==3
6409      if (carry>=0) {
6410        est=(((ueInt)carry>>3)*16777)>>21;
6411        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6412        carry=est;                           /* likely quotient [99%]  */
6413        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6414        carry++;
6415        *c-=DECDPUNMAX+1;
6416        continue;
6417        }
6418      /* negative case  */
6419      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6420      est=(((ueInt)carry>>3)*16777)>>21;
6421      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6422      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6423      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6424      carry++;
6425      *c-=DECDPUNMAX+1;
6426    #elif DECDPUN<=2
6427      /* Can use QUOT10 as carry <= 4 digits  */
6428      if (carry>=0) {
6429        est=QUOT10(carry, DECDPUN);
6430        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6431        carry=est;                           /* quotient  */
6432        continue;
6433        }
6434      /* negative case  */
6435      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6436      est=QUOT10(carry, DECDPUN);
6437      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6438      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6439    #else
6440      /* remainder operator is undefined if negative, so must test  */
6441      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1  */
6442        *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions]  */
6443        carry=1;
6444        continue;
6445        }
6446      if (carry>=0) {
6447        *c=(Unit)(carry%(DECDPUNMAX+1));
6448        carry=carry/(DECDPUNMAX+1);
6449        continue;
6450        }
6451      /* negative case  */
6452      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6453      *c=(Unit)(carry%(DECDPUNMAX+1));
6454      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6455    #endif
6456    } /* c  */
6457
6458  /* now may have one or other to complete  */
6459  /* [pretest to avoid loop setup/shutdown]  */
6460  if (c<maxC) for (; c<maxC; c++) {
6461    if (a<alsu+alength) {               /* still in A  */
6462      carry+=*a;
6463      a++;
6464      }
6465     else {                             /* inside B  */
6466      carry+=((eInt)*b)*m;
6467      b++;
6468      }
6469    /* here carry is new Unit of digits; it could be +ve or -ve and  */
6470    /* magnitude up to DECDPUNMAX squared  */
6471    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6472      *c=(Unit)carry;
6473      carry=0;
6474      continue;
6475      }
6476    /* result for this unit is negative or >DECDPUNMAX  */
6477    #if DECDPUN==4                           /* use divide-by-multiply  */
6478      if (carry>=0) {
6479        est=(((ueInt)carry>>11)*53687)>>18;
6480        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6481        carry=est;                           /* likely quotient [79.7%]  */
6482        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6483        carry++;
6484        *c-=DECDPUNMAX+1;
6485        continue;
6486        }
6487      /* negative case  */
6488      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6489      est=(((ueInt)carry>>11)*53687)>>18;
6490      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6491      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6492      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6493      carry++;
6494      *c-=DECDPUNMAX+1;
6495    #elif DECDPUN==3
6496      if (carry>=0) {
6497        est=(((ueInt)carry>>3)*16777)>>21;
6498        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6499        carry=est;                           /* likely quotient [99%]  */
6500        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6501        carry++;
6502        *c-=DECDPUNMAX+1;
6503        continue;
6504        }
6505      /* negative case  */
6506      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6507      est=(((ueInt)carry>>3)*16777)>>21;
6508      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6509      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6510      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6511      carry++;
6512      *c-=DECDPUNMAX+1;
6513    #elif DECDPUN<=2
6514      if (carry>=0) {
6515        est=QUOT10(carry, DECDPUN);
6516        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6517        carry=est;                           /* quotient  */
6518        continue;
6519        }
6520      /* negative case  */
6521      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6522      est=QUOT10(carry, DECDPUN);
6523      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6524      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6525    #else
6526      if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1  */
6527        *c=(Unit)(carry-(DECDPUNMAX+1));
6528        carry=1;
6529        continue;
6530        }
6531      /* remainder operator is undefined if negative, so must test  */
6532      if (carry>=0) {
6533        *c=(Unit)(carry%(DECDPUNMAX+1));
6534        carry=carry/(DECDPUNMAX+1);
6535        continue;
6536        }
6537      /* negative case  */
6538      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6539      *c=(Unit)(carry%(DECDPUNMAX+1));
6540      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6541    #endif
6542    } /* c  */
6543
6544  /* OK, all A and B processed; might still have carry or borrow  */
6545  /* return number of Units in the result, negated if a borrow  */
6546  if (carry==0) return c-clsu;     /* no carry, so no more to do  */
6547  if (carry>0) {                   /* positive carry  */
6548    *c=(Unit)carry;                /* place as new unit  */
6549    c++;                           /* ..  */
6550    return c-clsu;
6551    }
6552  /* -ve carry: it's a borrow; complement needed  */
6553  add=1;                           /* temporary carry...  */
6554  for (c=clsu; c<maxC; c++) {
6555    add=DECDPUNMAX+add-*c;
6556    if (add<=DECDPUNMAX) {
6557      *c=(Unit)add;
6558      add=0;
6559      }
6560     else {
6561      *c=0;
6562      add=1;
6563      }
6564    }
6565  /* add an extra unit iff it would be non-zero  */
6566  #if DECTRACE
6567    printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6568  #endif
6569  if ((add-carry-1)!=0) {
6570    *c=(Unit)(add-carry-1);
6571    c++;                      /* interesting, include it  */
6572    }
6573  return clsu-c;              /* -ve result indicates borrowed  */
6574  } /* decUnitAddSub  */
6575
6576/* ------------------------------------------------------------------ */
6577/* decTrim -- trim trailing zeros or normalize                        */
6578/*                                                                    */
6579/*   dn is the number to trim or normalize                            */
6580/*   set is the context to use to check for clamp                     */
6581/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6582/*   noclamp is 1 to unconditional (unclamped) trim                   */
6583/*   dropped returns the number of discarded trailing zeros           */
6584/*   returns dn                                                       */
6585/*                                                                    */
6586/* If clamp is set in the context then the number of zeros trimmed    */
6587/* may be limited if the exponent is high.                            */
6588/* All fields are updated as required.  This is a utility operation,  */
6589/* so special values are unchanged and no error is possible.          */
6590/* ------------------------------------------------------------------ */
6591static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6592                           Flag noclamp, Int *dropped) {
6593  Int   d, exp;                    /* work  */
6594  uInt  cut;                       /* ..  */
6595  Unit  *up;                       /* -> current Unit  */
6596
6597  #if DECCHECK
6598  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6599  #endif
6600
6601  *dropped=0;                           /* assume no zeros dropped  */
6602  if ((dn->bits & DECSPECIAL)           /* fast exit if special ..  */
6603    || (*dn->lsu & 0x01)) return dn;    /* .. or odd  */
6604  if (ISZERO(dn)) {                     /* .. or 0  */
6605    dn->exponent=0;                     /* (sign is preserved)  */
6606    return dn;
6607    }
6608
6609  /* have a finite number which is even  */
6610  exp=dn->exponent;
6611  cut=1;                           /* digit (1-DECDPUN) in Unit  */
6612  up=dn->lsu;                      /* -> current Unit  */
6613  for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit]  */
6614    /* slice by powers  */
6615    #if DECDPUN<=4
6616      uInt quot=QUOT10(*up, cut);
6617      if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit  */
6618    #else
6619      if (*up%powers[cut]!=0) break;         /* found non-0 digit  */
6620    #endif
6621    /* have a trailing 0  */
6622    if (!all) {                    /* trimming  */
6623      /* [if exp>0 then all trailing 0s are significant for trim]  */
6624      if (exp<=0) {                /* if digit might be significant  */
6625        if (exp==0) break;         /* then quit  */
6626        exp++;                     /* next digit might be significant  */
6627        }
6628      }
6629    cut++;                         /* next power  */
6630    if (cut>DECDPUN) {             /* need new Unit  */
6631      up++;
6632      cut=1;
6633      }
6634    } /* d  */
6635  if (d==0) return dn;             /* none to drop  */
6636
6637  /* may need to limit drop if clamping  */
6638  if (set->clamp && !noclamp) {
6639    Int maxd=set->emax-set->digits+1-dn->exponent;
6640    if (maxd<=0) return dn;        /* nothing possible  */
6641    if (d>maxd) d=maxd;
6642    }
6643
6644  /* effect the drop  */
6645  decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6646  dn->exponent+=d;                 /* maintain numerical value  */
6647  dn->digits-=d;                   /* new length  */
6648  *dropped=d;                      /* report the count  */
6649  return dn;
6650  } /* decTrim  */
6651
6652/* ------------------------------------------------------------------ */
6653/* decReverse -- reverse a Unit array in place                        */
6654/*                                                                    */
6655/*   ulo    is the start of the array                                 */
6656/*   uhi    is the end of the array (highest Unit to include)         */
6657/*                                                                    */
6658/* The units ulo through uhi are reversed in place (if the number     */
6659/* of units is odd, the middle one is untouched).  Note that the      */
6660/* digit(s) in each unit are unaffected.                              */
6661/* ------------------------------------------------------------------ */
6662static void decReverse(Unit *ulo, Unit *uhi) {
6663  Unit temp;
6664  for (; ulo<uhi; ulo++, uhi--) {
6665    temp=*ulo;
6666    *ulo=*uhi;
6667    *uhi=temp;
6668    }
6669  return;
6670  } /* decReverse  */
6671
6672/* ------------------------------------------------------------------ */
6673/* decShiftToMost -- shift digits in array towards most significant   */
6674/*                                                                    */
6675/*   uar    is the array                                              */
6676/*   digits is the count of digits in use in the array                */
6677/*   shift  is the number of zeros to pad with (least significant);   */
6678/*     it must be zero or positive                                    */
6679/*                                                                    */
6680/*   returns the new length of the integer in the array, in digits    */
6681/*                                                                    */
6682/* No overflow is permitted (that is, the uar array must be known to  */
6683/* be large enough to hold the result, after shifting).               */
6684/* ------------------------------------------------------------------ */
6685static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6686  Unit  *target, *source, *first;  /* work  */
6687  Int   cut;                       /* odd 0's to add  */
6688  uInt  next;                      /* work  */
6689
6690  if (shift==0) return digits;     /* [fastpath] nothing to do  */
6691  if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case  */
6692    *uar=(Unit)(*uar*powers[shift]);
6693    return digits+shift;
6694    }
6695
6696  next=0;                          /* all paths  */
6697  source=uar+D2U(digits)-1;        /* where msu comes from  */
6698  target=source+D2U(shift);        /* where upper part of first cut goes  */
6699  cut=DECDPUN-MSUDIGITS(shift);    /* where to slice  */
6700  if (cut==0) {                    /* unit-boundary case  */
6701    for (; source>=uar; source--, target--) *target=*source;
6702    }
6703   else {
6704    first=uar+D2U(digits+shift)-1; /* where msu of source will end up  */
6705    for (; source>=uar; source--, target--) {
6706      /* split the source Unit and accumulate remainder for next  */
6707      #if DECDPUN<=4
6708        uInt quot=QUOT10(*source, cut);
6709        uInt rem=*source-quot*powers[cut];
6710        next+=quot;
6711      #else
6712        uInt rem=*source%powers[cut];
6713        next+=*source/powers[cut];
6714      #endif
6715      if (target<=first) *target=(Unit)next;   /* write to target iff valid  */
6716      next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit  */
6717      }
6718    } /* shift-move  */
6719
6720  /* propagate any partial unit to one below and clear the rest  */
6721  for (; target>=uar; target--) {
6722    *target=(Unit)next;
6723    next=0;
6724    }
6725  return digits+shift;
6726  } /* decShiftToMost  */
6727
6728/* ------------------------------------------------------------------ */
6729/* decShiftToLeast -- shift digits in array towards least significant */
6730/*                                                                    */
6731/*   uar   is the array                                               */
6732/*   units is length of the array, in units                           */
6733/*   shift is the number of digits to remove from the lsu end; it     */
6734/*     must be zero or positive and <= than units*DECDPUN.            */
6735/*                                                                    */
6736/*   returns the new length of the integer in the array, in units     */
6737/*                                                                    */
6738/* Removed digits are discarded (lost).  Units not required to hold   */
6739/* the final result are unchanged.                                    */
6740/* ------------------------------------------------------------------ */
6741static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6742  Unit  *target, *up;              /* work  */
6743  Int   cut, count;                /* work  */
6744  Int   quot, rem;                 /* for division  */
6745
6746  if (shift==0) return units;      /* [fastpath] nothing to do  */
6747  if (shift==units*DECDPUN) {      /* [fastpath] little to do  */
6748    *uar=0;                        /* all digits cleared gives zero  */
6749    return 1;                      /* leaves just the one  */
6750    }
6751
6752  target=uar;                      /* both paths  */
6753  cut=MSUDIGITS(shift);
6754  if (cut==DECDPUN) {              /* unit-boundary case; easy  */
6755    up=uar+D2U(shift);
6756    for (; up<uar+units; target++, up++) *target=*up;
6757    return target-uar;
6758    }
6759
6760  /* messier  */
6761  up=uar+D2U(shift-cut);           /* source; correct to whole Units  */
6762  count=units*DECDPUN-shift;       /* the maximum new length  */
6763  #if DECDPUN<=4
6764    quot=QUOT10(*up, cut);
6765  #else
6766    quot=*up/powers[cut];
6767  #endif
6768  for (; ; target++) {
6769    *target=(Unit)quot;
6770    count-=(DECDPUN-cut);
6771    if (count<=0) break;
6772    up++;
6773    quot=*up;
6774    #if DECDPUN<=4
6775      quot=QUOT10(quot, cut);
6776      rem=*up-quot*powers[cut];
6777    #else
6778      rem=quot%powers[cut];
6779      quot=quot/powers[cut];
6780    #endif
6781    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6782    count-=cut;
6783    if (count<=0) break;
6784    }
6785  return target-uar+1;
6786  } /* decShiftToLeast  */
6787
6788#if DECSUBSET
6789/* ------------------------------------------------------------------ */
6790/* decRoundOperand -- round an operand  [used for subset only]        */
6791/*                                                                    */
6792/*   dn is the number to round (dn->digits is > set->digits)          */
6793/*   set is the relevant context                                      */
6794/*   status is the status accumulator                                 */
6795/*                                                                    */
6796/*   returns an allocated decNumber with the rounded result.          */
6797/*                                                                    */
6798/* lostDigits and other status may be set by this.                    */
6799/*                                                                    */
6800/* Since the input is an operand, it must not be modified.            */
6801/* Instead, return an allocated decNumber, rounded as required.       */
6802/* It is the caller's responsibility to free the allocated storage.   */
6803/*                                                                    */
6804/* If no storage is available then the result cannot be used, so NULL */
6805/* is returned.                                                       */
6806/* ------------------------------------------------------------------ */
6807static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6808                                  uInt *status) {
6809  decNumber *res;                       /* result structure  */
6810  uInt newstatus=0;                     /* status from round  */
6811  Int  residue=0;                       /* rounding accumulator  */
6812
6813  /* Allocate storage for the returned decNumber, big enough for the  */
6814  /* length specified by the context  */
6815  res=(decNumber *)malloc(sizeof(decNumber)
6816                          +(D2U(set->digits)-1)*sizeof(Unit));
6817  if (res==NULL) {
6818    *status|=DEC_Insufficient_storage;
6819    return NULL;
6820    }
6821  decCopyFit(res, dn, set, &residue, &newstatus);
6822  decApplyRound(res, set, residue, &newstatus);
6823
6824  /* If that set Inexact then "lost digits" is raised...  */
6825  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6826  *status|=newstatus;
6827  return res;
6828  } /* decRoundOperand  */
6829#endif
6830
6831/* ------------------------------------------------------------------ */
6832/* decCopyFit -- copy a number, truncating the coefficient if needed  */
6833/*                                                                    */
6834/*   dest is the target decNumber                                     */
6835/*   src  is the source decNumber                                     */
6836/*   set is the context [used for length (digits) and rounding mode]  */
6837/*   residue is the residue accumulator                               */
6838/*   status contains the current status to be updated                 */
6839/*                                                                    */
6840/* (dest==src is allowed and will be a no-op if fits)                 */
6841/* All fields are updated as required.                                */
6842/* ------------------------------------------------------------------ */
6843static void decCopyFit(decNumber *dest, const decNumber *src,
6844                       decContext *set, Int *residue, uInt *status) {
6845  dest->bits=src->bits;
6846  dest->exponent=src->exponent;
6847  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6848  } /* decCopyFit  */
6849
6850/* ------------------------------------------------------------------ */
6851/* decSetCoeff -- set the coefficient of a number                     */
6852/*                                                                    */
6853/*   dn    is the number whose coefficient array is to be set.        */
6854/*         It must have space for set->digits digits                  */
6855/*   set   is the context [for size]                                  */
6856/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6857/*   len   is digits in the source coefficient [may be dn->digits]    */
6858/*   residue is the residue accumulator.  This has values as in       */
6859/*         decApplyRound, and will be unchanged unless the            */
6860/*         target size is less than len.  In this case, the           */
6861/*         coefficient is truncated and the residue is updated to     */
6862/*         reflect the previous residue and the dropped digits.       */
6863/*   status is the status accumulator, as usual                       */
6864/*                                                                    */
6865/* The coefficient may already be in the number, or it can be an      */
6866/* external intermediate array.  If it is in the number, lsu must ==  */
6867/* dn->lsu and len must == dn->digits.                                */
6868/*                                                                    */
6869/* Note that the coefficient length (len) may be < set->digits, and   */
6870/* in this case this merely copies the coefficient (or is a no-op     */
6871/* if dn->lsu==lsu).                                                  */
6872/*                                                                    */
6873/* Note also that (only internally, from decQuantizeOp and            */
6874/* decSetSubnormal) the value of set->digits may be less than one,    */
6875/* indicating a round to left.  This routine handles that case        */
6876/* correctly; caller ensures space.                                   */
6877/*                                                                    */
6878/* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6879/* updated as necessary.   dn->bits (sign) is unchanged.              */
6880/*                                                                    */
6881/* DEC_Rounded status is set if any digits are discarded.             */
6882/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6883/*                       incoming residue was non-0 (implies rounded) */
6884/* ------------------------------------------------------------------ */
6885/* mapping array: maps 0-9 to canonical residues, so that a residue  */
6886/* can be adjusted in the range [-1, +1] and achieve correct rounding  */
6887/*                             0  1  2  3  4  5  6  7  8  9  */
6888static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6889static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6890                        Int len, Int *residue, uInt *status) {
6891  Int   discard;              /* number of digits to discard  */
6892  uInt  cut;                  /* cut point in Unit  */
6893  const Unit *up;             /* work  */
6894  Unit  *target;              /* ..  */
6895  Int   count;                /* ..  */
6896  #if DECDPUN<=4
6897  uInt  temp;                 /* ..  */
6898  #endif
6899
6900  discard=len-set->digits;    /* digits to discard  */
6901  if (discard<=0) {           /* no digits are being discarded  */
6902    if (dn->lsu!=lsu) {       /* copy needed  */
6903      /* copy the coefficient array to the result number; no shift needed  */
6904      count=len;              /* avoids D2U  */
6905      up=lsu;
6906      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6907        *target=*up;
6908      dn->digits=len;         /* set the new length  */
6909      }
6910    /* dn->exponent and residue are unchanged, record any inexactitude  */
6911    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6912    return;
6913    }
6914
6915  /* some digits must be discarded ...  */
6916  dn->exponent+=discard;      /* maintain numerical value  */
6917  *status|=DEC_Rounded;       /* accumulate Rounded status  */
6918  if (*residue>1) *residue=1; /* previous residue now to right, so reduce  */
6919
6920  if (discard>len) {          /* everything, +1, is being discarded  */
6921    /* guard digit is 0  */
6922    /* residue is all the number [NB could be all 0s]  */
6923    if (*residue<=0) {        /* not already positive  */
6924      count=len;              /* avoids D2U  */
6925      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0  */
6926        *residue=1;
6927        break;                /* no need to check any others  */
6928        }
6929      }
6930    if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
6931    *dn->lsu=0;               /* coefficient will now be 0  */
6932    dn->digits=1;             /* ..  */
6933    return;
6934    } /* total discard  */
6935
6936  /* partial discard [most common case]  */
6937  /* here, at least the first (most significant) discarded digit exists  */
6938
6939  /* spin up the number, noting residue during the spin, until get to  */
6940  /* the Unit with the first discarded digit.  When reach it, extract  */
6941  /* it and remember its position  */
6942  count=0;
6943  for (up=lsu;; up++) {
6944    count+=DECDPUN;
6945    if (count>=discard) break; /* full ones all checked  */
6946    if (*up!=0) *residue=1;
6947    } /* up  */
6948
6949  /* here up -> Unit with first discarded digit  */
6950  cut=discard-(count-DECDPUN)-1;
6951  if (cut==DECDPUN-1) {       /* unit-boundary case (fast)  */
6952    Unit half=(Unit)powers[DECDPUN]>>1;
6953    /* set residue directly  */
6954    if (*up>=half) {
6955      if (*up>half) *residue=7;
6956      else *residue+=5;       /* add sticky bit  */
6957      }
6958     else { /* <half  */
6959      if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit]  */
6960      }
6961    if (set->digits<=0) {     /* special for Quantize/Subnormal :-(  */
6962      *dn->lsu=0;             /* .. result is 0  */
6963      dn->digits=1;           /* ..  */
6964      }
6965     else {                   /* shift to least  */
6966      count=set->digits;      /* now digits to end up with  */
6967      dn->digits=count;       /* set the new length  */
6968      up++;                   /* move to next  */
6969      /* on unit boundary, so shift-down copy loop is simple  */
6970      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6971        *target=*up;
6972      }
6973    } /* unit-boundary case  */
6974
6975   else { /* discard digit is in low digit(s), and not top digit  */
6976    uInt  discard1;                /* first discarded digit  */
6977    uInt  quot, rem;               /* for divisions  */
6978    if (cut==0) quot=*up;          /* is at bottom of unit  */
6979     else /* cut>0 */ {            /* it's not at bottom of unit  */
6980      #if DECDPUN<=4
6981        quot=QUOT10(*up, cut);
6982        rem=*up-quot*powers[cut];
6983      #else
6984        rem=*up%powers[cut];
6985        quot=*up/powers[cut];
6986      #endif
6987      if (rem!=0) *residue=1;
6988      }
6989    /* discard digit is now at bottom of quot  */
6990    #if DECDPUN<=4
6991      temp=(quot*6554)>>16;        /* fast /10  */
6992      /* Vowels algorithm here not a win (9 instructions)  */
6993      discard1=quot-X10(temp);
6994      quot=temp;
6995    #else
6996      discard1=quot%10;
6997      quot=quot/10;
6998    #endif
6999    /* here, discard1 is the guard digit, and residue is everything  */
7000    /* else [use mapping array to accumulate residue safely]  */
7001    *residue+=resmap[discard1];
7002    cut++;                         /* update cut  */
7003    /* here: up -> Unit of the array with bottom digit  */
7004    /*       cut is the division point for each Unit  */
7005    /*       quot holds the uncut high-order digits for the current unit  */
7006    if (set->digits<=0) {          /* special for Quantize/Subnormal :-(  */
7007      *dn->lsu=0;                  /* .. result is 0  */
7008      dn->digits=1;                /* ..  */
7009      }
7010     else {                        /* shift to least needed  */
7011      count=set->digits;           /* now digits to end up with  */
7012      dn->digits=count;            /* set the new length  */
7013      /* shift-copy the coefficient array to the result number  */
7014      for (target=dn->lsu; ; target++) {
7015        *target=(Unit)quot;
7016        count-=(DECDPUN-cut);
7017        if (count<=0) break;
7018        up++;
7019        quot=*up;
7020        #if DECDPUN<=4
7021          quot=QUOT10(quot, cut);
7022          rem=*up-quot*powers[cut];
7023        #else
7024          rem=quot%powers[cut];
7025          quot=quot/powers[cut];
7026        #endif
7027        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7028        count-=cut;
7029        if (count<=0) break;
7030        } /* shift-copy loop  */
7031      } /* shift to least  */
7032    } /* not unit boundary  */
7033
7034  if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
7035  return;
7036  } /* decSetCoeff  */
7037
7038/* ------------------------------------------------------------------ */
7039/* decApplyRound -- apply pending rounding to a number                */
7040/*                                                                    */
7041/*   dn    is the number, with space for set->digits digits           */
7042/*   set   is the context [for size and rounding mode]                */
7043/*   residue indicates pending rounding, being any accumulated        */
7044/*         guard and sticky information.  It may be:                  */
7045/*         6-9: rounding digit is >5                                  */
7046/*         5:   rounding digit is exactly half-way                    */
7047/*         1-4: rounding digit is <5 and >0                           */
7048/*         0:   the coefficient is exact                              */
7049/*        -1:   as 1, but the hidden digits are subtractive, that     */
7050/*              is, of the opposite sign to dn.  In this case the     */
7051/*              coefficient must be non-0.  This case occurs when     */
7052/*              subtracting a small number (which can be reduced to   */
7053/*              a sticky bit); see decAddOp.                          */
7054/*   status is the status accumulator, as usual                       */
7055/*                                                                    */
7056/* This routine applies rounding while keeping the length of the      */
7057/* coefficient constant.  The exponent and status are unchanged       */
7058/* except if:                                                         */
7059/*                                                                    */
7060/*   -- the coefficient was increased and is all nines (in which      */
7061/*      case Overflow could occur, and is handled directly here so    */
7062/*      the caller does not need to re-test for overflow)             */
7063/*                                                                    */
7064/*   -- the coefficient was decreased and becomes all nines (in which */
7065/*      case Underflow could occur, and is also handled directly).    */
7066/*                                                                    */
7067/* All fields in dn are updated as required.                          */
7068/*                                                                    */
7069/* ------------------------------------------------------------------ */
7070static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7071                          uInt *status) {
7072  Int  bump;                  /* 1 if coefficient needs to be incremented  */
7073                              /* -1 if coefficient needs to be decremented  */
7074
7075  if (residue==0) return;     /* nothing to apply  */
7076
7077  bump=0;                     /* assume a smooth ride  */
7078
7079  /* now decide whether, and how, to round, depending on mode  */
7080  switch (set->round) {
7081    case DEC_ROUND_05UP: {    /* round zero or five up (for reround)  */
7082      /* This is the same as DEC_ROUND_DOWN unless there is a  */
7083      /* positive residue and the lsd of dn is 0 or 5, in which case  */
7084      /* it is bumped; when residue is <0, the number is therefore  */
7085      /* bumped down unless the final digit was 1 or 6 (in which  */
7086      /* case it is bumped down and then up -- a no-op)  */
7087      Int lsd5=*dn->lsu%5;     /* get lsd and quintate  */
7088      if (residue<0 && lsd5!=1) bump=-1;
7089       else if (residue>0 && lsd5==0) bump=1;
7090      /* [bump==1 could be applied directly; use common path for clarity]  */
7091      break;} /* r-05  */
7092
7093    case DEC_ROUND_DOWN: {
7094      /* no change, except if negative residue  */
7095      if (residue<0) bump=-1;
7096      break;} /* r-d  */
7097
7098    case DEC_ROUND_HALF_DOWN: {
7099      if (residue>5) bump=1;
7100      break;} /* r-h-d  */
7101
7102    case DEC_ROUND_HALF_EVEN: {
7103      if (residue>5) bump=1;            /* >0.5 goes up  */
7104       else if (residue==5) {           /* exactly 0.5000...  */
7105        /* 0.5 goes up iff [new] lsd is odd  */
7106        if (*dn->lsu & 0x01) bump=1;
7107        }
7108      break;} /* r-h-e  */
7109
7110    case DEC_ROUND_HALF_UP: {
7111      if (residue>=5) bump=1;
7112      break;} /* r-h-u  */
7113
7114    case DEC_ROUND_UP: {
7115      if (residue>0) bump=1;
7116      break;} /* r-u  */
7117
7118    case DEC_ROUND_CEILING: {
7119      /* same as _UP for positive numbers, and as _DOWN for negatives  */
7120      /* [negative residue cannot occur on 0]  */
7121      if (decNumberIsNegative(dn)) {
7122        if (residue<0) bump=-1;
7123        }
7124       else {
7125        if (residue>0) bump=1;
7126        }
7127      break;} /* r-c  */
7128
7129    case DEC_ROUND_FLOOR: {
7130      /* same as _UP for negative numbers, and as _DOWN for positive  */
7131      /* [negative residue cannot occur on 0]  */
7132      if (!decNumberIsNegative(dn)) {
7133        if (residue<0) bump=-1;
7134        }
7135       else {
7136        if (residue>0) bump=1;
7137        }
7138      break;} /* r-f  */
7139
7140    default: {      /* e.g., DEC_ROUND_MAX  */
7141      *status|=DEC_Invalid_context;
7142      #if DECTRACE || (DECCHECK && DECVERB)
7143      printf("Unknown rounding mode: %d\n", set->round);
7144      #endif
7145      break;}
7146    } /* switch  */
7147
7148  /* now bump the number, up or down, if need be  */
7149  if (bump==0) return;                       /* no action required  */
7150
7151  /* Simply use decUnitAddSub unless bumping up and the number is  */
7152  /* all nines.  In this special case set to 100... explicitly  */
7153  /* and adjust the exponent by one (as otherwise could overflow  */
7154  /* the array)  */
7155  /* Similarly handle all-nines result if bumping down.  */
7156  if (bump>0) {
7157    Unit *up;                                /* work  */
7158    uInt count=dn->digits;                   /* digits to be checked  */
7159    for (up=dn->lsu; ; up++) {
7160      if (count<=DECDPUN) {
7161        /* this is the last Unit (the msu)  */
7162        if (*up!=powers[count]-1) break;     /* not still 9s  */
7163        /* here if it, too, is all nines  */
7164        *up=(Unit)powers[count-1];           /* here 999 -> 100 etc.  */
7165        for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0  */
7166        dn->exponent++;                      /* and bump exponent  */
7167        /* [which, very rarely, could cause Overflow...]  */
7168        if ((dn->exponent+dn->digits)>set->emax+1) {
7169          decSetOverflow(dn, set, status);
7170          }
7171        return;                              /* done  */
7172        }
7173      /* a full unit to check, with more to come  */
7174      if (*up!=DECDPUNMAX) break;            /* not still 9s  */
7175      count-=DECDPUN;
7176      } /* up  */
7177    } /* bump>0  */
7178   else {                                    /* -1  */
7179    /* here checking for a pre-bump of 1000... (leading 1, all  */
7180    /* other digits zero)  */
7181    Unit *up, *sup;                          /* work  */
7182    uInt count=dn->digits;                   /* digits to be checked  */
7183    for (up=dn->lsu; ; up++) {
7184      if (count<=DECDPUN) {
7185        /* this is the last Unit (the msu)  */
7186        if (*up!=powers[count-1]) break;     /* not 100..  */
7187        /* here if have the 1000... case  */
7188        sup=up;                              /* save msu pointer  */
7189        *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999  */
7190        /* others all to all-nines, too  */
7191        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7192        dn->exponent--;                      /* and bump exponent  */
7193
7194        /* iff the number was at the subnormal boundary (exponent=etiny)  */
7195        /* then the exponent is now out of range, so it will in fact get  */
7196        /* clamped to etiny and the final 9 dropped.  */
7197        /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin,  */
7198        /*        dn->exponent, set->digits);  */
7199        if (dn->exponent+1==set->emin-set->digits+1) {
7200          if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9]  */
7201           else {
7202            *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99..  */
7203            dn->digits--;
7204            }
7205          dn->exponent++;
7206          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7207          }
7208        return;                              /* done  */
7209        }
7210
7211      /* a full unit to check, with more to come  */
7212      if (*up!=0) break;                     /* not still 0s  */
7213      count-=DECDPUN;
7214      } /* up  */
7215
7216    } /* bump<0  */
7217
7218  /* Actual bump needed.  Do it.  */
7219  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7220  } /* decApplyRound  */
7221
7222#if DECSUBSET
7223/* ------------------------------------------------------------------ */
7224/* decFinish -- finish processing a number                            */
7225/*                                                                    */
7226/*   dn is the number                                                 */
7227/*   set is the context                                               */
7228/*   residue is the rounding accumulator (as in decApplyRound)        */
7229/*   status is the accumulator                                        */
7230/*                                                                    */
7231/* This finishes off the current number by:                           */
7232/*    1. If not extended:                                             */
7233/*       a. Converting a zero result to clean '0'                     */
7234/*       b. Reducing positive exponents to 0, if would fit in digits  */
7235/*    2. Checking for overflow and subnormals (always)                */
7236/* Note this is just Finalize when no subset arithmetic.              */
7237/* All fields are updated as required.                                */
7238/* ------------------------------------------------------------------ */
7239static void decFinish(decNumber *dn, decContext *set, Int *residue,
7240                      uInt *status) {
7241  if (!set->extended) {
7242    if ISZERO(dn) {                /* value is zero  */
7243      dn->exponent=0;              /* clean exponent ..  */
7244      dn->bits=0;                  /* .. and sign  */
7245      return;                      /* no error possible  */
7246      }
7247    if (dn->exponent>=0) {         /* non-negative exponent  */
7248      /* >0; reduce to integer if possible  */
7249      if (set->digits >= (dn->exponent+dn->digits)) {
7250        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7251        dn->exponent=0;
7252        }
7253      }
7254    } /* !extended  */
7255
7256  decFinalize(dn, set, residue, status);
7257  } /* decFinish  */
7258#endif
7259
7260/* ------------------------------------------------------------------ */
7261/* decFinalize -- final check, clamp, and round of a number           */
7262/*                                                                    */
7263/*   dn is the number                                                 */
7264/*   set is the context                                               */
7265/*   residue is the rounding accumulator (as in decApplyRound)        */
7266/*   status is the status accumulator                                 */
7267/*                                                                    */
7268/* This finishes off the current number by checking for subnormal     */
7269/* results, applying any pending rounding, checking for overflow,     */
7270/* and applying any clamping.                                         */
7271/* Underflow and overflow conditions are raised as appropriate.       */
7272/* All fields are updated as required.                                */
7273/* ------------------------------------------------------------------ */
7274static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7275                        uInt *status) {
7276  Int shift;                            /* shift needed if clamping  */
7277  Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary  */
7278
7279  /* Must be careful, here, when checking the exponent as the  */
7280  /* adjusted exponent could overflow 31 bits [because it may already  */
7281  /* be up to twice the expected].  */
7282
7283  /* First test for subnormal.  This must be done before any final  */
7284  /* round as the result could be rounded to Nmin or 0.  */
7285  if (dn->exponent<=tinyexp) {          /* prefilter  */
7286    Int comp;
7287    decNumber nmin;
7288    /* A very nasty case here is dn == Nmin and residue<0  */
7289    if (dn->exponent<tinyexp) {
7290      /* Go handle subnormals; this will apply round if needed.  */
7291      decSetSubnormal(dn, set, residue, status);
7292      return;
7293      }
7294    /* Equals case: only subnormal if dn=Nmin and negative residue  */
7295    uprv_decNumberZero(&nmin);
7296    nmin.lsu[0]=1;
7297    nmin.exponent=set->emin;
7298    comp=decCompare(dn, &nmin, 1);                /* (signless compare)  */
7299    if (comp==BADINT) {                           /* oops  */
7300      *status|=DEC_Insufficient_storage;          /* abandon...  */
7301      return;
7302      }
7303    if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin  */
7304      decApplyRound(dn, set, *residue, status);   /* might force down  */
7305      decSetSubnormal(dn, set, residue, status);
7306      return;
7307      }
7308    }
7309
7310  /* now apply any pending round (this could raise overflow).  */
7311  if (*residue!=0) decApplyRound(dn, set, *residue, status);
7312
7313  /* Check for overflow [redundant in the 'rare' case] or clamp  */
7314  if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed  */
7315
7316
7317  /* here when might have an overflow or clamp to do  */
7318  if (dn->exponent>set->emax-dn->digits+1) {           /* too big  */
7319    decSetOverflow(dn, set, status);
7320    return;
7321    }
7322  /* here when the result is normal but in clamp range  */
7323  if (!set->clamp) return;
7324
7325  /* here when need to apply the IEEE exponent clamp (fold-down)  */
7326  shift=dn->exponent-(set->emax-set->digits+1);
7327
7328  /* shift coefficient (if non-zero)  */
7329  if (!ISZERO(dn)) {
7330    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7331    }
7332  dn->exponent-=shift;   /* adjust the exponent to match  */
7333  *status|=DEC_Clamped;  /* and record the dirty deed  */
7334  return;
7335  } /* decFinalize  */
7336
7337/* ------------------------------------------------------------------ */
7338/* decSetOverflow -- set number to proper overflow value              */
7339/*                                                                    */
7340/*   dn is the number (used for sign [only] and result)               */
7341/*   set is the context [used for the rounding mode, etc.]            */
7342/*   status contains the current status to be updated                 */
7343/*                                                                    */
7344/* This sets the sign of a number and sets its value to either        */
7345/* Infinity or the maximum finite value, depending on the sign of     */
7346/* dn and the rounding mode, following IEEE 754 rules.                */
7347/* ------------------------------------------------------------------ */
7348static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7349  Flag needmax=0;                  /* result is maximum finite value  */
7350  uByte sign=dn->bits&DECNEG;      /* clean and save sign bit  */
7351
7352  if (ISZERO(dn)) {                /* zero does not overflow magnitude  */
7353    Int emax=set->emax;                      /* limit value  */
7354    if (set->clamp) emax-=set->digits-1;     /* lower if clamping  */
7355    if (dn->exponent>emax) {                 /* clamp required  */
7356      dn->exponent=emax;
7357      *status|=DEC_Clamped;
7358      }
7359    return;
7360    }
7361
7362  uprv_decNumberZero(dn);
7363  switch (set->round) {
7364    case DEC_ROUND_DOWN: {
7365      needmax=1;                   /* never Infinity  */
7366      break;} /* r-d  */
7367    case DEC_ROUND_05UP: {
7368      needmax=1;                   /* never Infinity  */
7369      break;} /* r-05  */
7370    case DEC_ROUND_CEILING: {
7371      if (sign) needmax=1;         /* Infinity if non-negative  */
7372      break;} /* r-c  */
7373    case DEC_ROUND_FLOOR: {
7374      if (!sign) needmax=1;        /* Infinity if negative  */
7375      break;} /* r-f  */
7376    default: break;                /* Infinity in all other cases  */
7377    }
7378  if (needmax) {
7379    decSetMaxValue(dn, set);
7380    dn->bits=sign;                 /* set sign  */
7381    }
7382   else dn->bits=sign|DECINF;      /* Value is +/-Infinity  */
7383  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7384  } /* decSetOverflow  */
7385
7386/* ------------------------------------------------------------------ */
7387/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7388/*                                                                    */
7389/*   dn is the number to set                                          */
7390/*   set is the context [used for digits and emax]                    */
7391/*                                                                    */
7392/* This sets the number to the maximum positive value.                */
7393/* ------------------------------------------------------------------ */
7394static void decSetMaxValue(decNumber *dn, decContext *set) {
7395  Unit *up;                        /* work  */
7396  Int count=set->digits;           /* nines to add  */
7397  dn->digits=count;
7398  /* fill in all nines to set maximum value  */
7399  for (up=dn->lsu; ; up++) {
7400    if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines  */
7401     else {                             /* this is the msu  */
7402      *up=(Unit)(powers[count]-1);
7403      break;
7404      }
7405    count-=DECDPUN;                /* filled those digits  */
7406    } /* up  */
7407  dn->bits=0;                      /* + sign  */
7408  dn->exponent=set->emax-set->digits+1;
7409  } /* decSetMaxValue  */
7410
7411/* ------------------------------------------------------------------ */
7412/* decSetSubnormal -- process value whose exponent is <Emin           */
7413/*                                                                    */
7414/*   dn is the number (used as input as well as output; it may have   */
7415/*         an allowed subnormal value, which may need to be rounded)  */
7416/*   set is the context [used for the rounding mode]                  */
7417/*   residue is any pending residue                                   */
7418/*   status contains the current status to be updated                 */
7419/*                                                                    */
7420/* If subset mode, set result to zero and set Underflow flags.        */
7421/*                                                                    */
7422/* Value may be zero with a low exponent; this does not set Subnormal */
7423/* but the exponent will be clamped to Etiny.                         */
7424/*                                                                    */
7425/* Otherwise ensure exponent is not out of range, and round as        */
7426/* necessary.  Underflow is set if the result is Inexact.             */
7427/* ------------------------------------------------------------------ */
7428static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7429                            uInt *status) {
7430  decContext workset;         /* work  */
7431  Int        etiny, adjust;   /* ..  */
7432
7433  #if DECSUBSET
7434  /* simple set to zero and 'hard underflow' for subset  */
7435  if (!set->extended) {
7436    uprv_decNumberZero(dn);
7437    /* always full overflow  */
7438    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7439    return;
7440    }
7441  #endif
7442
7443  /* Full arithmetic -- allow subnormals, rounded to minimum exponent  */
7444  /* (Etiny) if needed  */
7445  etiny=set->emin-(set->digits-1);      /* smallest allowed exponent  */
7446
7447  if ISZERO(dn) {                       /* value is zero  */
7448    /* residue can never be non-zero here  */
7449    #if DECCHECK
7450      if (*residue!=0) {
7451        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7452        *status|=DEC_Invalid_operation;
7453        }
7454    #endif
7455    if (dn->exponent<etiny) {           /* clamp required  */
7456      dn->exponent=etiny;
7457      *status|=DEC_Clamped;
7458      }
7459    return;
7460    }
7461
7462  *status|=DEC_Subnormal;               /* have a non-zero subnormal  */
7463  adjust=etiny-dn->exponent;            /* calculate digits to remove  */
7464  if (adjust<=0) {                      /* not out of range; unrounded  */
7465    /* residue can never be non-zero here, except in the Nmin-residue  */
7466    /* case (which is a subnormal result), so can take fast-path here  */
7467    /* it may already be inexact (from setting the coefficient)  */
7468    if (*status&DEC_Inexact) *status|=DEC_Underflow;
7469    return;
7470    }
7471
7472  /* adjust>0, so need to rescale the result so exponent becomes Etiny  */
7473  /* [this code is similar to that in rescale]  */
7474  workset=*set;                         /* clone rounding, etc.  */
7475  workset.digits=dn->digits-adjust;     /* set requested length  */
7476  workset.emin-=adjust;                 /* and adjust emin to match  */
7477  /* [note that the latter can be <1, here, similar to Rescale case]  */
7478  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7479  decApplyRound(dn, &workset, *residue, status);
7480
7481  /* Use 754 default rule: Underflow is set iff Inexact  */
7482  /* [independent of whether trapped]  */
7483  if (*status&DEC_Inexact) *status|=DEC_Underflow;
7484
7485  /* if rounded up a 999s case, exponent will be off by one; adjust  */
7486  /* back if so [it will fit, because it was shortened earlier]  */
7487  if (dn->exponent>etiny) {
7488    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7489    dn->exponent--;                     /* (re)adjust the exponent.  */
7490    }
7491
7492  /* if rounded to zero, it is by definition clamped...  */
7493  if (ISZERO(dn)) *status|=DEC_Clamped;
7494  } /* decSetSubnormal  */
7495
7496/* ------------------------------------------------------------------ */
7497/* decCheckMath - check entry conditions for a math function          */
7498/*                                                                    */
7499/*   This checks the context and the operand                          */
7500/*                                                                    */
7501/*   rhs is the operand to check                                      */
7502/*   set is the context to check                                      */
7503/*   status is unchanged if both are good                             */
7504/*                                                                    */
7505/* returns non-zero if status is changed, 0 otherwise                 */
7506/*                                                                    */
7507/* Restrictions enforced:                                             */
7508/*                                                                    */
7509/*   digits, emax, and -emin in the context must be less than         */
7510/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7511/*   non-zero.  Invalid_operation is set in the status if a           */
7512/*   restriction is violated.                                         */
7513/* ------------------------------------------------------------------ */
7514static uInt decCheckMath(const decNumber *rhs, decContext *set,
7515                         uInt *status) {
7516  uInt save=*status;                         /* record  */
7517  if (set->digits>DEC_MAX_MATH
7518   || set->emax>DEC_MAX_MATH
7519   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7520   else if ((rhs->digits>DEC_MAX_MATH
7521     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7522     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7523     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7524  return (*status!=save);
7525  } /* decCheckMath  */
7526
7527/* ------------------------------------------------------------------ */
7528/* decGetInt -- get integer from a number                             */
7529/*                                                                    */
7530/*   dn is the number [which will not be altered]                     */
7531/*                                                                    */
7532/*   returns one of:                                                  */
7533/*     BADINT if there is a non-zero fraction                         */
7534/*     the converted integer                                          */
7535/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7536/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7537/*                                                                    */
7538/* This checks and gets a whole number from the input decNumber.      */
7539/* The sign can be determined from dn by the caller when BIGEVEN or   */
7540/* BIGODD is returned.                                                */
7541/* ------------------------------------------------------------------ */
7542static Int decGetInt(const decNumber *dn) {
7543  Int  theInt;                          /* result accumulator  */
7544  const Unit *up;                       /* work  */
7545  Int  got;                             /* digits (real or not) processed  */
7546  Int  ilength=dn->digits+dn->exponent; /* integral length  */
7547  Flag neg=decNumberIsNegative(dn);     /* 1 if -ve  */
7548
7549  /* The number must be an integer that fits in 10 digits  */
7550  /* Assert, here, that 10 is enough for any rescale Etiny  */
7551  #if DEC_MAX_EMAX > 999999999
7552    #error GetInt may need updating [for Emax]
7553  #endif
7554  #if DEC_MIN_EMIN < -999999999
7555    #error GetInt may need updating [for Emin]
7556  #endif
7557  if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent  */
7558
7559  up=dn->lsu;                           /* ready for lsu  */
7560  theInt=0;                             /* ready to accumulate  */
7561  if (dn->exponent>=0) {                /* relatively easy  */
7562    /* no fractional part [usual]; allow for positive exponent  */
7563    got=dn->exponent;
7564    }
7565   else { /* -ve exponent; some fractional part to check and discard  */
7566    Int count=-dn->exponent;            /* digits to discard  */
7567    /* spin up whole units until reach the Unit with the unit digit  */
7568    for (; count>=DECDPUN; up++) {
7569      if (*up!=0) return BADINT;        /* non-zero Unit to discard  */
7570      count-=DECDPUN;
7571      }
7572    if (count==0) got=0;                /* [a multiple of DECDPUN]  */
7573     else {                             /* [not multiple of DECDPUN]  */
7574      Int rem;                          /* work  */
7575      /* slice off fraction digits and check for non-zero  */
7576      #if DECDPUN<=4
7577        theInt=QUOT10(*up, count);
7578        rem=*up-theInt*powers[count];
7579      #else
7580        rem=*up%powers[count];          /* slice off discards  */
7581        theInt=*up/powers[count];
7582      #endif
7583      if (rem!=0) return BADINT;        /* non-zero fraction  */
7584      /* it looks good  */
7585      got=DECDPUN-count;                /* number of digits so far  */
7586      up++;                             /* ready for next  */
7587      }
7588    }
7589  /* now it's known there's no fractional part  */
7590
7591  /* tricky code now, to accumulate up to 9.3 digits  */
7592  if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there  */
7593
7594  if (ilength<11) {
7595    Int save=theInt;
7596    /* collect any remaining unit(s)  */
7597    for (; got<ilength; up++) {
7598      theInt+=*up*powers[got];
7599      got+=DECDPUN;
7600      }
7601    if (ilength==10) {                  /* need to check for wrap  */
7602      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7603         /* [that test also disallows the BADINT result case]  */
7604       else if (neg && theInt>1999999997) ilength=11;
7605       else if (!neg && theInt>999999999) ilength=11;
7606      if (ilength==11) theInt=save;     /* restore correct low bit  */
7607      }
7608    }
7609
7610  if (ilength>10) {                     /* too big  */
7611    if (theInt&1) return BIGODD;        /* bottom bit 1  */
7612    return BIGEVEN;                     /* bottom bit 0  */
7613    }
7614
7615  if (neg) theInt=-theInt;              /* apply sign  */
7616  return theInt;
7617  } /* decGetInt  */
7618
7619/* ------------------------------------------------------------------ */
7620/* decDecap -- decapitate the coefficient of a number                 */
7621/*                                                                    */
7622/*   dn   is the number to be decapitated                             */
7623/*   drop is the number of digits to be removed from the left of dn;  */
7624/*     this must be <= dn->digits (if equal, the coefficient is       */
7625/*     set to 0)                                                      */
7626/*                                                                    */
7627/* Returns dn; dn->digits will be <= the initial digits less drop     */
7628/* (after removing drop digits there may be leading zero digits       */
7629/* which will also be removed).  Only dn->lsu and dn->digits change.  */
7630/* ------------------------------------------------------------------ */
7631static decNumber *decDecap(decNumber *dn, Int drop) {
7632  Unit *msu;                            /* -> target cut point  */
7633  Int cut;                              /* work  */
7634  if (drop>=dn->digits) {               /* losing the whole thing  */
7635    #if DECCHECK
7636    if (drop>dn->digits)
7637      printf("decDecap called with drop>digits [%ld>%ld]\n",
7638             (LI)drop, (LI)dn->digits);
7639    #endif
7640    dn->lsu[0]=0;
7641    dn->digits=1;
7642    return dn;
7643    }
7644  msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu  */
7645  cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu  */
7646  if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits  */
7647  /* that may have left leading zero digits, so do a proper count...  */
7648  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7649  return dn;
7650  } /* decDecap  */
7651
7652/* ------------------------------------------------------------------ */
7653/* decBiStr -- compare string with pairwise options                   */
7654/*                                                                    */
7655/*   targ is the string to compare                                    */
7656/*   str1 is one of the strings to compare against (length may be 0)  */
7657/*   str2 is the other; it must be the same length as str1            */
7658/*                                                                    */
7659/*   returns 1 if strings compare equal, (that is, it is the same     */
7660/*   length as str1 and str2, and each character of targ is in either */
7661/*   str1 or str2 in the corresponding position), or 0 otherwise      */
7662/*                                                                    */
7663/* This is used for generic caseless compare, including the awkward   */
7664/* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7665/*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7666/* ------------------------------------------------------------------ */
7667static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7668  for (;;targ++, str1++, str2++) {
7669    if (*targ!=*str1 && *targ!=*str2) return 0;
7670    /* *targ has a match in one (or both, if terminator)  */
7671    if (*targ=='\0') break;
7672    } /* forever  */
7673  return 1;
7674  } /* decBiStr  */
7675
7676/* ------------------------------------------------------------------ */
7677/* decNaNs -- handle NaN operand or operands                          */
7678/*                                                                    */
7679/*   res     is the result number                                     */
7680/*   lhs     is the first operand                                     */
7681/*   rhs     is the second operand, or NULL if none                   */
7682/*   context is used to limit payload length                          */
7683/*   status  contains the current status                              */
7684/*   returns res in case convenient                                   */
7685/*                                                                    */
7686/* Called when one or both operands is a NaN, and propagates the      */
7687/* appropriate result to res.  When an sNaN is found, it is changed   */
7688/* to a qNaN and Invalid operation is set.                            */
7689/* ------------------------------------------------------------------ */
7690static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7691                           const decNumber *rhs, decContext *set,
7692                           uInt *status) {
7693  /* This decision tree ends up with LHS being the source pointer,  */
7694  /* and status updated if need be  */
7695  if (lhs->bits & DECSNAN)
7696    *status|=DEC_Invalid_operation | DEC_sNaN;
7697   else if (rhs==NULL);
7698   else if (rhs->bits & DECSNAN) {
7699    lhs=rhs;
7700    *status|=DEC_Invalid_operation | DEC_sNaN;
7701    }
7702   else if (lhs->bits & DECNAN);
7703   else lhs=rhs;
7704
7705  /* propagate the payload  */
7706  if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy  */
7707   else { /* too long  */
7708    const Unit *ul;
7709    Unit *ur, *uresp1;
7710    /* copy safe number of units, then decapitate  */
7711    res->bits=lhs->bits;                /* need sign etc.  */
7712    uresp1=res->lsu+D2U(set->digits);
7713    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7714    res->digits=D2U(set->digits)*DECDPUN;
7715    /* maybe still too long  */
7716    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7717    }
7718
7719  res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while  */
7720  res->bits|=DECNAN;          /* .. preserving sign  */
7721  res->exponent=0;            /* clean exponent  */
7722                              /* [coefficient was copied/decapitated]  */
7723  return res;
7724  } /* decNaNs  */
7725
7726/* ------------------------------------------------------------------ */
7727/* decStatus -- apply non-zero status                                 */
7728/*                                                                    */
7729/*   dn     is the number to set if error                             */
7730/*   status contains the current status (not yet in context)          */
7731/*   set    is the context                                            */
7732/*                                                                    */
7733/* If the status is an error status, the number is set to a NaN,      */
7734/* unless the error was an overflow, divide-by-zero, or underflow,    */
7735/* in which case the number will have already been set.               */
7736/*                                                                    */
7737/* The context status is then updated with the new status.  Note that */
7738/* this may raise a signal, so control may never return from this     */
7739/* routine (hence resources must be recovered before it is called).   */
7740/* ------------------------------------------------------------------ */
7741static void decStatus(decNumber *dn, uInt status, decContext *set) {
7742  if (status & DEC_NaNs) {              /* error status -> NaN  */
7743    /* if cause was an sNaN, clear and propagate [NaN is already set up]  */
7744    if (status & DEC_sNaN) status&=~DEC_sNaN;
7745     else {
7746      uprv_decNumberZero(dn);                /* other error: clean throughout  */
7747      dn->bits=DECNAN;                  /* and make a quiet NaN  */
7748      }
7749    }
7750  uprv_decContextSetStatus(set, status);     /* [may not return]  */
7751  return;
7752  } /* decStatus  */
7753
7754/* ------------------------------------------------------------------ */
7755/* decGetDigits -- count digits in a Units array                      */
7756/*                                                                    */
7757/*   uar is the Unit array holding the number (this is often an       */
7758/*          accumulator of some sort)                                 */
7759/*   len is the length of the array in units [>=1]                    */
7760/*                                                                    */
7761/*   returns the number of (significant) digits in the array          */
7762/*                                                                    */
7763/* All leading zeros are excluded, except the last if the array has   */
7764/* only zero Units.                                                   */
7765/* ------------------------------------------------------------------ */
7766/* This may be called twice during some operations.  */
7767static Int decGetDigits(Unit *uar, Int len) {
7768  Unit *up=uar+(len-1);            /* -> msu  */
7769  Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu  */
7770  #if DECDPUN>4
7771  uInt const *pow;                 /* work  */
7772  #endif
7773                                   /* (at least 1 in final msu)  */
7774  #if DECCHECK
7775  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7776  #endif
7777
7778  for (; up>=uar; up--) {
7779    if (*up==0) {                  /* unit is all 0s  */
7780      if (digits==1) break;        /* a zero has one digit  */
7781      digits-=DECDPUN;             /* adjust for 0 unit  */
7782      continue;}
7783    /* found the first (most significant) non-zero Unit  */
7784    #if DECDPUN>1                  /* not done yet  */
7785    if (*up<10) break;             /* is 1-9  */
7786    digits++;
7787    #if DECDPUN>2                  /* not done yet  */
7788    if (*up<100) break;            /* is 10-99  */
7789    digits++;
7790    #if DECDPUN>3                  /* not done yet  */
7791    if (*up<1000) break;           /* is 100-999  */
7792    digits++;
7793    #if DECDPUN>4                  /* count the rest ...  */
7794    for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7795    #endif
7796    #endif
7797    #endif
7798    #endif
7799    break;
7800    } /* up  */
7801  return digits;
7802  } /* decGetDigits  */
7803
7804#if DECTRACE | DECCHECK
7805/* ------------------------------------------------------------------ */
7806/* decNumberShow -- display a number [debug aid]                      */
7807/*   dn is the number to show                                         */
7808/*                                                                    */
7809/* Shows: sign, exponent, coefficient (msu first), digits             */
7810/*    or: sign, special-value                                         */
7811/* ------------------------------------------------------------------ */
7812/* this is public so other modules can use it  */
7813void uprv_decNumberShow(const decNumber *dn) {
7814  const Unit *up;                  /* work  */
7815  uInt u, d;                       /* ..  */
7816  Int cut;                         /* ..  */
7817  char isign='+';                  /* main sign  */
7818  if (dn==NULL) {
7819    printf("NULL\n");
7820    return;}
7821  if (decNumberIsNegative(dn)) isign='-';
7822  printf(" >> %c ", isign);
7823  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
7824    if (decNumberIsInfinite(dn)) printf("Infinity");
7825     else {                                  /* a NaN  */
7826      if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN  */
7827       else printf("NaN");
7828      }
7829    /* if coefficient and exponent are 0, no more to do  */
7830    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7831      printf("\n");
7832      return;}
7833    /* drop through to report other information  */
7834    printf(" ");
7835    }
7836
7837  /* now carefully display the coefficient  */
7838  up=dn->lsu+D2U(dn->digits)-1;         /* msu  */
7839  printf("%ld", (LI)*up);
7840  for (up=up-1; up>=dn->lsu; up--) {
7841    u=*up;
7842    printf(":");
7843    for (cut=DECDPUN-1; cut>=0; cut--) {
7844      d=u/powers[cut];
7845      u-=d*powers[cut];
7846      printf("%ld", (LI)d);
7847      } /* cut  */
7848    } /* up  */
7849  if (dn->exponent!=0) {
7850    char esign='+';
7851    if (dn->exponent<0) esign='-';
7852    printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7853    }
7854  printf(" [%ld]\n", (LI)dn->digits);
7855  } /* decNumberShow  */
7856#endif
7857
7858#if DECTRACE || DECCHECK
7859/* ------------------------------------------------------------------ */
7860/* decDumpAr -- display a unit array [debug/check aid]                */
7861/*   name is a single-character tag name                              */
7862/*   ar   is the array to display                                     */
7863/*   len  is the length of the array in Units                         */
7864/* ------------------------------------------------------------------ */
7865static void decDumpAr(char name, const Unit *ar, Int len) {
7866  Int i;
7867  const char *spec;
7868  #if DECDPUN==9
7869    spec="%09d ";
7870  #elif DECDPUN==8
7871    spec="%08d ";
7872  #elif DECDPUN==7
7873    spec="%07d ";
7874  #elif DECDPUN==6
7875    spec="%06d ";
7876  #elif DECDPUN==5
7877    spec="%05d ";
7878  #elif DECDPUN==4
7879    spec="%04d ";
7880  #elif DECDPUN==3
7881    spec="%03d ";
7882  #elif DECDPUN==2
7883    spec="%02d ";
7884  #else
7885    spec="%d ";
7886  #endif
7887  printf("  :%c: ", name);
7888  for (i=len-1; i>=0; i--) {
7889    if (i==len-1) printf("%ld ", (LI)ar[i]);
7890     else printf(spec, ar[i]);
7891    }
7892  printf("\n");
7893  return;}
7894#endif
7895
7896#if DECCHECK
7897/* ------------------------------------------------------------------ */
7898/* decCheckOperands -- check operand(s) to a routine                  */
7899/*   res is the result structure (not checked; it will be set to      */
7900/*          quiet NaN if error found (and it is not NULL))            */
7901/*   lhs is the first operand (may be DECUNRESU)                      */
7902/*   rhs is the second (may be DECUNUSED)                             */
7903/*   set is the context (may be DECUNCONT)                            */
7904/*   returns 0 if both operands, and the context are clean, or 1      */
7905/*     otherwise (in which case the context will show an error,       */
7906/*     unless NULL).  Note that res is not cleaned; caller should     */
7907/*     handle this so res=NULL case is safe.                          */
7908/* The caller is expected to abandon immediately if 1 is returned.    */
7909/* ------------------------------------------------------------------ */
7910static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7911                             const decNumber *rhs, decContext *set) {
7912  Flag bad=0;
7913  if (set==NULL) {                 /* oops; hopeless  */
7914    #if DECTRACE || DECVERB
7915    printf("Reference to context is NULL.\n");
7916    #endif
7917    bad=1;
7918    return 1;}
7919   else if (set!=DECUNCONT
7920     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7921    bad=1;
7922    #if DECTRACE || DECVERB
7923    printf("Bad context [digits=%ld round=%ld].\n",
7924           (LI)set->digits, (LI)set->round);
7925    #endif
7926    }
7927   else {
7928    if (res==NULL) {
7929      bad=1;
7930      #if DECTRACE
7931      /* this one not DECVERB as standard tests include NULL  */
7932      printf("Reference to result is NULL.\n");
7933      #endif
7934      }
7935    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7936    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7937    }
7938  if (bad) {
7939    if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7940    if (res!=DECUNRESU && res!=NULL) {
7941      uprv_decNumberZero(res);
7942      res->bits=DECNAN;       /* qNaN  */
7943      }
7944    }
7945  return bad;
7946  } /* decCheckOperands  */
7947
7948/* ------------------------------------------------------------------ */
7949/* decCheckNumber -- check a number                                   */
7950/*   dn is the number to check                                        */
7951/*   returns 0 if the number is clean, or 1 otherwise                 */
7952/*                                                                    */
7953/* The number is considered valid if it could be a result from some   */
7954/* operation in some valid context.                                   */
7955/* ------------------------------------------------------------------ */
7956static Flag decCheckNumber(const decNumber *dn) {
7957  const Unit *up;             /* work  */
7958  uInt maxuint;               /* ..  */
7959  Int ae, d, digits;          /* ..  */
7960  Int emin, emax;             /* ..  */
7961
7962  if (dn==NULL) {             /* hopeless  */
7963    #if DECTRACE
7964    /* this one not DECVERB as standard tests include NULL  */
7965    printf("Reference to decNumber is NULL.\n");
7966    #endif
7967    return 1;}
7968
7969  /* check special values  */
7970  if (dn->bits & DECSPECIAL) {
7971    if (dn->exponent!=0) {
7972      #if DECTRACE || DECVERB
7973      printf("Exponent %ld (not 0) for a special value [%02x].\n",
7974             (LI)dn->exponent, dn->bits);
7975      #endif
7976      return 1;}
7977
7978    /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only  */
7979    if (decNumberIsInfinite(dn)) {
7980      if (dn->digits!=1) {
7981        #if DECTRACE || DECVERB
7982        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7983        #endif
7984        return 1;}
7985      if (*dn->lsu!=0) {
7986        #if DECTRACE || DECVERB
7987        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7988        #endif
7989        decDumpAr('I', dn->lsu, D2U(dn->digits));
7990        return 1;}
7991      } /* Inf  */
7992    /* 2002.12.26: negative NaNs can now appear through proposed IEEE  */
7993    /*             concrete formats (decimal64, etc.).  */
7994    return 0;
7995    }
7996
7997  /* check the coefficient  */
7998  if (dn->digits<1 || dn->digits>DECNUMMAXP) {
7999    #if DECTRACE || DECVERB
8000    printf("Digits %ld in number.\n", (LI)dn->digits);
8001    #endif
8002    return 1;}
8003
8004  d=dn->digits;
8005
8006  for (up=dn->lsu; d>0; up++) {
8007    if (d>DECDPUN) maxuint=DECDPUNMAX;
8008     else {                   /* reached the msu  */
8009      maxuint=powers[d]-1;
8010      if (dn->digits>1 && *up<powers[d-1]) {
8011        #if DECTRACE || DECVERB
8012        printf("Leading 0 in number.\n");
8013        uprv_decNumberShow(dn);
8014        #endif
8015        return 1;}
8016      }
8017    if (*up>maxuint) {
8018      #if DECTRACE || DECVERB
8019      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8020              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8021      #endif
8022      return 1;}
8023    d-=DECDPUN;
8024    }
8025
8026  /* check the exponent.  Note that input operands can have exponents  */
8027  /* which are out of the set->emin/set->emax and set->digits range  */
8028  /* (just as they can have more digits than set->digits).  */
8029  ae=dn->exponent+dn->digits-1;    /* adjusted exponent  */
8030  emax=DECNUMMAXE;
8031  emin=DECNUMMINE;
8032  digits=DECNUMMAXP;
8033  if (ae<emin-(digits-1)) {
8034    #if DECTRACE || DECVERB
8035    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8036    uprv_decNumberShow(dn);
8037    #endif
8038    return 1;}
8039  if (ae>+emax) {
8040    #if DECTRACE || DECVERB
8041    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8042    uprv_decNumberShow(dn);
8043    #endif
8044    return 1;}
8045
8046  return 0;              /* it's OK  */
8047  } /* decCheckNumber  */
8048
8049/* ------------------------------------------------------------------ */
8050/* decCheckInexact -- check a normal finite inexact result has digits */
8051/*   dn is the number to check                                        */
8052/*   set is the context (for status and precision)                    */
8053/*   sets Invalid operation, etc., if some digits are missing         */
8054/* [this check is not made for DECSUBSET compilation or when          */
8055/* subnormal is not set]                                              */
8056/* ------------------------------------------------------------------ */
8057static void decCheckInexact(const decNumber *dn, decContext *set) {
8058  #if !DECSUBSET && DECEXTFLAG
8059    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8060     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8061      #if DECTRACE || DECVERB
8062      printf("Insufficient digits [%ld] on normal Inexact result.\n",
8063             (LI)dn->digits);
8064      uprv_decNumberShow(dn);
8065      #endif
8066      uprv_decContextSetStatus(set, DEC_Invalid_operation);
8067      }
8068  #else
8069    /* next is a noop for quiet compiler  */
8070    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8071  #endif
8072  return;
8073  } /* decCheckInexact  */
8074#endif
8075
8076#if DECALLOC
8077#undef malloc
8078#undef free
8079/* ------------------------------------------------------------------ */
8080/* decMalloc -- accountable allocation routine                        */
8081/*   n is the number of bytes to allocate                             */
8082/*                                                                    */
8083/* Semantics is the same as the stdlib malloc routine, but bytes      */
8084/* allocated are accounted for globally, and corruption fences are    */
8085/* added before and after the 'actual' storage.                       */
8086/* ------------------------------------------------------------------ */
8087/* This routine allocates storage with an extra twelve bytes; 8 are   */
8088/* at the start and hold:                                             */
8089/*   0-3 the original length requested                                */
8090/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8091/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8092/* ------------------------------------------------------------------ */
8093static void *decMalloc(size_t n) {
8094  uInt  size=n+12;                 /* true size  */
8095  void  *alloc;                    /* -> allocated storage  */
8096  uByte *b, *b0;                   /* work  */
8097  uInt  uiwork;                    /* for macros  */
8098
8099  alloc=malloc(size);              /* -> allocated storage  */
8100  if (alloc==NULL) return NULL;    /* out of strorage  */
8101  b0=(uByte *)alloc;               /* as bytes  */
8102  decAllocBytes+=n;                /* account for storage  */
8103  UBFROMUI(alloc, n);              /* save n  */
8104  /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);  */
8105  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8106  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8107  return b0+8;                     /* -> play area  */
8108  } /* decMalloc  */
8109
8110/* ------------------------------------------------------------------ */
8111/* decFree -- accountable free routine                                */
8112/*   alloc is the storage to free                                     */
8113/*                                                                    */
8114/* Semantics is the same as the stdlib malloc routine, except that    */
8115/* the global storage accounting is updated and the fences are        */
8116/* checked to ensure that no routine has written 'out of bounds'.     */
8117/* ------------------------------------------------------------------ */
8118/* This routine first checks that the fences have not been corrupted. */
8119/* It then frees the storage using the 'truw' storage address (that   */
8120/* is, offset by 8).                                                  */
8121/* ------------------------------------------------------------------ */
8122static void decFree(void *alloc) {
8123  uInt  n;                         /* original length  */
8124  uByte *b, *b0;                   /* work  */
8125  uInt  uiwork;                    /* for macros  */
8126
8127  if (alloc==NULL) return;         /* allowed; it's a nop  */
8128  b0=(uByte *)alloc;               /* as bytes  */
8129  b0-=8;                           /* -> true start of storage  */
8130  n=UBTOUI(b0);                    /* lift length  */
8131  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8132    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8133           b-b0-8, (LI)b0);
8134  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8135    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8136           b-b0-8, (LI)b0, (LI)n);
8137  free(b0);                        /* drop the storage  */
8138  decAllocBytes-=n;                /* account for storage  */
8139  /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);  */
8140  } /* decFree  */
8141#define malloc(a) decMalloc(a)
8142#define free(a) decFree(a)
8143#endif
8144