• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /* ------------------------------------------------------------------ */
4 /* Decimal Number arithmetic module                                   */
5 /* ------------------------------------------------------------------ */
6 /* Copyright (c) IBM Corporation, 2000-2014.  All rights reserved.    */
7 /*                                                                    */
8 /* This software is made available under the terms of the             */
9 /* ICU License -- ICU 1.8.1 and later.                                */
10 /*                                                                    */
11 /* The description and User's Guide ("The decNumber C Library") for   */
12 /* this software is called decNumber.pdf.  This document is           */
13 /* available, together with arithmetic and format specifications,     */
14 /* testcases, and Web links, on the General Decimal Arithmetic page.  */
15 /*                                                                    */
16 /* Please send comments, suggestions, and corrections to the author:  */
17 /*   mfc@uk.ibm.com                                                   */
18 /*   Mike Cowlishaw, IBM Fellow                                       */
19 /*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */
20 /* ------------------------------------------------------------------ */
21 
22 /* Modified version, for use from within ICU.
23  *    Renamed public functions, to avoid an unwanted export of the
24  *    standard names from the ICU library.
25  *
26  *    Use ICU's uprv_malloc() and uprv_free()
27  *
28  *    Revert comment syntax to plain C
29  *
30  *    Remove a few compiler warnings.
31  */
32 
33 /* This module comprises the routines for arbitrary-precision General */
34 /* Decimal Arithmetic as defined in the specification which may be    */
35 /* found on the General Decimal Arithmetic pages.  It implements both */
36 /* the full ('extended') arithmetic and the simpler ('subset')        */
37 /* arithmetic.                                                        */
38 /*                                                                    */
39 /* Usage notes:                                                       */
40 /*                                                                    */
41 /* 1. This code is ANSI C89 except:                                   */
42 /*                                                                    */
43 /*    a) C99 line comments (double forward slash) are used.  (Most C  */
44 /*       compilers accept these.  If yours does not, a simple script  */
45 /*       can be used to convert them to ANSI C comments.)             */
46 /*                                                                    */
47 /*    b) Types from C99 stdint.h are used.  If you do not have this   */
48 /*       header file, see the User's Guide section of the decNumber   */
49 /*       documentation; this lists the necessary definitions.         */
50 /*                                                                    */
51 /*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
52 /*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
53 /*       and DECDPUN<=4 (see documentation).                          */
54 /*                                                                    */
55 /*    The code also conforms to C99 restrictions; in particular,      */
56 /*    strict aliasing rules are observed.                             */
57 /*                                                                    */
58 /* 2. The decNumber format which this library uses is optimized for   */
59 /*    efficient processing of relatively short numbers; in particular */
60 /*    it allows the use of fixed sized structures and minimizes copy  */
61 /*    and move operations.  It does, however, support arbitrary       */
62 /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
63 /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
64 /*    range -999,999,999 through 0).  Mathematical functions (for     */
65 /*    example decNumberExp) as identified below are restricted more   */
66 /*    tightly: digits, emax, and -emin in the context must be <=      */
67 /*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
68 /*    these bounds.                                                   */
69 /*                                                                    */
70 /* 3. Logical functions are further restricted; their operands must   */
71 /*    be finite, positive, have an exponent of zero, and all digits   */
72 /*    must be either 0 or 1.  The result will only contain digits     */
73 /*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
74 /*                                                                    */
75 /* 4. Operands to operator functions are never modified unless they   */
76 /*    are also specified to be the result number (which is always     */
77 /*    permitted).  Other than that case, operands must not overlap.   */
78 /*                                                                    */
79 /* 5. Error handling: the type of the error is ORed into the status   */
80 /*    flags in the current context (decContext structure).  The       */
81 /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
82 /*    flag in the decContext is set (is 1).                           */
83 /*                                                                    */
84 /*    It is the responsibility of the caller to clear the status      */
85 /*    flags as required.                                              */
86 /*                                                                    */
87 /*    The result of any routine which returns a number will always    */
88 /*    be a valid number (which may be a special value, such as an     */
89 /*    Infinity or NaN).                                               */
90 /*                                                                    */
91 /* 6. The decNumber format is not an exchangeable concrete            */
92 /*    representation as it comprises fields which may be machine-     */
93 /*    dependent (packed or unpacked, or special length, for example). */
94 /*    Canonical conversions to and from strings are provided; other   */
95 /*    conversions are available in separate modules.                  */
96 /*                                                                    */
97 /* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
98 /*    to 1 for extended operand checking (including NULL operands).   */
99 /*    Results are undefined if a badly-formed structure (or a NULL    */
100 /*    pointer to a structure) is provided, though with DECCHECK       */
101 /*    enabled the operator routines are protected against exceptions. */
102 /*    (Except if the result pointer is NULL, which is unrecoverable.) */
103 /*                                                                    */
104 /*    However, the routines will never cause exceptions if they are   */
105 /*    given well-formed operands, even if the value of the operands   */
106 /*    is inappropriate for the operation and DECCHECK is not set.     */
107 /*    (Except for SIGFPE, as and where documented.)                   */
108 /*                                                                    */
109 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
110 /* ------------------------------------------------------------------ */
111 /* Implementation notes for maintenance of this module:               */
112 /*                                                                    */
113 /* 1. Storage leak protection:  Routines which use malloc are not     */
114 /*    permitted to use return for fastpath or error exits (i.e.,      */
115 /*    they follow strict structured programming conventions).         */
116 /*    Instead they have a do{}while(0); construct surrounding the     */
117 /*    code which is protected -- break may be used to exit this.      */
118 /*    Other routines can safely use the return statement inline.      */
119 /*                                                                    */
120 /*    Storage leak accounting can be enabled using DECALLOC.          */
121 /*                                                                    */
122 /* 2. All loops use the for(;;) construct.  Any do construct does     */
123 /*    not loop; it is for allocation protection as just described.    */
124 /*                                                                    */
125 /* 3. Setting status in the context must always be the very last      */
126 /*    action in a routine, as non-0 status may raise a trap and hence */
127 /*    the call to set status may not return (if the handler uses long */
128 /*    jump).  Therefore all cleanup must be done first.  In general,  */
129 /*    to achieve this status is accumulated and is only applied just  */
130 /*    before return by calling decContextSetStatus (via decStatus).   */
131 /*                                                                    */
132 /*    Routines which allocate storage cannot, in general, use the     */
133 /*    'top level' routines which could cause a non-returning          */
134 /*    transfer of control.  The decXxxxOp routines are safe (do not   */
135 /*    call decStatus even if traps are set in the context) and should */
136 /*    be used instead (they are also a little faster).                */
137 /*                                                                    */
138 /* 4. Exponent checking is minimized by allowing the exponent to      */
139 /*    grow outside its limits during calculations, provided that      */
140 /*    the decFinalize function is called later.  Multiplication and   */
141 /*    division, and intermediate calculations in exponentiation,      */
142 /*    require more careful checks because of the risk of 31-bit       */
143 /*    overflow (the most negative valid exponent is -1999999997, for  */
144 /*    a 999999999-digit number with adjusted exponent of -999999999). */
145 /*                                                                    */
146 /* 5. Rounding is deferred until finalization of results, with any    */
147 /*    'off to the right' data being represented as a single digit     */
148 /*    residue (in the range -1 through 9).  This avoids any double-   */
149 /*    rounding when more than one shortening takes place (for         */
150 /*    example, when a result is subnormal).                           */
151 /*                                                                    */
152 /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
153 /*    during many operations, so whole Units are handled and exact    */
154 /*    accounting of digits is not needed.  The correct digits value   */
155 /*    is found by decGetDigits, which accounts for leading zeros.     */
156 /*    This must be called before any rounding if the number of digits */
157 /*    is not known exactly.                                           */
158 /*                                                                    */
159 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
160 /*    numbers up to four digits, using appropriate constants.  This   */
161 /*    is not useful for longer numbers because overflow of 32 bits    */
162 /*    would lead to 4 multiplies, which is almost as expensive as     */
163 /*    a divide (unless a floating-point or 64-bit multiply is         */
164 /*    assumed to be available).                                       */
165 /*                                                                    */
166 /* 8. Unusual abbreviations that may be used in the commentary:       */
167 /*      lhs -- left hand side (operand, of an operation)              */
168 /*      lsd -- least significant digit (of coefficient)               */
169 /*      lsu -- least significant Unit (of coefficient)                */
170 /*      msd -- most significant digit (of coefficient)                */
171 /*      msi -- most significant item (in an array)                    */
172 /*      msu -- most significant Unit (of coefficient)                 */
173 /*      rhs -- right hand side (operand, of an operation)             */
174 /*      +ve -- positive                                               */
175 /*      -ve -- negative                                               */
176 /*      **  -- raise to the power                                     */
177 /* ------------------------------------------------------------------ */
178 
179 #include <stdlib.h>                /* for malloc, free, etc.  */
180 /*  #include <stdio.h>   */        /* for printf [if needed]  */
181 #include <string.h>                /* for strcpy  */
182 #include <ctype.h>                 /* for lower  */
183 #include "cmemory.h"               /* for uprv_malloc, etc., in ICU */
184 #include "decNumber.h"             /* base number library  */
185 #include "decNumberLocal.h"        /* decNumber local types, etc.  */
186 #include "uassert.h"
187 
188 /* Constants */
189 /* Public lookup table used by the D2U macro  */
190 static const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
191 
192 #define DECVERB     1              /* set to 1 for verbose DECCHECK  */
193 #define powers      DECPOWERS      /* old internal name  */
194 
195 /* Local constants  */
196 #define DIVIDE      0x80           /* Divide operators  */
197 #define REMAINDER   0x40           /* ..  */
198 #define DIVIDEINT   0x20           /* ..  */
199 #define REMNEAR     0x10           /* ..  */
200 #define COMPARE     0x01           /* Compare operators  */
201 #define COMPMAX     0x02           /* ..  */
202 #define COMPMIN     0x03           /* ..  */
203 #define COMPTOTAL   0x04           /* ..  */
204 #define COMPNAN     0x05           /* .. [NaN processing]  */
205 #define COMPSIG     0x06           /* .. [signaling COMPARE]  */
206 #define COMPMAXMAG  0x07           /* ..  */
207 #define COMPMINMAG  0x08           /* ..  */
208 
209 #define DEC_sNaN     0x40000000    /* local status: sNaN signal  */
210 #define BADINT  (Int)0x80000000    /* most-negative Int; error indicator  */
211 /* Next two indicate an integer >= 10**6, and its parity (bottom bit)  */
212 #define BIGEVEN (Int)0x80000002
213 #define BIGODD  (Int)0x80000003
214 
215 static const Unit uarrone[1]={1};   /* Unit array of 1, used for incrementing  */
216 
217 /* ------------------------------------------------------------------ */
218 /* round-for-reround digits                                           */
219 /* ------------------------------------------------------------------ */
220 #if 0
221 static const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */
222 #endif
223 
224 /* ------------------------------------------------------------------ */
225 /* Powers of ten (powers[n]==10**n, 0<=n<=9)                          */
226 /* ------------------------------------------------------------------ */
227 static const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000,
228                           10000000, 100000000, 1000000000};
229 
230 
231 /* Granularity-dependent code */
232 #if DECDPUN<=4
233   #define eInt  Int           /* extended integer  */
234   #define ueInt uInt          /* unsigned extended integer  */
235   /* Constant multipliers for divide-by-power-of five using reciprocal  */
236   /* multiply, after removing powers of 2 by shifting, and final shift  */
237   /* of 17 [we only need up to **4]  */
238   static const uInt multies[]={131073, 26215, 5243, 1049, 210};
239   /* QUOT10 -- macro to return the quotient of unit u divided by 10**n  */
240   #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
241 #else
242   /* For DECDPUN>4 non-ANSI-89 64-bit types are needed.  */
243   #if !DECUSE64
244     #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
245   #endif
246   #define eInt  Long          /* extended integer  */
247   #define ueInt uLong         /* unsigned extended integer  */
248 #endif
249 
250 /* Local routines */
251 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
252                               decContext *, uByte, uInt *);
253 static Flag        decBiStr(const char *, const char *, const char *);
254 static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
255 static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
256 static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
257 static decNumber * decCompareOp(decNumber *, const decNumber *,
258                               const decNumber *, decContext *,
259                               Flag, uInt *);
260 static void        decCopyFit(decNumber *, const decNumber *, decContext *,
261                               Int *, uInt *);
262 static decNumber * decDecap(decNumber *, Int);
263 static decNumber * decDivideOp(decNumber *, const decNumber *,
264                               const decNumber *, decContext *, Flag, uInt *);
265 static decNumber * decExpOp(decNumber *, const decNumber *,
266                               decContext *, uInt *);
267 static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
268 static Int         decGetDigits(Unit *, Int);
269 static Int         decGetInt(const decNumber *);
270 static decNumber * decLnOp(decNumber *, const decNumber *,
271                               decContext *, uInt *);
272 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
273                               const decNumber *, decContext *,
274                               uInt *);
275 static decNumber * decNaNs(decNumber *, const decNumber *,
276                               const decNumber *, decContext *, uInt *);
277 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
278                               const decNumber *, decContext *, Flag,
279                               uInt *);
280 static void        decReverse(Unit *, Unit *);
281 static void        decSetCoeff(decNumber *, decContext *, const Unit *,
282                               Int, Int *, uInt *);
283 static void        decSetMaxValue(decNumber *, decContext *);
284 static void        decSetOverflow(decNumber *, decContext *, uInt *);
285 static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
286 static Int         decShiftToLeast(Unit *, Int, Int);
287 static Int         decShiftToMost(Unit *, Int, Int);
288 static void        decStatus(decNumber *, uInt, decContext *);
289 static void        decToString(const decNumber *, char[], Flag);
290 static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
291 static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
292                               Unit *, Int);
293 static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
294 
295 #if !DECSUBSET
296 /* decFinish == decFinalize when no subset arithmetic needed */
297 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
298 #else
299 static void        decFinish(decNumber *, decContext *, Int *, uInt *);
300 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
301 #endif
302 
303 /* Local macros */
304 /* masked special-values bits  */
305 #define SPECIALARG  (rhs->bits & DECSPECIAL)
306 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
307 
308 /* For use in ICU */
309 #define malloc(a) uprv_malloc(a)
310 #define free(a) uprv_free(a)
311 
312 /* Diagnostic macros, etc. */
313 #if DECALLOC
314 /* Handle malloc/free accounting.  If enabled, our accountable routines  */
315 /* are used; otherwise the code just goes straight to the system malloc  */
316 /* and free routines.  */
317 #define malloc(a) decMalloc(a)
318 #define free(a) decFree(a)
319 #define DECFENCE 0x5a              /* corruption detector  */
320 /* 'Our' malloc and free:  */
321 static void *decMalloc(size_t);
322 static void  decFree(void *);
323 uInt decAllocBytes=0;              /* count of bytes allocated  */
324 /* Note that DECALLOC code only checks for storage buffer overflow.  */
325 /* To check for memory leaks, the decAllocBytes variable must be  */
326 /* checked to be 0 at appropriate times (e.g., after the test  */
327 /* harness completes a set of tests).  This checking may be unreliable  */
328 /* if the testing is done in a multi-thread environment.  */
329 #endif
330 
331 #if DECCHECK
332 /* Optional checking routines.  Enabling these means that decNumber  */
333 /* and decContext operands to operator routines are checked for  */
334 /* correctness.  This roughly doubles the execution time of the  */
335 /* fastest routines (and adds 600+ bytes), so should not normally be  */
336 /* used in 'production'.  */
337 /* decCheckInexact is used to check that inexact results have a full  */
338 /* complement of digits (where appropriate -- this is not the case  */
339 /* for Quantize, for example)  */
340 #define DECUNRESU ((decNumber *)(void *)0xffffffff)
341 #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
342 #define DECUNCONT ((decContext *)(void *)(0xffffffff))
343 static Flag decCheckOperands(decNumber *, const decNumber *,
344                              const decNumber *, decContext *);
345 static Flag decCheckNumber(const decNumber *);
346 static void decCheckInexact(const decNumber *, decContext *);
347 #endif
348 
349 #if DECTRACE || DECCHECK
350 /* Optional trace/debugging routines (may or may not be used)  */
351 void decNumberShow(const decNumber *);  /* displays the components of a number  */
352 static void decDumpAr(char, const Unit *, Int);
353 #endif
354 
355 /* ================================================================== */
356 /* Conversions                                                        */
357 /* ================================================================== */
358 
359 /* ------------------------------------------------------------------ */
360 /* from-int32 -- conversion from Int or uInt                          */
361 /*                                                                    */
362 /*  dn is the decNumber to receive the integer                        */
363 /*  in or uin is the integer to be converted                          */
364 /*  returns dn                                                        */
365 /*                                                                    */
366 /* No error is possible.                                              */
367 /* ------------------------------------------------------------------ */
uprv_decNumberFromInt32(decNumber * dn,Int in)368 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
369   uInt unsig;
370   if (in>=0) unsig=in;
371    else {                               /* negative (possibly BADINT)  */
372     if (in==BADINT) unsig=(uInt)1073741824*2; /* special case  */
373      else unsig=-in;                    /* invert  */
374     }
375   /* in is now positive  */
376   uprv_decNumberFromUInt32(dn, unsig);
377   if (in<0) dn->bits=DECNEG;            /* sign needed  */
378   return dn;
379   } /* decNumberFromInt32  */
380 
uprv_decNumberFromUInt32(decNumber * dn,uInt uin)381 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
382   Unit *up;                             /* work pointer  */
383   uprv_decNumberZero(dn);                    /* clean  */
384   if (uin==0) return dn;                /* [or decGetDigits bad call]  */
385   for (up=dn->lsu; uin>0; up++) {
386     *up=(Unit)(uin%(DECDPUNMAX+1));
387     uin=uin/(DECDPUNMAX+1);
388     }
389   dn->digits=decGetDigits(dn->lsu, static_cast<int32_t>(up - dn->lsu));
390   return dn;
391   } /* decNumberFromUInt32  */
392 
393 /* ------------------------------------------------------------------ */
394 /* to-int32 -- conversion to Int or uInt                              */
395 /*                                                                    */
396 /*  dn is the decNumber to convert                                    */
397 /*  set is the context for reporting errors                           */
398 /*  returns the converted decNumber, or 0 if Invalid is set           */
399 /*                                                                    */
400 /* Invalid is set if the decNumber does not have exponent==0 or if    */
401 /* it is a NaN, Infinite, or out-of-range.                            */
402 /* ------------------------------------------------------------------ */
uprv_decNumberToInt32(const decNumber * dn,decContext * set)403 U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
404   #if DECCHECK
405   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
406   #endif
407 
408   /* special or too many digits, or bad exponent  */
409   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad  */
410    else { /* is a finite integer with 10 or fewer digits  */
411     Int d;                         /* work  */
412     const Unit *up;                /* ..  */
413     uInt hi=0, lo;                 /* ..  */
414     up=dn->lsu;                    /* -> lsu  */
415     lo=*up;                        /* get 1 to 9 digits  */
416     #if DECDPUN>1                  /* split to higher  */
417       hi=lo/10;
418       lo=lo%10;
419     #endif
420     up++;
421     /* collect remaining Units, if any, into hi  */
422     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
423     /* now low has the lsd, hi the remainder  */
424     if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range?  */
425       /* most-negative is a reprieve  */
426       if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
427       /* bad -- drop through  */
428       }
429      else { /* in-range always  */
430       Int i=X10(hi)+lo;
431       if (dn->bits&DECNEG) return -i;
432       return i;
433       }
434     } /* integer  */
435   uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
436   return 0;
437   } /* decNumberToInt32  */
438 
uprv_decNumberToUInt32(const decNumber * dn,decContext * set)439 U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
440   #if DECCHECK
441   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
442   #endif
443   /* special or too many digits, or bad exponent, or negative (<0)  */
444   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
445     || (dn->bits&DECNEG && !ISZERO(dn)));                   /* bad  */
446    else { /* is a finite integer with 10 or fewer digits  */
447     Int d;                         /* work  */
448     const Unit *up;                /* ..  */
449     uInt hi=0, lo;                 /* ..  */
450     up=dn->lsu;                    /* -> lsu  */
451     lo=*up;                        /* get 1 to 9 digits  */
452     #if DECDPUN>1                  /* split to higher  */
453       hi=lo/10;
454       lo=lo%10;
455     #endif
456     up++;
457     /* collect remaining Units, if any, into hi  */
458     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
459 
460     /* now low has the lsd, hi the remainder  */
461     if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible  */
462      else return X10(hi)+lo;
463     } /* integer  */
464   uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
465   return 0;
466   } /* decNumberToUInt32  */
467 
468 /* ------------------------------------------------------------------ */
469 /* to-scientific-string -- conversion to numeric string               */
470 /* to-engineering-string -- conversion to numeric string              */
471 /*                                                                    */
472 /*   decNumberToString(dn, string);                                   */
473 /*   decNumberToEngString(dn, string);                                */
474 /*                                                                    */
475 /*  dn is the decNumber to convert                                    */
476 /*  string is the string where the result will be laid out            */
477 /*                                                                    */
478 /*  string must be at least dn->digits+14 characters long             */
479 /*                                                                    */
480 /*  No error is possible, and no status can be set.                   */
481 /* ------------------------------------------------------------------ */
uprv_decNumberToString(const decNumber * dn,char * string)482 U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
483   decToString(dn, string, 0);
484   return string;
485   } /* DecNumberToString  */
486 
uprv_decNumberToEngString(const decNumber * dn,char * string)487 U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
488   decToString(dn, string, 1);
489   return string;
490   } /* DecNumberToEngString  */
491 
492 /* ------------------------------------------------------------------ */
493 /* to-number -- conversion from numeric string                        */
494 /*                                                                    */
495 /* decNumberFromString -- convert string to decNumber                 */
496 /*   dn        -- the number structure to fill                        */
497 /*   chars[]   -- the string to convert ('\0' terminated)             */
498 /*   set       -- the context used for processing any error,          */
499 /*                determining the maximum precision available         */
500 /*                (set.digits), determining the maximum and minimum   */
501 /*                exponent (set.emax and set.emin), determining if    */
502 /*                extended values are allowed, and checking the       */
503 /*                rounding mode if overflow occurs or rounding is     */
504 /*                needed.                                             */
505 /*                                                                    */
506 /* The length of the coefficient and the size of the exponent are     */
507 /* checked by this routine, so the correct error (Underflow or        */
508 /* Overflow) can be reported or rounding applied, as necessary.       */
509 /*                                                                    */
510 /* If bad syntax is detected, the result will be a quiet NaN.         */
511 /* ------------------------------------------------------------------ */
uprv_decNumberFromString(decNumber * dn,const char chars[],decContext * set)512 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
513                                 decContext *set) {
514   Int   exponent=0;                /* working exponent [assume 0]  */
515   uByte bits=0;                    /* working flags [assume +ve]  */
516   Unit  *res;                      /* where result will be built  */
517   Unit  resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary  */
518                                    /* [+9 allows for ln() constants]  */
519   Unit  *allocres=NULL;            /* -> allocated result, iff allocated  */
520   Int   d=0;                       /* count of digits found in decimal part  */
521   const char *dotchar=NULL;        /* where dot was found  */
522   const char *cfirst=chars;        /* -> first character of decimal part  */
523   const char *last=NULL;           /* -> last digit of decimal part  */
524   const char *c;                   /* work  */
525   Unit  *up;                       /* ..  */
526   #if DECDPUN>1
527   Int   cut, out;                  /* ..  */
528   #endif
529   Int   residue;                   /* rounding residue  */
530   uInt  status=0;                  /* error code  */
531 
532   #if DECCHECK
533   if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
534     return uprv_decNumberZero(dn);
535   #endif
536 
537   do {                             /* status & malloc protection  */
538     for (c=chars;; c++) {          /* -> input character  */
539       if (*c>='0' && *c<='9') {    /* test for Arabic digit  */
540         last=c;
541         d++;                       /* count of real digits  */
542         continue;                  /* still in decimal part  */
543         }
544       if (*c=='.' && dotchar==NULL) { /* first '.'  */
545         dotchar=c;                 /* record offset into decimal part  */
546         if (c==cfirst) cfirst++;   /* first digit must follow  */
547         continue;}
548       if (c==chars) {              /* first in string...  */
549         if (*c=='-') {             /* valid - sign  */
550           cfirst++;
551           bits=DECNEG;
552           continue;}
553         if (*c=='+') {             /* valid + sign  */
554           cfirst++;
555           continue;}
556         }
557       /* *c is not a digit, or a valid +, -, or '.'  */
558       break;
559       } /* c  */
560 
561     if (last==NULL) {              /* no digits yet  */
562       status=DEC_Conversion_syntax;/* assume the worst  */
563       if (*c=='\0') break;         /* and no more to come...  */
564       #if DECSUBSET
565       /* if subset then infinities and NaNs are not allowed  */
566       if (!set->extended) break;   /* hopeless  */
567       #endif
568       /* Infinities and NaNs are possible, here  */
569       if (dotchar!=NULL) break;    /* .. unless had a dot  */
570       uprv_decNumberZero(dn);           /* be optimistic  */
571       if (decBiStr(c, "infinity", "INFINITY")
572        || decBiStr(c, "inf", "INF")) {
573         dn->bits=bits | DECINF;
574         status=0;                  /* is OK  */
575         break; /* all done  */
576         }
577       /* a NaN expected  */
578       /* 2003.09.10 NaNs are now permitted to have a sign  */
579       dn->bits=bits | DECNAN;      /* assume simple NaN  */
580       if (*c=='s' || *c=='S') {    /* looks like an sNaN  */
581         c++;
582         dn->bits=bits | DECSNAN;
583         }
584       if (*c!='n' && *c!='N') break;    /* check caseless "NaN"  */
585       c++;
586       if (*c!='a' && *c!='A') break;    /* ..  */
587       c++;
588       if (*c!='n' && *c!='N') break;    /* ..  */
589       c++;
590       /* now either nothing, or nnnn payload, expected  */
591       /* -> start of integer and skip leading 0s [including plain 0]  */
592       for (cfirst=c; *cfirst=='0';) cfirst++;
593       if (*cfirst=='\0') {         /* "NaN" or "sNaN", maybe with all 0s  */
594         status=0;                  /* it's good  */
595         break;                     /* ..  */
596         }
597       /* something other than 0s; setup last and d as usual [no dots]  */
598       for (c=cfirst;; c++, d++) {
599         if (*c<'0' || *c>'9') break; /* test for Arabic digit  */
600         last=c;
601         }
602       if (*c!='\0') break;         /* not all digits  */
603       if (d>set->digits-1) {
604         /* [NB: payload in a decNumber can be full length unless  */
605         /* clamped, in which case can only be digits-1]  */
606         if (set->clamp) break;
607         if (d>set->digits) break;
608         } /* too many digits?  */
609       /* good; drop through to convert the integer to coefficient  */
610       status=0;                    /* syntax is OK  */
611       bits=dn->bits;               /* for copy-back  */
612       } /* last==NULL  */
613 
614      else if (*c!='\0') {          /* more to process...  */
615       /* had some digits; exponent is only valid sequence now  */
616       Flag nege;                   /* 1=negative exponent  */
617       const char *firstexp;        /* -> first significant exponent digit  */
618       status=DEC_Conversion_syntax;/* assume the worst  */
619       if (*c!='e' && *c!='E') break;
620       /* Found 'e' or 'E' -- now process explicit exponent */
621       /* 1998.07.11: sign no longer required  */
622       nege=0;
623       c++;                         /* to (possible) sign  */
624       if (*c=='-') {nege=1; c++;}
625        else if (*c=='+') c++;
626       if (*c=='\0') break;
627 
628       for (; *c=='0' && *(c+1)!='\0';) c++;  /* strip insignificant zeros  */
629       firstexp=c;                            /* save exponent digit place  */
630       uInt uexponent = 0;   /* Avoid undefined behavior on signed int overflow */
631       for (; ;c++) {
632         if (*c<'0' || *c>'9') break;         /* not a digit  */
633         uexponent=X10(uexponent)+(uInt)*c-(uInt)'0';
634         } /* c  */
635       exponent = (Int)uexponent;
636       /* if not now on a '\0', *c must not be a digit  */
637       if (*c!='\0') break;
638 
639       /* (this next test must be after the syntax checks)  */
640       /* if it was too long the exponent may have wrapped, so check  */
641       /* carefully and set it to a certain overflow if wrap possible  */
642       if (c>=firstexp+9+1) {
643         if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
644         /* [up to 1999999999 is OK, for example 1E-1000000998]  */
645         }
646       if (nege) exponent=-exponent;     /* was negative  */
647       status=0;                         /* is OK  */
648       } /* stuff after digits  */
649 
650     /* Here when whole string has been inspected; syntax is good  */
651     /* cfirst->first digit (never dot), last->last digit (ditto)  */
652 
653     /* strip leading zeros/dot [leave final 0 if all 0's]  */
654     if (*cfirst=='0') {                 /* [cfirst has stepped over .]  */
655       for (c=cfirst; c<last; c++, cfirst++) {
656         if (*c=='.') continue;          /* ignore dots  */
657         if (*c!='0') break;             /* non-zero found  */
658         d--;                            /* 0 stripped  */
659         } /* c  */
660       #if DECSUBSET
661       /* make a rapid exit for easy zeros if !extended  */
662       if (*cfirst=='0' && !set->extended) {
663         uprv_decNumberZero(dn);              /* clean result  */
664         break;                          /* [could be return]  */
665         }
666       #endif
667       } /* at least one leading 0  */
668 
669     /* Handle decimal point...  */
670     if (dotchar!=NULL && dotchar<last)  /* non-trailing '.' found?  */
671       exponent -= static_cast<int32_t>(last-dotchar);         /* adjust exponent  */
672     /* [we can now ignore the .]  */
673 
674     /* OK, the digits string is good.  Assemble in the decNumber, or in  */
675     /* a temporary units array if rounding is needed  */
676     if (d<=set->digits) res=dn->lsu;    /* fits into supplied decNumber  */
677      else {                             /* rounding needed  */
678       Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed  */
679       res=resbuff;                      /* assume use local buffer  */
680       if (needbytes>(Int)sizeof(resbuff)) { /* too big for local  */
681         allocres=(Unit *)malloc(needbytes);
682         if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
683         res=allocres;
684         }
685       }
686     /* res now -> number lsu, buffer, or allocated storage for Unit array  */
687 
688     /* Place the coefficient into the selected Unit array  */
689     /* [this is often 70% of the cost of this function when DECDPUN>1]  */
690     #if DECDPUN>1
691     out=0;                         /* accumulator  */
692     up=res+D2U(d)-1;               /* -> msu  */
693     cut=d-(up-res)*DECDPUN;        /* digits in top unit  */
694     for (c=cfirst;; c++) {         /* along the digits  */
695       if (*c=='.') continue;       /* ignore '.' [don't decrement cut]  */
696       out=X10(out)+(Int)*c-(Int)'0';
697       if (c==last) break;          /* done [never get to trailing '.']  */
698       cut--;
699       if (cut>0) continue;         /* more for this unit  */
700       *up=(Unit)out;               /* write unit  */
701       up--;                        /* prepare for unit below..  */
702       cut=DECDPUN;                 /* ..  */
703       out=0;                       /* ..  */
704       } /* c  */
705     *up=(Unit)out;                 /* write lsu  */
706 
707     #else
708     /* DECDPUN==1  */
709     up=res;                        /* -> lsu  */
710     for (c=last; c>=cfirst; c--) { /* over each character, from least  */
711       if (*c=='.') continue;       /* ignore . [don't step up]  */
712       *up=(Unit)((Int)*c-(Int)'0');
713       up++;
714       } /* c  */
715     #endif
716 
717     dn->bits=bits;
718     dn->exponent=exponent;
719     dn->digits=d;
720 
721     /* if not in number (too long) shorten into the number  */
722     if (d>set->digits) {
723       residue=0;
724       decSetCoeff(dn, set, res, d, &residue, &status);
725       /* always check for overflow or subnormal and round as needed  */
726       decFinalize(dn, set, &residue, &status);
727       }
728      else { /* no rounding, but may still have overflow or subnormal  */
729       /* [these tests are just for performance; finalize repeats them]  */
730       if ((dn->exponent-1<set->emin-dn->digits)
731        || (dn->exponent-1>set->emax-set->digits)) {
732         residue=0;
733         decFinalize(dn, set, &residue, &status);
734         }
735       }
736     /* decNumberShow(dn);  */
737     } while(0);                         /* [for break]  */
738 
739   if (allocres!=NULL) free(allocres);   /* drop any storage used  */
740   if (status!=0) decStatus(dn, status, set);
741   return dn;
742   } /* decNumberFromString */
743 
744 /* ================================================================== */
745 /* Operators                                                          */
746 /* ================================================================== */
747 
748 /* ------------------------------------------------------------------ */
749 /* decNumberAbs -- absolute value operator                            */
750 /*                                                                    */
751 /*   This computes C = abs(A)                                         */
752 /*                                                                    */
753 /*   res is C, the result.  C may be A                                */
754 /*   rhs is A                                                         */
755 /*   set is the context                                               */
756 /*                                                                    */
757 /* See also decNumberCopyAbs for a quiet bitwise version of this.     */
758 /* C must have space for set->digits digits.                          */
759 /* ------------------------------------------------------------------ */
760 /* This has the same effect as decNumberPlus unless A is negative,    */
761 /* in which case it has the same effect as decNumberMinus.            */
762 /* ------------------------------------------------------------------ */
uprv_decNumberAbs(decNumber * res,const decNumber * rhs,decContext * set)763 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
764                          decContext *set) {
765   decNumber dzero;                      /* for 0  */
766   uInt status=0;                        /* accumulator  */
767 
768   #if DECCHECK
769   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
770   #endif
771 
772   uprv_decNumberZero(&dzero);                /* set 0  */
773   dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
774   decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
775   if (status!=0) decStatus(res, status, set);
776   #if DECCHECK
777   decCheckInexact(res, set);
778   #endif
779   return res;
780   } /* decNumberAbs  */
781 
782 /* ------------------------------------------------------------------ */
783 /* decNumberAdd -- add two Numbers                                    */
784 /*                                                                    */
785 /*   This computes C = A + B                                          */
786 /*                                                                    */
787 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
788 /*   lhs is A                                                         */
789 /*   rhs is B                                                         */
790 /*   set is the context                                               */
791 /*                                                                    */
792 /* C must have space for set->digits digits.                          */
793 /* ------------------------------------------------------------------ */
794 /* This just calls the routine shared with Subtract                   */
uprv_decNumberAdd(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)795 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
796                          const decNumber *rhs, decContext *set) {
797   uInt status=0;                        /* accumulator  */
798   decAddOp(res, lhs, rhs, set, 0, &status);
799   if (status!=0) decStatus(res, status, set);
800   #if DECCHECK
801   decCheckInexact(res, set);
802   #endif
803   return res;
804   } /* decNumberAdd  */
805 
806 /* ------------------------------------------------------------------ */
807 /* decNumberAnd -- AND two Numbers, digitwise                         */
808 /*                                                                    */
809 /*   This computes C = A & B                                          */
810 /*                                                                    */
811 /*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
812 /*   lhs is A                                                         */
813 /*   rhs is B                                                         */
814 /*   set is the context (used for result length and error report)     */
815 /*                                                                    */
816 /* C must have space for set->digits digits.                          */
817 /*                                                                    */
818 /* Logical function restrictions apply (see above); a NaN is          */
819 /* returned with Invalid_operation if a restriction is violated.      */
820 /* ------------------------------------------------------------------ */
uprv_decNumberAnd(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)821 U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
822                          const decNumber *rhs, decContext *set) {
823   const Unit *ua, *ub;                  /* -> operands  */
824   const Unit *msua, *msub;              /* -> operand msus  */
825   Unit *uc,  *msuc;                     /* -> result and its msu  */
826   Int   msudigs;                        /* digits in res msu  */
827   #if DECCHECK
828   if (decCheckOperands(res, lhs, rhs, set)) return res;
829   #endif
830 
831   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
832    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
833     decStatus(res, DEC_Invalid_operation, set);
834     return res;
835     }
836 
837   /* operands are valid  */
838   ua=lhs->lsu;                          /* bottom-up  */
839   ub=rhs->lsu;                          /* ..  */
840   uc=res->lsu;                          /* ..  */
841   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
842   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
843   msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
844   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
845   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
846     Unit a, b;                          /* extract units  */
847     if (ua>msua) a=0;
848      else a=*ua;
849     if (ub>msub) b=0;
850      else b=*ub;
851     *uc=0;                              /* can now write back  */
852     if (a|b) {                          /* maybe 1 bits to examine  */
853       Int i, j;
854       *uc=0;                            /* can now write back  */
855       /* This loop could be unrolled and/or use BIN2BCD tables  */
856       for (i=0; i<DECDPUN; i++) {
857         if (a&b&1) *uc=*uc+(Unit)powers[i];  /* effect AND  */
858         j=a%10;
859         a=a/10;
860         j|=b%10;
861         b=b/10;
862         if (j>1) {
863           decStatus(res, DEC_Invalid_operation, set);
864           return res;
865           }
866         if (uc==msuc && i==msudigs-1) break; /* just did final digit  */
867         } /* each digit  */
868       } /* both OK  */
869     } /* each unit  */
870   /* [here uc-1 is the msu of the result]  */
871   res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc - res->lsu));
872   res->exponent=0;                      /* integer  */
873   res->bits=0;                          /* sign=0  */
874   return res;  /* [no status to set]  */
875   } /* decNumberAnd  */
876 
877 /* ------------------------------------------------------------------ */
878 /* decNumberCompare -- compare two Numbers                            */
879 /*                                                                    */
880 /*   This computes C = A ? B                                          */
881 /*                                                                    */
882 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
883 /*   lhs is A                                                         */
884 /*   rhs is B                                                         */
885 /*   set is the context                                               */
886 /*                                                                    */
887 /* C must have space for one digit (or NaN).                          */
888 /* ------------------------------------------------------------------ */
uprv_decNumberCompare(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)889 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
890                              const decNumber *rhs, decContext *set) {
891   uInt status=0;                        /* accumulator  */
892   decCompareOp(res, lhs, rhs, set, COMPARE, &status);
893   if (status!=0) decStatus(res, status, set);
894   return res;
895   } /* decNumberCompare  */
896 
897 /* ------------------------------------------------------------------ */
898 /* decNumberCompareSignal -- compare, signalling on all NaNs          */
899 /*                                                                    */
900 /*   This computes C = A ? B                                          */
901 /*                                                                    */
902 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
903 /*   lhs is A                                                         */
904 /*   rhs is B                                                         */
905 /*   set is the context                                               */
906 /*                                                                    */
907 /* C must have space for one digit (or NaN).                          */
908 /* ------------------------------------------------------------------ */
uprv_decNumberCompareSignal(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)909 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
910                                    const decNumber *rhs, decContext *set) {
911   uInt status=0;                        /* accumulator  */
912   decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
913   if (status!=0) decStatus(res, status, set);
914   return res;
915   } /* decNumberCompareSignal  */
916 
917 /* ------------------------------------------------------------------ */
918 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
919 /*                                                                    */
920 /*   This computes C = A ? B, under total ordering                    */
921 /*                                                                    */
922 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
923 /*   lhs is A                                                         */
924 /*   rhs is B                                                         */
925 /*   set is the context                                               */
926 /*                                                                    */
927 /* C must have space for one digit; the result will always be one of  */
928 /* -1, 0, or 1.                                                       */
929 /* ------------------------------------------------------------------ */
uprv_decNumberCompareTotal(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)930 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
931                                   const decNumber *rhs, decContext *set) {
932   uInt status=0;                        /* accumulator  */
933   decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
934   if (status!=0) decStatus(res, status, set);
935   return res;
936   } /* decNumberCompareTotal  */
937 
938 /* ------------------------------------------------------------------ */
939 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
940 /*                                                                    */
941 /*   This computes C = |A| ? |B|, under total ordering                */
942 /*                                                                    */
943 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
944 /*   lhs is A                                                         */
945 /*   rhs is B                                                         */
946 /*   set is the context                                               */
947 /*                                                                    */
948 /* C must have space for one digit; the result will always be one of  */
949 /* -1, 0, or 1.                                                       */
950 /* ------------------------------------------------------------------ */
uprv_decNumberCompareTotalMag(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)951 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
952                                      const decNumber *rhs, decContext *set) {
953   uInt status=0;                   /* accumulator  */
954   uInt needbytes;                  /* for space calculations  */
955   decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0  */
956   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
957   decNumber bufb[D2N(DECBUFFER+1)];
958   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
959   decNumber *a, *b;                /* temporary pointers  */
960 
961   #if DECCHECK
962   if (decCheckOperands(res, lhs, rhs, set)) return res;
963   #endif
964 
965   do {                                  /* protect allocated storage  */
966     /* if either is negative, take a copy and absolute  */
967     if (decNumberIsNegative(lhs)) {     /* lhs<0  */
968       a=bufa;
969       needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
970       if (needbytes>sizeof(bufa)) {     /* need malloc space  */
971         allocbufa=(decNumber *)malloc(needbytes);
972         if (allocbufa==NULL) {          /* hopeless -- abandon  */
973           status|=DEC_Insufficient_storage;
974           break;}
975         a=allocbufa;                    /* use the allocated space  */
976         }
977       uprv_decNumberCopy(a, lhs);            /* copy content  */
978       a->bits&=~DECNEG;                 /* .. and clear the sign  */
979       lhs=a;                            /* use copy from here on  */
980       }
981     if (decNumberIsNegative(rhs)) {     /* rhs<0  */
982       b=bufb;
983       needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
984       if (needbytes>sizeof(bufb)) {     /* need malloc space  */
985         allocbufb=(decNumber *)malloc(needbytes);
986         if (allocbufb==NULL) {          /* hopeless -- abandon  */
987           status|=DEC_Insufficient_storage;
988           break;}
989         b=allocbufb;                    /* use the allocated space  */
990         }
991       uprv_decNumberCopy(b, rhs);            /* copy content  */
992       b->bits&=~DECNEG;                 /* .. and clear the sign  */
993       rhs=b;                            /* use copy from here on  */
994       }
995     decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
996     } while(0);                         /* end protected  */
997 
998   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
999   if (allocbufb!=NULL) free(allocbufb); /* ..  */
1000   if (status!=0) decStatus(res, status, set);
1001   return res;
1002   } /* decNumberCompareTotalMag  */
1003 
1004 /* ------------------------------------------------------------------ */
1005 /* decNumberDivide -- divide one number by another                    */
1006 /*                                                                    */
1007 /*   This computes C = A / B                                          */
1008 /*                                                                    */
1009 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
1010 /*   lhs is A                                                         */
1011 /*   rhs is B                                                         */
1012 /*   set is the context                                               */
1013 /*                                                                    */
1014 /* C must have space for set->digits digits.                          */
1015 /* ------------------------------------------------------------------ */
uprv_decNumberDivide(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1016 U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
1017                             const decNumber *rhs, decContext *set) {
1018   uInt status=0;                        /* accumulator  */
1019   decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1020   if (status!=0) decStatus(res, status, set);
1021   #if DECCHECK
1022   decCheckInexact(res, set);
1023   #endif
1024   return res;
1025   } /* decNumberDivide  */
1026 
1027 /* ------------------------------------------------------------------ */
1028 /* decNumberDivideInteger -- divide and return integer quotient       */
1029 /*                                                                    */
1030 /*   This computes C = A # B, where # is the integer divide operator  */
1031 /*                                                                    */
1032 /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1033 /*   lhs is A                                                         */
1034 /*   rhs is B                                                         */
1035 /*   set is the context                                               */
1036 /*                                                                    */
1037 /* C must have space for set->digits digits.                          */
1038 /* ------------------------------------------------------------------ */
uprv_decNumberDivideInteger(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1039 U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1040                                    const decNumber *rhs, decContext *set) {
1041   uInt status=0;                        /* accumulator  */
1042   decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1043   if (status!=0) decStatus(res, status, set);
1044   return res;
1045   } /* decNumberDivideInteger  */
1046 
1047 /* ------------------------------------------------------------------ */
1048 /* decNumberExp -- exponentiation                                     */
1049 /*                                                                    */
1050 /*   This computes C = exp(A)                                         */
1051 /*                                                                    */
1052 /*   res is C, the result.  C may be A                                */
1053 /*   rhs is A                                                         */
1054 /*   set is the context; note that rounding mode has no effect        */
1055 /*                                                                    */
1056 /* C must have space for set->digits digits.                          */
1057 /*                                                                    */
1058 /* Mathematical function restrictions apply (see above); a NaN is     */
1059 /* returned with Invalid_operation if a restriction is violated.      */
1060 /*                                                                    */
1061 /* Finite results will always be full precision and Inexact, except   */
1062 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1063 /*                                                                    */
1064 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1065 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1066 /* error in rare cases.                                               */
1067 /* ------------------------------------------------------------------ */
1068 /* This is a wrapper for decExpOp which can handle the slightly wider */
1069 /* (double) range needed by Ln (which has to be able to calculate     */
1070 /* exp(-a) where a can be the tiniest number (Ntiny).                 */
1071 /* ------------------------------------------------------------------ */
uprv_decNumberExp(decNumber * res,const decNumber * rhs,decContext * set)1072 U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
1073                          decContext *set) {
1074   uInt status=0;                        /* accumulator  */
1075   #if DECSUBSET
1076   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1077   #endif
1078 
1079   #if DECCHECK
1080   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1081   #endif
1082 
1083   /* Check restrictions; these restrictions ensure that if h=8 (see  */
1084   /* decExpOp) then the result will either overflow or underflow to 0.  */
1085   /* Other math functions restrict the input range, too, for inverses.  */
1086   /* If not violated then carry out the operation.  */
1087   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1088     #if DECSUBSET
1089     if (!set->extended) {
1090       /* reduce operand and set lostDigits status, as needed  */
1091       if (rhs->digits>set->digits) {
1092         allocrhs=decRoundOperand(rhs, set, &status);
1093         if (allocrhs==NULL) break;
1094         rhs=allocrhs;
1095         }
1096       }
1097     #endif
1098     decExpOp(res, rhs, set, &status);
1099     } while(0);                         /* end protected  */
1100 
1101   #if DECSUBSET
1102   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1103   #endif
1104   /* apply significant status  */
1105   if (status!=0) decStatus(res, status, set);
1106   #if DECCHECK
1107   decCheckInexact(res, set);
1108   #endif
1109   return res;
1110   } /* decNumberExp  */
1111 
1112 /* ------------------------------------------------------------------ */
1113 /* decNumberFMA -- fused multiply add                                 */
1114 /*                                                                    */
1115 /*   This computes D = (A * B) + C with only one rounding             */
1116 /*                                                                    */
1117 /*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1118 /*   lhs is A                                                         */
1119 /*   rhs is B                                                         */
1120 /*   fhs is C [far hand side]                                         */
1121 /*   set is the context                                               */
1122 /*                                                                    */
1123 /* Mathematical function restrictions apply (see above); a NaN is     */
1124 /* returned with Invalid_operation if a restriction is violated.      */
1125 /*                                                                    */
1126 /* C must have space for set->digits digits.                          */
1127 /* ------------------------------------------------------------------ */
uprv_decNumberFMA(decNumber * res,const decNumber * lhs,const decNumber * rhs,const decNumber * fhs,decContext * set)1128 U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
1129                          const decNumber *rhs, const decNumber *fhs,
1130                          decContext *set) {
1131   uInt status=0;                   /* accumulator  */
1132   decContext dcmul;                /* context for the multiplication  */
1133   uInt needbytes;                  /* for space calculations  */
1134   decNumber bufa[D2N(DECBUFFER*2+1)];
1135   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1136   decNumber *acc;                  /* accumulator pointer  */
1137   decNumber dzero;                 /* work  */
1138 
1139   #if DECCHECK
1140   if (decCheckOperands(res, lhs, rhs, set)) return res;
1141   if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1142   #endif
1143 
1144   do {                                  /* protect allocated storage  */
1145     #if DECSUBSET
1146     if (!set->extended) {               /* [undefined if subset]  */
1147       status|=DEC_Invalid_operation;
1148       break;}
1149     #endif
1150     /* Check math restrictions [these ensure no overflow or underflow]  */
1151     if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1152      || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1153      || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1154     /* set up context for multiply  */
1155     dcmul=*set;
1156     dcmul.digits=lhs->digits+rhs->digits; /* just enough  */
1157     /* [The above may be an over-estimate for subset arithmetic, but that's OK]  */
1158     dcmul.emax=DEC_MAX_EMAX;            /* effectively unbounded ..  */
1159     dcmul.emin=DEC_MIN_EMIN;            /* [thanks to Math restrictions]  */
1160     /* set up decNumber space to receive the result of the multiply  */
1161     acc=bufa;                           /* may fit  */
1162     needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1163     if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1164       allocbufa=(decNumber *)malloc(needbytes);
1165       if (allocbufa==NULL) {            /* hopeless -- abandon  */
1166         status|=DEC_Insufficient_storage;
1167         break;}
1168       acc=allocbufa;                    /* use the allocated space  */
1169       }
1170     /* multiply with extended range and necessary precision  */
1171     /*printf("emin=%ld\n", dcmul.emin);  */
1172     decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1173     /* Only Invalid operation (from sNaN or Inf * 0) is possible in  */
1174     /* status; if either is seen than ignore fhs (in case it is  */
1175     /* another sNaN) and set acc to NaN unless we had an sNaN  */
1176     /* [decMultiplyOp leaves that to caller]  */
1177     /* Note sNaN has to go through addOp to shorten payload if  */
1178     /* necessary  */
1179     if ((status&DEC_Invalid_operation)!=0) {
1180       if (!(status&DEC_sNaN)) {         /* but be true invalid  */
1181         uprv_decNumberZero(res);             /* acc not yet set  */
1182         res->bits=DECNAN;
1183         break;
1184         }
1185       uprv_decNumberZero(&dzero);            /* make 0 (any non-NaN would do)  */
1186       fhs=&dzero;                       /* use that  */
1187       }
1188     #if DECCHECK
1189      else { /* multiply was OK  */
1190       if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1191       }
1192     #endif
1193     /* add the third operand and result -> res, and all is done  */
1194     decAddOp(res, acc, fhs, set, 0, &status);
1195     } while(0);                         /* end protected  */
1196 
1197   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1198   if (status!=0) decStatus(res, status, set);
1199   #if DECCHECK
1200   decCheckInexact(res, set);
1201   #endif
1202   return res;
1203   } /* decNumberFMA  */
1204 
1205 /* ------------------------------------------------------------------ */
1206 /* decNumberInvert -- invert a Number, digitwise                      */
1207 /*                                                                    */
1208 /*   This computes C = ~A                                             */
1209 /*                                                                    */
1210 /*   res is C, the result.  C may be A (e.g., X=~X)                   */
1211 /*   rhs is A                                                         */
1212 /*   set is the context (used for result length and error report)     */
1213 /*                                                                    */
1214 /* C must have space for set->digits digits.                          */
1215 /*                                                                    */
1216 /* Logical function restrictions apply (see above); a NaN is          */
1217 /* returned with Invalid_operation if a restriction is violated.      */
1218 /* ------------------------------------------------------------------ */
uprv_decNumberInvert(decNumber * res,const decNumber * rhs,decContext * set)1219 U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
1220                             decContext *set) {
1221   const Unit *ua, *msua;                /* -> operand and its msu  */
1222   Unit  *uc, *msuc;                     /* -> result and its msu  */
1223   Int   msudigs;                        /* digits in res msu  */
1224   #if DECCHECK
1225   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1226   #endif
1227 
1228   if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1229     decStatus(res, DEC_Invalid_operation, set);
1230     return res;
1231     }
1232   /* operand is valid  */
1233   ua=rhs->lsu;                          /* bottom-up  */
1234   uc=res->lsu;                          /* ..  */
1235   msua=ua+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1236   msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1237   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1238   for (; uc<=msuc; ua++, uc++) {        /* Unit loop  */
1239     Unit a;                             /* extract unit  */
1240     Int  i, j;                          /* work  */
1241     if (ua>msua) a=0;
1242      else a=*ua;
1243     *uc=0;                              /* can now write back  */
1244     /* always need to examine all bits in rhs  */
1245     /* This loop could be unrolled and/or use BIN2BCD tables  */
1246     for (i=0; i<DECDPUN; i++) {
1247       if ((~a)&1) *uc=*uc+(Unit)powers[i];   /* effect INVERT  */
1248       j=a%10;
1249       a=a/10;
1250       if (j>1) {
1251         decStatus(res, DEC_Invalid_operation, set);
1252         return res;
1253         }
1254       if (uc==msuc && i==msudigs-1) break;   /* just did final digit  */
1255       } /* each digit  */
1256     } /* each unit  */
1257   /* [here uc-1 is the msu of the result]  */
1258   res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc - res->lsu));
1259   res->exponent=0;                      /* integer  */
1260   res->bits=0;                          /* sign=0  */
1261   return res;  /* [no status to set]  */
1262   } /* decNumberInvert  */
1263 
1264 /* ------------------------------------------------------------------ */
1265 /* decNumberLn -- natural logarithm                                   */
1266 /*                                                                    */
1267 /*   This computes C = ln(A)                                          */
1268 /*                                                                    */
1269 /*   res is C, the result.  C may be A                                */
1270 /*   rhs is A                                                         */
1271 /*   set is the context; note that rounding mode has no effect        */
1272 /*                                                                    */
1273 /* C must have space for set->digits digits.                          */
1274 /*                                                                    */
1275 /* Notable cases:                                                     */
1276 /*   A<0 -> Invalid                                                   */
1277 /*   A=0 -> -Infinity (Exact)                                         */
1278 /*   A=+Infinity -> +Infinity (Exact)                                 */
1279 /*   A=1 exactly -> 0 (Exact)                                         */
1280 /*                                                                    */
1281 /* Mathematical function restrictions apply (see above); a NaN is     */
1282 /* returned with Invalid_operation if a restriction is violated.      */
1283 /*                                                                    */
1284 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1285 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1286 /* error in rare cases.                                               */
1287 /* ------------------------------------------------------------------ */
1288 /* This is a wrapper for decLnOp which can handle the slightly wider  */
1289 /* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1290 /* to calculate at p+e+2).                                            */
1291 /* ------------------------------------------------------------------ */
uprv_decNumberLn(decNumber * res,const decNumber * rhs,decContext * set)1292 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
1293                         decContext *set) {
1294   uInt status=0;                   /* accumulator  */
1295   #if DECSUBSET
1296   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1297   #endif
1298 
1299   #if DECCHECK
1300   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1301   #endif
1302 
1303   /* Check restrictions; this is a math function; if not violated  */
1304   /* then carry out the operation.  */
1305   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1306     #if DECSUBSET
1307     if (!set->extended) {
1308       /* reduce operand and set lostDigits status, as needed  */
1309       if (rhs->digits>set->digits) {
1310         allocrhs=decRoundOperand(rhs, set, &status);
1311         if (allocrhs==NULL) break;
1312         rhs=allocrhs;
1313         }
1314       /* special check in subset for rhs=0  */
1315       if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1316         status|=DEC_Invalid_operation;
1317         break;}
1318       } /* extended=0  */
1319     #endif
1320     decLnOp(res, rhs, set, &status);
1321     } while(0);                         /* end protected  */
1322 
1323   #if DECSUBSET
1324   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1325   #endif
1326   /* apply significant status  */
1327   if (status!=0) decStatus(res, status, set);
1328   #if DECCHECK
1329   decCheckInexact(res, set);
1330   #endif
1331   return res;
1332   } /* decNumberLn  */
1333 
1334 /* ------------------------------------------------------------------ */
1335 /* decNumberLogB - get adjusted exponent, by 754 rules                */
1336 /*                                                                    */
1337 /*   This computes C = adjustedexponent(A)                            */
1338 /*                                                                    */
1339 /*   res is C, the result.  C may be A                                */
1340 /*   rhs is A                                                         */
1341 /*   set is the context, used only for digits and status              */
1342 /*                                                                    */
1343 /* C must have space for 10 digits (A might have 10**9 digits and     */
1344 /* an exponent of +999999999, or one digit and an exponent of         */
1345 /* -1999999999).                                                      */
1346 /*                                                                    */
1347 /* This returns the adjusted exponent of A after (in theory) padding  */
1348 /* with zeros on the right to set->digits digits while keeping the    */
1349 /* same value.  The exponent is not limited by emin/emax.             */
1350 /*                                                                    */
1351 /* Notable cases:                                                     */
1352 /*   A<0 -> Use |A|                                                   */
1353 /*   A=0 -> -Infinity (Division by zero)                              */
1354 /*   A=Infinite -> +Infinity (Exact)                                  */
1355 /*   A=1 exactly -> 0 (Exact)                                         */
1356 /*   NaNs are propagated as usual                                     */
1357 /* ------------------------------------------------------------------ */
uprv_decNumberLogB(decNumber * res,const decNumber * rhs,decContext * set)1358 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
1359                           decContext *set) {
1360   uInt status=0;                   /* accumulator  */
1361 
1362   #if DECCHECK
1363   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1364   #endif
1365 
1366   /* NaNs as usual; Infinities return +Infinity; 0->oops  */
1367   if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1368    else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
1369    else if (decNumberIsZero(rhs)) {
1370     uprv_decNumberZero(res);                 /* prepare for Infinity  */
1371     res->bits=DECNEG|DECINF;            /* -Infinity  */
1372     status|=DEC_Division_by_zero;       /* as per 754  */
1373     }
1374    else { /* finite non-zero  */
1375     Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent  */
1376     uprv_decNumberFromInt32(res, ae);        /* lay it out  */
1377     }
1378 
1379   if (status!=0) decStatus(res, status, set);
1380   return res;
1381   } /* decNumberLogB  */
1382 
1383 /* ------------------------------------------------------------------ */
1384 /* decNumberLog10 -- logarithm in base 10                             */
1385 /*                                                                    */
1386 /*   This computes C = log10(A)                                       */
1387 /*                                                                    */
1388 /*   res is C, the result.  C may be A                                */
1389 /*   rhs is A                                                         */
1390 /*   set is the context; note that rounding mode has no effect        */
1391 /*                                                                    */
1392 /* C must have space for set->digits digits.                          */
1393 /*                                                                    */
1394 /* Notable cases:                                                     */
1395 /*   A<0 -> Invalid                                                   */
1396 /*   A=0 -> -Infinity (Exact)                                         */
1397 /*   A=+Infinity -> +Infinity (Exact)                                 */
1398 /*   A=10**n (if n is an integer) -> n (Exact)                        */
1399 /*                                                                    */
1400 /* Mathematical function restrictions apply (see above); a NaN is     */
1401 /* returned with Invalid_operation if a restriction is violated.      */
1402 /*                                                                    */
1403 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1404 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1405 /* error in rare cases.                                               */
1406 /* ------------------------------------------------------------------ */
1407 /* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1408 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1409 /* requested digits and t is the number of digits in the exponent     */
1410 /* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1411 /* fastpath in decLnOp.  The final division is done to the requested  */
1412 /* precision.                                                         */
1413 /* ------------------------------------------------------------------ */
1414 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
1415 #pragma GCC diagnostic push
1416 #pragma GCC diagnostic ignored "-Warray-bounds"
1417 #endif
uprv_decNumberLog10(decNumber * res,const decNumber * rhs,decContext * set)1418 U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1419                           decContext *set) {
1420   uInt status=0, ignore=0;         /* status accumulators  */
1421   uInt needbytes;                  /* for space calculations  */
1422   Int p;                           /* working precision  */
1423   Int t;                           /* digits in exponent of A  */
1424 
1425   /* buffers for a and b working decimals  */
1426   /* (adjustment calculator, same size)  */
1427   decNumber bufa[D2N(DECBUFFER+2)];
1428   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1429   decNumber *a=bufa;               /* temporary a  */
1430   decNumber bufb[D2N(DECBUFFER+2)];
1431   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
1432   decNumber *b=bufb;               /* temporary b  */
1433   decNumber bufw[D2N(10)];         /* working 2-10 digit number  */
1434   decNumber *w=bufw;               /* ..  */
1435   #if DECSUBSET
1436   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1437   #endif
1438 
1439   decContext aset;                 /* working context  */
1440 
1441   #if DECCHECK
1442   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1443   #endif
1444 
1445   /* Check restrictions; this is a math function; if not violated  */
1446   /* then carry out the operation.  */
1447   if (!decCheckMath(rhs, set, &status)) do { /* protect malloc  */
1448     #if DECSUBSET
1449     if (!set->extended) {
1450       /* reduce operand and set lostDigits status, as needed  */
1451       if (rhs->digits>set->digits) {
1452         allocrhs=decRoundOperand(rhs, set, &status);
1453         if (allocrhs==NULL) break;
1454         rhs=allocrhs;
1455         }
1456       /* special check in subset for rhs=0  */
1457       if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1458         status|=DEC_Invalid_operation;
1459         break;}
1460       } /* extended=0  */
1461     #endif
1462 
1463     uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
1464 
1465     /* handle exact powers of 10; only check if +ve finite  */
1466     if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1467       Int residue=0;               /* (no residue)  */
1468       uInt copystat=0;             /* clean status  */
1469 
1470       /* round to a single digit...  */
1471       aset.digits=1;
1472       decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten  */
1473       /* if exact and the digit is 1, rhs is a power of 10  */
1474       if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1475         /* the exponent, conveniently, is the power of 10; making  */
1476         /* this the result needs a little care as it might not fit,  */
1477         /* so first convert it into the working number, and then move  */
1478         /* to res  */
1479         uprv_decNumberFromInt32(w, w->exponent);
1480         residue=0;
1481         decCopyFit(res, w, set, &residue, &status); /* copy & round  */
1482         decFinish(res, set, &residue, &status);     /* cleanup/set flags  */
1483         break;
1484         } /* not a power of 10  */
1485       } /* not a candidate for exact  */
1486 
1487     /* simplify the information-content calculation to use 'total  */
1488     /* number of digits in a, including exponent' as compared to the  */
1489     /* requested digits, as increasing this will only rarely cost an  */
1490     /* iteration in ln(a) anyway  */
1491     t=6;                                /* it can never be >6  */
1492 
1493     /* allocate space when needed...  */
1494     p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1495     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1496     if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1497       allocbufa=(decNumber *)malloc(needbytes);
1498       if (allocbufa==NULL) {            /* hopeless -- abandon  */
1499         status|=DEC_Insufficient_storage;
1500         break;}
1501       a=allocbufa;                      /* use the allocated space  */
1502       }
1503     aset.digits=p;                      /* as calculated  */
1504     aset.emax=DEC_MAX_MATH;             /* usual bounds  */
1505     aset.emin=-DEC_MAX_MATH;            /* ..  */
1506     aset.clamp=0;                       /* and no concrete format  */
1507     decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs)  */
1508 
1509     /* skip the division if the result so far is infinite, NaN, or  */
1510     /* zero, or there was an error; note NaN from sNaN needs copy  */
1511     if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1512     if (a->bits&DECSPECIAL || ISZERO(a)) {
1513       uprv_decNumberCopy(res, a);            /* [will fit]  */
1514       break;}
1515 
1516     /* for ln(10) an extra 3 digits of precision are needed  */
1517     p=set->digits+3;
1518     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1519     if (needbytes>sizeof(bufb)) {       /* need malloc space  */
1520       allocbufb=(decNumber *)malloc(needbytes);
1521       if (allocbufb==NULL) {            /* hopeless -- abandon  */
1522         status|=DEC_Insufficient_storage;
1523         break;}
1524       b=allocbufb;                      /* use the allocated space  */
1525       }
1526     uprv_decNumberZero(w);                   /* set up 10...  */
1527     #if DECDPUN==1
1528     w->lsu[1]=1; w->lsu[0]=0;           /* ..  */
1529     #else
1530     w->lsu[0]=10;                       /* ..  */
1531     #endif
1532     w->digits=2;                        /* ..  */
1533 
1534     aset.digits=p;
1535     decLnOp(b, w, &aset, &ignore);      /* b=ln(10)  */
1536 
1537     aset.digits=set->digits;            /* for final divide  */
1538     decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result  */
1539     } while(0);                         /* [for break]  */
1540 
1541   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1542   if (allocbufb!=NULL) free(allocbufb); /* ..  */
1543   #if DECSUBSET
1544   if (allocrhs !=NULL) free(allocrhs);  /* ..  */
1545   #endif
1546   /* apply significant status  */
1547   if (status!=0) decStatus(res, status, set);
1548   #if DECCHECK
1549   decCheckInexact(res, set);
1550   #endif
1551   return res;
1552   } /* decNumberLog10  */
1553 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
1554 #pragma GCC diagnostic pop
1555 #endif
1556 
1557 /* ------------------------------------------------------------------ */
1558 /* decNumberMax -- compare two Numbers and return the maximum         */
1559 /*                                                                    */
1560 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1561 /*                                                                    */
1562 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1563 /*   lhs is A                                                         */
1564 /*   rhs is B                                                         */
1565 /*   set is the context                                               */
1566 /*                                                                    */
1567 /* C must have space for set->digits digits.                          */
1568 /* ------------------------------------------------------------------ */
uprv_decNumberMax(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1569 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1570                          const decNumber *rhs, decContext *set) {
1571   uInt status=0;                        /* accumulator  */
1572   decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1573   if (status!=0) decStatus(res, status, set);
1574   #if DECCHECK
1575   decCheckInexact(res, set);
1576   #endif
1577   return res;
1578   } /* decNumberMax  */
1579 
1580 /* ------------------------------------------------------------------ */
1581 /* decNumberMaxMag -- compare and return the maximum by magnitude     */
1582 /*                                                                    */
1583 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1584 /*                                                                    */
1585 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1586 /*   lhs is A                                                         */
1587 /*   rhs is B                                                         */
1588 /*   set is the context                                               */
1589 /*                                                                    */
1590 /* C must have space for set->digits digits.                          */
1591 /* ------------------------------------------------------------------ */
uprv_decNumberMaxMag(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1592 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1593                          const decNumber *rhs, decContext *set) {
1594   uInt status=0;                        /* accumulator  */
1595   decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1596   if (status!=0) decStatus(res, status, set);
1597   #if DECCHECK
1598   decCheckInexact(res, set);
1599   #endif
1600   return res;
1601   } /* decNumberMaxMag  */
1602 
1603 /* ------------------------------------------------------------------ */
1604 /* decNumberMin -- compare two Numbers and return the minimum         */
1605 /*                                                                    */
1606 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1607 /*                                                                    */
1608 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1609 /*   lhs is A                                                         */
1610 /*   rhs is B                                                         */
1611 /*   set is the context                                               */
1612 /*                                                                    */
1613 /* C must have space for set->digits digits.                          */
1614 /* ------------------------------------------------------------------ */
uprv_decNumberMin(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1615 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1616                          const decNumber *rhs, decContext *set) {
1617   uInt status=0;                        /* accumulator  */
1618   decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1619   if (status!=0) decStatus(res, status, set);
1620   #if DECCHECK
1621   decCheckInexact(res, set);
1622   #endif
1623   return res;
1624   } /* decNumberMin  */
1625 
1626 /* ------------------------------------------------------------------ */
1627 /* decNumberMinMag -- compare and return the minimum by magnitude     */
1628 /*                                                                    */
1629 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1630 /*                                                                    */
1631 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1632 /*   lhs is A                                                         */
1633 /*   rhs is B                                                         */
1634 /*   set is the context                                               */
1635 /*                                                                    */
1636 /* C must have space for set->digits digits.                          */
1637 /* ------------------------------------------------------------------ */
uprv_decNumberMinMag(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1638 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1639                          const decNumber *rhs, decContext *set) {
1640   uInt status=0;                        /* accumulator  */
1641   decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1642   if (status!=0) decStatus(res, status, set);
1643   #if DECCHECK
1644   decCheckInexact(res, set);
1645   #endif
1646   return res;
1647   } /* decNumberMinMag  */
1648 
1649 /* ------------------------------------------------------------------ */
1650 /* decNumberMinus -- prefix minus operator                            */
1651 /*                                                                    */
1652 /*   This computes C = 0 - A                                          */
1653 /*                                                                    */
1654 /*   res is C, the result.  C may be A                                */
1655 /*   rhs is A                                                         */
1656 /*   set is the context                                               */
1657 /*                                                                    */
1658 /* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1659 /* C must have space for set->digits digits.                          */
1660 /* ------------------------------------------------------------------ */
1661 /* Simply use AddOp for the subtract, which will do the necessary.    */
1662 /* ------------------------------------------------------------------ */
uprv_decNumberMinus(decNumber * res,const decNumber * rhs,decContext * set)1663 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1664                            decContext *set) {
1665   decNumber dzero;
1666   uInt status=0;                        /* accumulator  */
1667 
1668   #if DECCHECK
1669   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1670   #endif
1671 
1672   uprv_decNumberZero(&dzero);                /* make 0  */
1673   dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1674   decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1675   if (status!=0) decStatus(res, status, set);
1676   #if DECCHECK
1677   decCheckInexact(res, set);
1678   #endif
1679   return res;
1680   } /* decNumberMinus  */
1681 
1682 /* ------------------------------------------------------------------ */
1683 /* decNumberNextMinus -- next towards -Infinity                       */
1684 /*                                                                    */
1685 /*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1686 /*                                                                    */
1687 /*   res is C, the result.  C may be A                                */
1688 /*   rhs is A                                                         */
1689 /*   set is the context                                               */
1690 /*                                                                    */
1691 /* This is a generalization of 754 NextDown.                          */
1692 /* ------------------------------------------------------------------ */
uprv_decNumberNextMinus(decNumber * res,const decNumber * rhs,decContext * set)1693 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1694                                decContext *set) {
1695   decNumber dtiny;                           /* constant  */
1696   decContext workset=*set;                   /* work  */
1697   uInt status=0;                             /* accumulator  */
1698   #if DECCHECK
1699   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1700   #endif
1701 
1702   /* +Infinity is the special case  */
1703   if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1704     decSetMaxValue(res, set);                /* is +ve  */
1705     /* there is no status to set  */
1706     return res;
1707     }
1708   uprv_decNumberZero(&dtiny);                     /* start with 0  */
1709   dtiny.lsu[0]=1;                            /* make number that is ..  */
1710   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1711   workset.round=DEC_ROUND_FLOOR;
1712   decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1713   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1714   if (status!=0) decStatus(res, status, set);
1715   return res;
1716   } /* decNumberNextMinus  */
1717 
1718 /* ------------------------------------------------------------------ */
1719 /* decNumberNextPlus -- next towards +Infinity                        */
1720 /*                                                                    */
1721 /*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1722 /*                                                                    */
1723 /*   res is C, the result.  C may be A                                */
1724 /*   rhs is A                                                         */
1725 /*   set is the context                                               */
1726 /*                                                                    */
1727 /* This is a generalization of 754 NextUp.                            */
1728 /* ------------------------------------------------------------------ */
uprv_decNumberNextPlus(decNumber * res,const decNumber * rhs,decContext * set)1729 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1730                               decContext *set) {
1731   decNumber dtiny;                           /* constant  */
1732   decContext workset=*set;                   /* work  */
1733   uInt status=0;                             /* accumulator  */
1734   #if DECCHECK
1735   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1736   #endif
1737 
1738   /* -Infinity is the special case  */
1739   if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1740     decSetMaxValue(res, set);
1741     res->bits=DECNEG;                        /* negative  */
1742     /* there is no status to set  */
1743     return res;
1744     }
1745   uprv_decNumberZero(&dtiny);                     /* start with 0  */
1746   dtiny.lsu[0]=1;                            /* make number that is ..  */
1747   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1748   workset.round=DEC_ROUND_CEILING;
1749   decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1750   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1751   if (status!=0) decStatus(res, status, set);
1752   return res;
1753   } /* decNumberNextPlus  */
1754 
1755 /* ------------------------------------------------------------------ */
1756 /* decNumberNextToward -- next towards rhs                            */
1757 /*                                                                    */
1758 /*   This computes C = A +/- infinitesimal, rounded towards           */
1759 /*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1760 /*   modified during revision but dropped from 754-2008.              */
1761 /*                                                                    */
1762 /*   res is C, the result.  C may be A or B.                          */
1763 /*   lhs is A                                                         */
1764 /*   rhs is B                                                         */
1765 /*   set is the context                                               */
1766 /*                                                                    */
1767 /* This is a generalization of 754-1985 NextAfter.                    */
1768 /* ------------------------------------------------------------------ */
uprv_decNumberNextToward(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1769 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1770                                 const decNumber *rhs, decContext *set) {
1771   decNumber dtiny;                           /* constant  */
1772   decContext workset=*set;                   /* work  */
1773   Int result;                                /* ..  */
1774   uInt status=0;                             /* accumulator  */
1775   #if DECCHECK
1776   if (decCheckOperands(res, lhs, rhs, set)) return res;
1777   #endif
1778 
1779   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1780     decNaNs(res, lhs, rhs, set, &status);
1781     }
1782    else { /* Is numeric, so no chance of sNaN Invalid, etc.  */
1783     result=decCompare(lhs, rhs, 0);     /* sign matters  */
1784     if (result==BADINT) status|=DEC_Insufficient_storage; /* rare  */
1785      else { /* valid compare  */
1786       if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy  */
1787        else { /* differ: need NextPlus or NextMinus  */
1788         uByte sub;                      /* add or subtract  */
1789         if (result<0) {                 /* lhs<rhs, do nextplus  */
1790           /* -Infinity is the special case  */
1791           if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1792             decSetMaxValue(res, set);
1793             res->bits=DECNEG;           /* negative  */
1794             return res;                 /* there is no status to set  */
1795             }
1796           workset.round=DEC_ROUND_CEILING;
1797           sub=0;                        /* add, please  */
1798           } /* plus  */
1799          else {                         /* lhs>rhs, do nextminus  */
1800           /* +Infinity is the special case  */
1801           if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1802             decSetMaxValue(res, set);
1803             return res;                 /* there is no status to set  */
1804             }
1805           workset.round=DEC_ROUND_FLOOR;
1806           sub=DECNEG;                   /* subtract, please  */
1807           } /* minus  */
1808         uprv_decNumberZero(&dtiny);          /* start with 0  */
1809         dtiny.lsu[0]=1;                 /* make number that is ..  */
1810         dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest  */
1811         decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or -  */
1812         /* turn off exceptions if the result is a normal number  */
1813         /* (including Nmin), otherwise let all status through  */
1814         if (uprv_decNumberIsNormal(res, set)) status=0;
1815         } /* unequal  */
1816       } /* compare OK  */
1817     } /* numeric  */
1818   if (status!=0) decStatus(res, status, set);
1819   return res;
1820   } /* decNumberNextToward  */
1821 
1822 /* ------------------------------------------------------------------ */
1823 /* decNumberOr -- OR two Numbers, digitwise                           */
1824 /*                                                                    */
1825 /*   This computes C = A | B                                          */
1826 /*                                                                    */
1827 /*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1828 /*   lhs is A                                                         */
1829 /*   rhs is B                                                         */
1830 /*   set is the context (used for result length and error report)     */
1831 /*                                                                    */
1832 /* C must have space for set->digits digits.                          */
1833 /*                                                                    */
1834 /* Logical function restrictions apply (see above); a NaN is          */
1835 /* returned with Invalid_operation if a restriction is violated.      */
1836 /* ------------------------------------------------------------------ */
uprv_decNumberOr(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1837 U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1838                         const decNumber *rhs, decContext *set) {
1839   const Unit *ua, *ub;                  /* -> operands  */
1840   const Unit *msua, *msub;              /* -> operand msus  */
1841   Unit  *uc, *msuc;                     /* -> result and its msu  */
1842   Int   msudigs;                        /* digits in res msu  */
1843   #if DECCHECK
1844   if (decCheckOperands(res, lhs, rhs, set)) return res;
1845   #endif
1846 
1847   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1848    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1849     decStatus(res, DEC_Invalid_operation, set);
1850     return res;
1851     }
1852   /* operands are valid  */
1853   ua=lhs->lsu;                          /* bottom-up  */
1854   ub=rhs->lsu;                          /* ..  */
1855   uc=res->lsu;                          /* ..  */
1856   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
1857   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1858   msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1859   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1860   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
1861     Unit a, b;                          /* extract units  */
1862     if (ua>msua) a=0;
1863      else a=*ua;
1864     if (ub>msub) b=0;
1865      else b=*ub;
1866     *uc=0;                              /* can now write back  */
1867     if (a|b) {                          /* maybe 1 bits to examine  */
1868       Int i, j;
1869       /* This loop could be unrolled and/or use BIN2BCD tables  */
1870       for (i=0; i<DECDPUN; i++) {
1871         if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR  */
1872         j=a%10;
1873         a=a/10;
1874         j|=b%10;
1875         b=b/10;
1876         if (j>1) {
1877           decStatus(res, DEC_Invalid_operation, set);
1878           return res;
1879           }
1880         if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
1881         } /* each digit  */
1882       } /* non-zero  */
1883     } /* each unit  */
1884   /* [here uc-1 is the msu of the result]  */
1885   res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc-res->lsu));
1886   res->exponent=0;                      /* integer  */
1887   res->bits=0;                          /* sign=0  */
1888   return res;  /* [no status to set]  */
1889   } /* decNumberOr  */
1890 
1891 /* ------------------------------------------------------------------ */
1892 /* decNumberPlus -- prefix plus operator                              */
1893 /*                                                                    */
1894 /*   This computes C = 0 + A                                          */
1895 /*                                                                    */
1896 /*   res is C, the result.  C may be A                                */
1897 /*   rhs is A                                                         */
1898 /*   set is the context                                               */
1899 /*                                                                    */
1900 /* See also decNumberCopy for a quiet bitwise version of this.        */
1901 /* C must have space for set->digits digits.                          */
1902 /* ------------------------------------------------------------------ */
1903 /* This simply uses AddOp; Add will take fast path after preparing A. */
1904 /* Performance is a concern here, as this routine is often used to    */
1905 /* check operands and apply rounding and overflow/underflow testing.  */
1906 /* ------------------------------------------------------------------ */
uprv_decNumberPlus(decNumber * res,const decNumber * rhs,decContext * set)1907 U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1908                           decContext *set) {
1909   decNumber dzero;
1910   uInt status=0;                        /* accumulator  */
1911   #if DECCHECK
1912   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1913   #endif
1914 
1915   uprv_decNumberZero(&dzero);                /* make 0  */
1916   dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1917   decAddOp(res, &dzero, rhs, set, 0, &status);
1918   if (status!=0) decStatus(res, status, set);
1919   #if DECCHECK
1920   decCheckInexact(res, set);
1921   #endif
1922   return res;
1923   } /* decNumberPlus  */
1924 
1925 /* ------------------------------------------------------------------ */
1926 /* decNumberMultiply -- multiply two Numbers                          */
1927 /*                                                                    */
1928 /*   This computes C = A x B                                          */
1929 /*                                                                    */
1930 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1931 /*   lhs is A                                                         */
1932 /*   rhs is B                                                         */
1933 /*   set is the context                                               */
1934 /*                                                                    */
1935 /* C must have space for set->digits digits.                          */
1936 /* ------------------------------------------------------------------ */
uprv_decNumberMultiply(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1937 U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1938                               const decNumber *rhs, decContext *set) {
1939   uInt status=0;                   /* accumulator  */
1940   decMultiplyOp(res, lhs, rhs, set, &status);
1941   if (status!=0) decStatus(res, status, set);
1942   #if DECCHECK
1943   decCheckInexact(res, set);
1944   #endif
1945   return res;
1946   } /* decNumberMultiply  */
1947 
1948 /* ------------------------------------------------------------------ */
1949 /* decNumberPower -- raise a number to a power                        */
1950 /*                                                                    */
1951 /*   This computes C = A ** B                                         */
1952 /*                                                                    */
1953 /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1954 /*   lhs is A                                                         */
1955 /*   rhs is B                                                         */
1956 /*   set is the context                                               */
1957 /*                                                                    */
1958 /* C must have space for set->digits digits.                          */
1959 /*                                                                    */
1960 /* Mathematical function restrictions apply (see above); a NaN is     */
1961 /* returned with Invalid_operation if a restriction is violated.      */
1962 /*                                                                    */
1963 /* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1964 /* restrictions on A and the context are relaxed to the usual bounds, */
1965 /* for compatibility with the earlier (integer power only) version    */
1966 /* of this function.                                                  */
1967 /*                                                                    */
1968 /* When B is an integer, the result may be exact, even if rounded.    */
1969 /*                                                                    */
1970 /* The final result is rounded according to the context; it will      */
1971 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1972 /* error in rare cases.                                               */
1973 /* ------------------------------------------------------------------ */
uprv_decNumberPower(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1974 U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1975                            const decNumber *rhs, decContext *set) {
1976   #if DECSUBSET
1977   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
1978   decNumber *allocrhs=NULL;        /* .., rhs  */
1979   #endif
1980   decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used  */
1981   decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used  */
1982   Int   reqdigits=set->digits;     /* requested DIGITS  */
1983   Int   n;                         /* rhs in binary  */
1984   Flag  rhsint=0;                  /* 1 if rhs is an integer  */
1985   Flag  useint=0;                  /* 1 if can use integer calculation  */
1986   Flag  isoddint=0;                /* 1 if rhs is an integer and odd  */
1987   Int   i;                         /* work  */
1988   #if DECSUBSET
1989   Int   dropped;                   /* ..  */
1990   #endif
1991   uInt  needbytes;                 /* buffer size needed  */
1992   Flag  seenbit;                   /* seen a bit while powering  */
1993   Int   residue=0;                 /* rounding residue  */
1994   uInt  status=0;                  /* accumulators  */
1995   uByte bits=0;                    /* result sign if errors  */
1996   decContext aset;                 /* working context  */
1997   decNumber dnOne;                 /* work value 1...  */
1998   /* local accumulator buffer [a decNumber, with digits+elength+1 digits]  */
1999   decNumber dacbuff[D2N(DECBUFFER+9)];
2000   decNumber *dac=dacbuff;          /* -> result accumulator  */
2001   /* same again for possible 1/lhs calculation  */
2002   decNumber invbuff[D2N(DECBUFFER+9)];
2003 
2004   #if DECCHECK
2005   if (decCheckOperands(res, lhs, rhs, set)) return res;
2006   #endif
2007 
2008   do {                             /* protect allocated storage  */
2009     #if DECSUBSET
2010     if (!set->extended) { /* reduce operands and set status, as needed  */
2011       if (lhs->digits>reqdigits) {
2012         alloclhs=decRoundOperand(lhs, set, &status);
2013         if (alloclhs==NULL) break;
2014         lhs=alloclhs;
2015         }
2016       if (rhs->digits>reqdigits) {
2017         allocrhs=decRoundOperand(rhs, set, &status);
2018         if (allocrhs==NULL) break;
2019         rhs=allocrhs;
2020         }
2021       }
2022     #endif
2023     /* [following code does not require input rounding]  */
2024 
2025     /* handle NaNs and rhs Infinity (lhs infinity is harder)  */
2026     if (SPECIALARGS) {
2027       if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs  */
2028         decNaNs(res, lhs, rhs, set, &status);
2029         break;}
2030       if (decNumberIsInfinite(rhs)) {   /* rhs Infinity  */
2031         Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign  */
2032         if (decNumberIsNegative(lhs)    /* lhs<0  */
2033          && !decNumberIsZero(lhs))      /* ..  */
2034           status|=DEC_Invalid_operation;
2035          else {                         /* lhs >=0  */
2036           uprv_decNumberZero(&dnOne);        /* set up 1  */
2037           dnOne.lsu[0]=1;
2038           uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1  */
2039           uprv_decNumberZero(res);           /* prepare for 0/1/Infinity  */
2040           if (decNumberIsNegative(dac)) {    /* lhs<1  */
2041             if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0]  */
2042             }
2043            else if (dac->lsu[0]==0) {        /* lhs=1  */
2044             /* 1**Infinity is inexact, so return fully-padded 1.0000  */
2045             Int shift=set->digits-1;
2046             *res->lsu=1;                     /* was 0, make int 1  */
2047             res->digits=decShiftToMost(res->lsu, 1, shift);
2048             res->exponent=-shift;            /* make 1.0000...  */
2049             status|=DEC_Inexact|DEC_Rounded; /* deemed inexact  */
2050             }
2051            else {                            /* lhs>1  */
2052             if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0]  */
2053             }
2054           } /* lhs>=0  */
2055         break;}
2056       /* [lhs infinity drops through]  */
2057       } /* specials  */
2058 
2059     /* Original rhs may be an integer that fits and is in range  */
2060     n=decGetInt(rhs);
2061     if (n!=BADINT) {                    /* it is an integer  */
2062       rhsint=1;                         /* record the fact for 1**n  */
2063       isoddint=(Flag)n&1;               /* [works even if big]  */
2064       if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path?  */
2065         useint=1;                       /* looks good  */
2066       }
2067 
2068     if (decNumberIsNegative(lhs)        /* -x ..  */
2069       && isoddint) bits=DECNEG;         /* .. to an odd power  */
2070 
2071     /* handle LHS infinity  */
2072     if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled]  */
2073       uByte rbits=rhs->bits;            /* save  */
2074       uprv_decNumberZero(res);               /* prepare  */
2075       if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1  */
2076        else {
2077         /* -Inf**nonint -> error  */
2078         if (!rhsint && decNumberIsNegative(lhs)) {
2079           status|=DEC_Invalid_operation;     /* -Inf**nonint is error  */
2080           break;}
2081         if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n  */
2082         /* [otherwise will be 0 or -0]  */
2083         res->bits=bits;
2084         }
2085       break;}
2086 
2087     /* similarly handle LHS zero  */
2088     if (decNumberIsZero(lhs)) {
2089       if (n==0) {                            /* 0**0 => Error  */
2090         #if DECSUBSET
2091         if (!set->extended) {                /* [unless subset]  */
2092           uprv_decNumberZero(res);
2093           *res->lsu=1;                       /* return 1  */
2094           break;}
2095         #endif
2096         status|=DEC_Invalid_operation;
2097         }
2098        else {                                /* 0**x  */
2099         uByte rbits=rhs->bits;               /* save  */
2100         if (rbits & DECNEG) {                /* was a 0**(-n)  */
2101           #if DECSUBSET
2102           if (!set->extended) {              /* [bad if subset]  */
2103             status|=DEC_Invalid_operation;
2104             break;}
2105           #endif
2106           bits|=DECINF;
2107           }
2108         uprv_decNumberZero(res);                  /* prepare  */
2109         /* [otherwise will be 0 or -0]  */
2110         res->bits=bits;
2111         }
2112       break;}
2113 
2114     /* here both lhs and rhs are finite; rhs==0 is handled in the  */
2115     /* integer path.  Next handle the non-integer cases  */
2116     if (!useint) {                      /* non-integral rhs  */
2117       /* any -ve lhs is bad, as is either operand or context out of  */
2118       /* bounds  */
2119       if (decNumberIsNegative(lhs)) {
2120         status|=DEC_Invalid_operation;
2121         break;}
2122       if (decCheckMath(lhs, set, &status)
2123        || decCheckMath(rhs, set, &status)) break; /* variable status  */
2124 
2125       uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
2126       aset.emax=DEC_MAX_MATH;           /* usual bounds  */
2127       aset.emin=-DEC_MAX_MATH;          /* ..  */
2128       aset.clamp=0;                     /* and no concrete format  */
2129 
2130       /* calculate the result using exp(ln(lhs)*rhs), which can  */
2131       /* all be done into the accumulator, dac.  The precision needed  */
2132       /* is enough to contain the full information in the lhs (which  */
2133       /* is the total digits, including exponent), or the requested  */
2134       /* precision, if larger, + 4; 6 is used for the exponent  */
2135       /* maximum length, and this is also used when it is shorter  */
2136       /* than the requested digits as it greatly reduces the >0.5 ulp  */
2137       /* cases at little cost (because Ln doubles digits each  */
2138       /* iteration so a few extra digits rarely causes an extra  */
2139       /* iteration)  */
2140       aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2141       } /* non-integer rhs  */
2142 
2143      else { /* rhs is in-range integer  */
2144       if (n==0) {                       /* x**0 = 1  */
2145         /* (0**0 was handled above)  */
2146         uprv_decNumberZero(res);             /* result=1  */
2147         *res->lsu=1;                    /* ..  */
2148         break;}
2149       /* rhs is a non-zero integer  */
2150       if (n<0) n=-n;                    /* use abs(n)  */
2151 
2152       aset=*set;                        /* clone the context  */
2153       aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced  */
2154       /* calculate the working DIGITS  */
2155       aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2156       #if DECSUBSET
2157       if (!set->extended) aset.digits--;     /* use classic precision  */
2158       #endif
2159       /* it's an error if this is more than can be handled  */
2160       if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2161       } /* integer path  */
2162 
2163     /* aset.digits is the count of digits for the accumulator needed  */
2164     /* if accumulator is too long for local storage, then allocate  */
2165     needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2166     /* [needbytes also used below if 1/lhs needed]  */
2167     if (needbytes>sizeof(dacbuff)) {
2168       allocdac=(decNumber *)malloc(needbytes);
2169       if (allocdac==NULL) {   /* hopeless -- abandon  */
2170         status|=DEC_Insufficient_storage;
2171         break;}
2172       dac=allocdac;           /* use the allocated space  */
2173       }
2174     /* here, aset is set up and accumulator is ready for use  */
2175 
2176     if (!useint) {                           /* non-integral rhs  */
2177       /* x ** y; special-case x=1 here as it will otherwise always  */
2178       /* reduce to integer 1; decLnOp has a fastpath which detects  */
2179       /* the case of x=1  */
2180       decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs)  */
2181       /* [no error possible, as lhs 0 already handled]  */
2182       if (ISZERO(dac)) {                     /* x==1, 1.0, etc.  */
2183         /* need to return fully-padded 1.0000 etc., but rhsint->1  */
2184         *dac->lsu=1;                         /* was 0, make int 1  */
2185         if (!rhsint) {                       /* add padding  */
2186           Int shift=set->digits-1;
2187           dac->digits=decShiftToMost(dac->lsu, 1, shift);
2188           dac->exponent=-shift;              /* make 1.0000...  */
2189           status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact  */
2190           }
2191         }
2192        else {
2193         decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs  */
2194         decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac)  */
2195         }
2196       /* and drop through for final rounding  */
2197       } /* non-integer rhs  */
2198 
2199      else {                             /* carry on with integer  */
2200       uprv_decNumberZero(dac);               /* acc=1  */
2201       *dac->lsu=1;                      /* ..  */
2202 
2203       /* if a negative power the constant 1 is needed, and if not subset  */
2204       /* invert the lhs now rather than inverting the result later  */
2205       if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0]  */
2206         decNumber *inv=invbuff;         /* asssume use fixed buffer  */
2207         uprv_decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later]  */
2208         #if DECSUBSET
2209         if (set->extended) {            /* need to calculate 1/lhs  */
2210         #endif
2211           /* divide lhs into 1, putting result in dac [dac=1/dac]  */
2212           decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2213           /* now locate or allocate space for the inverted lhs  */
2214           if (needbytes>sizeof(invbuff)) {
2215             allocinv=(decNumber *)malloc(needbytes);
2216             if (allocinv==NULL) {       /* hopeless -- abandon  */
2217               status|=DEC_Insufficient_storage;
2218               break;}
2219             inv=allocinv;               /* use the allocated space  */
2220             }
2221           /* [inv now points to big-enough buffer or allocated storage]  */
2222           uprv_decNumberCopy(inv, dac);      /* copy the 1/lhs  */
2223           uprv_decNumberCopy(dac, &dnOne);   /* restore acc=1  */
2224           lhs=inv;                      /* .. and go forward with new lhs  */
2225         #if DECSUBSET
2226           }
2227         #endif
2228         }
2229 
2230       /* Raise-to-the-power loop...  */
2231       seenbit=0;                   /* set once a 1-bit is encountered  */
2232       for (i=1;;i++){              /* for each bit [top bit ignored]  */
2233         /* abandon if had overflow or terminal underflow  */
2234         if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
2235           if (status&DEC_Overflow || ISZERO(dac)) break;
2236           }
2237         /* [the following two lines revealed an optimizer bug in a C++  */
2238         /* compiler, with symptom: 5**3 -> 25, when n=n+n was used]  */
2239         n=n<<1;                    /* move next bit to testable position  */
2240         if (n<0) {                 /* top bit is set  */
2241           seenbit=1;               /* OK, significant bit seen  */
2242           decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x  */
2243           }
2244         if (i==31) break;          /* that was the last bit  */
2245         if (!seenbit) continue;    /* no need to square 1  */
2246         decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square]  */
2247         } /*i*/ /* 32 bits  */
2248 
2249       /* complete internal overflow or underflow processing  */
2250       if (status & (DEC_Overflow|DEC_Underflow)) {
2251         #if DECSUBSET
2252         /* If subset, and power was negative, reverse the kind of -erflow  */
2253         /* [1/x not yet done]  */
2254         if (!set->extended && decNumberIsNegative(rhs)) {
2255           if (status & DEC_Overflow)
2256             status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2257            else { /* trickier -- Underflow may or may not be set  */
2258             status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both]  */
2259             status|=DEC_Overflow;
2260             }
2261           }
2262         #endif
2263         dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign  */
2264         /* round subnormals [to set.digits rather than aset.digits]  */
2265         /* or set overflow result similarly as required  */
2266         decFinalize(dac, set, &residue, &status);
2267         uprv_decNumberCopy(res, dac);   /* copy to result (is now OK length)  */
2268         break;
2269         }
2270 
2271       #if DECSUBSET
2272       if (!set->extended &&                  /* subset math  */
2273           decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0]  */
2274         /* so divide result into 1 [dac=1/dac]  */
2275         decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2276         }
2277       #endif
2278       } /* rhs integer path  */
2279 
2280     /* reduce result to the requested length and copy to result  */
2281     decCopyFit(res, dac, set, &residue, &status);
2282     decFinish(res, set, &residue, &status);  /* final cleanup  */
2283     #if DECSUBSET
2284     if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros  */
2285     #endif
2286     } while(0);                         /* end protected  */
2287 
2288   if (allocdac!=NULL) free(allocdac);   /* drop any storage used  */
2289   if (allocinv!=NULL) free(allocinv);   /* ..  */
2290   #if DECSUBSET
2291   if (alloclhs!=NULL) free(alloclhs);   /* ..  */
2292   if (allocrhs!=NULL) free(allocrhs);   /* ..  */
2293   #endif
2294   if (status!=0) decStatus(res, status, set);
2295   #if DECCHECK
2296   decCheckInexact(res, set);
2297   #endif
2298   return res;
2299   } /* decNumberPower  */
2300 
2301 /* ------------------------------------------------------------------ */
2302 /* decNumberQuantize -- force exponent to requested value             */
2303 /*                                                                    */
2304 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2305 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2306 /*   of C has exponent of B.  The numerical value of C will equal A,  */
2307 /*   except for the effects of any rounding that occurred.            */
2308 /*                                                                    */
2309 /*   res is C, the result.  C may be A or B                           */
2310 /*   lhs is A, the number to adjust                                   */
2311 /*   rhs is B, the number with exponent to match                      */
2312 /*   set is the context                                               */
2313 /*                                                                    */
2314 /* C must have space for set->digits digits.                          */
2315 /*                                                                    */
2316 /* Unless there is an error or the result is infinite, the exponent   */
2317 /* after the operation is guaranteed to be equal to that of B.        */
2318 /* ------------------------------------------------------------------ */
uprv_decNumberQuantize(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2319 U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2320                               const decNumber *rhs, decContext *set) {
2321   uInt status=0;                        /* accumulator  */
2322   decQuantizeOp(res, lhs, rhs, set, 1, &status);
2323   if (status!=0) decStatus(res, status, set);
2324   return res;
2325   } /* decNumberQuantize  */
2326 
2327 /* ------------------------------------------------------------------ */
2328 /* decNumberReduce -- remove trailing zeros                           */
2329 /*                                                                    */
2330 /*   This computes C = 0 + A, and normalizes the result               */
2331 /*                                                                    */
2332 /*   res is C, the result.  C may be A                                */
2333 /*   rhs is A                                                         */
2334 /*   set is the context                                               */
2335 /*                                                                    */
2336 /* C must have space for set->digits digits.                          */
2337 /* ------------------------------------------------------------------ */
2338 /* Previously known as Normalize  */
uprv_decNumberNormalize(decNumber * res,const decNumber * rhs,decContext * set)2339 U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2340                                decContext *set) {
2341   return uprv_decNumberReduce(res, rhs, set);
2342   } /* decNumberNormalize  */
2343 
uprv_decNumberReduce(decNumber * res,const decNumber * rhs,decContext * set)2344 U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2345                             decContext *set) {
2346   #if DECSUBSET
2347   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2348   #endif
2349   uInt status=0;                   /* as usual  */
2350   Int  residue=0;                  /* as usual  */
2351   Int  dropped;                    /* work  */
2352 
2353   #if DECCHECK
2354   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2355   #endif
2356 
2357   do {                             /* protect allocated storage  */
2358     #if DECSUBSET
2359     if (!set->extended) {
2360       /* reduce operand and set lostDigits status, as needed  */
2361       if (rhs->digits>set->digits) {
2362         allocrhs=decRoundOperand(rhs, set, &status);
2363         if (allocrhs==NULL) break;
2364         rhs=allocrhs;
2365         }
2366       }
2367     #endif
2368     /* [following code does not require input rounding]  */
2369 
2370     /* Infinities copy through; NaNs need usual treatment  */
2371     if (decNumberIsNaN(rhs)) {
2372       decNaNs(res, rhs, NULL, set, &status);
2373       break;
2374       }
2375 
2376     /* reduce result to the requested length and copy to result  */
2377     decCopyFit(res, rhs, set, &residue, &status); /* copy & round  */
2378     decFinish(res, set, &residue, &status);       /* cleanup/set flags  */
2379     decTrim(res, set, 1, 0, &dropped);            /* normalize in place  */
2380                                                   /* [may clamp]  */
2381     } while(0);                              /* end protected  */
2382 
2383   #if DECSUBSET
2384   if (allocrhs !=NULL) free(allocrhs);       /* ..  */
2385   #endif
2386   if (status!=0) decStatus(res, status, set);/* then report status  */
2387   return res;
2388   } /* decNumberReduce  */
2389 
2390 /* ------------------------------------------------------------------ */
2391 /* decNumberRescale -- force exponent to requested value              */
2392 /*                                                                    */
2393 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2394 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2395 /*   of C has the value B.  The numerical value of C will equal A,    */
2396 /*   except for the effects of any rounding that occurred.            */
2397 /*                                                                    */
2398 /*   res is C, the result.  C may be A or B                           */
2399 /*   lhs is A, the number to adjust                                   */
2400 /*   rhs is B, the requested exponent                                 */
2401 /*   set is the context                                               */
2402 /*                                                                    */
2403 /* C must have space for set->digits digits.                          */
2404 /*                                                                    */
2405 /* Unless there is an error or the result is infinite, the exponent   */
2406 /* after the operation is guaranteed to be equal to B.                */
2407 /* ------------------------------------------------------------------ */
uprv_decNumberRescale(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2408 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2409                              const decNumber *rhs, decContext *set) {
2410   uInt status=0;                        /* accumulator  */
2411   decQuantizeOp(res, lhs, rhs, set, 0, &status);
2412   if (status!=0) decStatus(res, status, set);
2413   return res;
2414   } /* decNumberRescale  */
2415 
2416 /* ------------------------------------------------------------------ */
2417 /* decNumberRemainder -- divide and return remainder                  */
2418 /*                                                                    */
2419 /*   This computes C = A % B                                          */
2420 /*                                                                    */
2421 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2422 /*   lhs is A                                                         */
2423 /*   rhs is B                                                         */
2424 /*   set is the context                                               */
2425 /*                                                                    */
2426 /* C must have space for set->digits digits.                          */
2427 /* ------------------------------------------------------------------ */
uprv_decNumberRemainder(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2428 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2429                                const decNumber *rhs, decContext *set) {
2430   uInt status=0;                        /* accumulator  */
2431   decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2432   if (status!=0) decStatus(res, status, set);
2433   #if DECCHECK
2434   decCheckInexact(res, set);
2435   #endif
2436   return res;
2437   } /* decNumberRemainder  */
2438 
2439 /* ------------------------------------------------------------------ */
2440 /* decNumberRemainderNear -- divide and return remainder from nearest */
2441 /*                                                                    */
2442 /*   This computes C = A % B, where % is the IEEE remainder operator  */
2443 /*                                                                    */
2444 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2445 /*   lhs is A                                                         */
2446 /*   rhs is B                                                         */
2447 /*   set is the context                                               */
2448 /*                                                                    */
2449 /* C must have space for set->digits digits.                          */
2450 /* ------------------------------------------------------------------ */
uprv_decNumberRemainderNear(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2451 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2452                                    const decNumber *rhs, decContext *set) {
2453   uInt status=0;                        /* accumulator  */
2454   decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2455   if (status!=0) decStatus(res, status, set);
2456   #if DECCHECK
2457   decCheckInexact(res, set);
2458   #endif
2459   return res;
2460   } /* decNumberRemainderNear  */
2461 
2462 /* ------------------------------------------------------------------ */
2463 /* decNumberRotate -- rotate the coefficient of a Number left/right   */
2464 /*                                                                    */
2465 /*   This computes C = A rot B  (in base ten and rotating set->digits */
2466 /*   digits).                                                         */
2467 /*                                                                    */
2468 /*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2469 /*   lhs is A                                                         */
2470 /*   rhs is B, the number of digits to rotate (-ve to right)          */
2471 /*   set is the context                                               */
2472 /*                                                                    */
2473 /* The digits of the coefficient of A are rotated to the left (if B   */
2474 /* is positive) or to the right (if B is negative) without adjusting  */
2475 /* the exponent or the sign of A.  If lhs->digits is less than        */
2476 /* set->digits the coefficient is padded with zeros on the left       */
2477 /* before the rotate.  Any leading zeros in the result are removed    */
2478 /* as usual.                                                          */
2479 /*                                                                    */
2480 /* B must be an integer (q=0) and in the range -set->digits through   */
2481 /* +set->digits.                                                      */
2482 /* C must have space for set->digits digits.                          */
2483 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2484 /* B must be valid).  No status is set unless B is invalid or an      */
2485 /* operand is an sNaN.                                                */
2486 /* ------------------------------------------------------------------ */
uprv_decNumberRotate(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2487 U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2488                            const decNumber *rhs, decContext *set) {
2489   uInt status=0;              /* accumulator  */
2490   Int  rotate;                /* rhs as an Int  */
2491 
2492   #if DECCHECK
2493   if (decCheckOperands(res, lhs, rhs, set)) return res;
2494   #endif
2495 
2496   /* NaNs propagate as normal  */
2497   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2498     decNaNs(res, lhs, rhs, set, &status);
2499    /* rhs must be an integer  */
2500    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2501     status=DEC_Invalid_operation;
2502    else { /* both numeric, rhs is an integer  */
2503     rotate=decGetInt(rhs);                   /* [cannot fail]  */
2504     if (rotate==BADINT                       /* something bad ..  */
2505      || rotate==BIGODD || rotate==BIGEVEN    /* .. very big ..  */
2506      || abs(rotate)>set->digits)             /* .. or out of range  */
2507       status=DEC_Invalid_operation;
2508      else {                                  /* rhs is OK  */
2509       uprv_decNumberCopy(res, lhs);
2510       /* convert -ve rotate to equivalent positive rotation  */
2511       if (rotate<0) rotate=set->digits+rotate;
2512       if (rotate!=0 && rotate!=set->digits   /* zero or full rotation  */
2513        && !decNumberIsInfinite(res)) {       /* lhs was infinite  */
2514         /* left-rotate to do; 0 < rotate < set->digits  */
2515         uInt units, shift;                   /* work  */
2516         uInt msudigits;                      /* digits in result msu  */
2517         Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu  */
2518         Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu  */
2519         for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0  */
2520         res->digits=set->digits;                  /* now full-length  */
2521         msudigits=MSUDIGITS(res->digits);         /* actual digits in msu  */
2522 
2523         /* rotation here is done in-place, in three steps  */
2524         /* 1. shift all to least up to one unit to unit-align final  */
2525         /*    lsd [any digits shifted out are rotated to the left,  */
2526         /*    abutted to the original msd (which may require split)]  */
2527         /*  */
2528         /*    [if there are no whole units left to rotate, the  */
2529         /*    rotation is now complete]  */
2530         /*  */
2531         /* 2. shift to least, from below the split point only, so that  */
2532         /*    the final msd is in the right place in its Unit [any  */
2533         /*    digits shifted out will fit exactly in the current msu,  */
2534         /*    left aligned, no split required]  */
2535         /*  */
2536         /* 3. rotate all the units by reversing left part, right  */
2537         /*    part, and then whole  */
2538         /*  */
2539         /* example: rotate right 8 digits (2 units + 2), DECDPUN=3.  */
2540         /*  */
2541         /*   start: 00a bcd efg hij klm npq  */
2542         /*  */
2543         /*      1a  000 0ab cde fgh|ijk lmn [pq saved]  */
2544         /*      1b  00p qab cde fgh|ijk lmn  */
2545         /*  */
2546         /*      2a  00p qab cde fgh|00i jkl [mn saved]  */
2547         /*      2b  mnp qab cde fgh|00i jkl  */
2548         /*  */
2549         /*      3a  fgh cde qab mnp|00i jkl  */
2550         /*      3b  fgh cde qab mnp|jkl 00i  */
2551         /*      3c  00i jkl mnp qab cde fgh  */
2552 
2553         /* Step 1: amount to shift is the partial right-rotate count  */
2554         rotate=set->digits-rotate;      /* make it right-rotate  */
2555         units=rotate/DECDPUN;           /* whole units to rotate  */
2556         shift=rotate%DECDPUN;           /* left-over digits count  */
2557         if (shift>0) {                  /* not an exact number of units  */
2558           uInt save=res->lsu[0]%powers[shift];    /* save low digit(s)  */
2559           decShiftToLeast(res->lsu, D2U(res->digits), shift);
2560           if (shift>msudigits) {        /* msumax-1 needs >0 digits  */
2561             uInt rem=save%powers[shift-msudigits];/* split save  */
2562             *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert  */
2563             *(msumax-1)=*(msumax-1)
2564                        +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* ..  */
2565             }
2566            else { /* all fits in msumax  */
2567             *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1]  */
2568             }
2569           } /* digits shift needed  */
2570 
2571         /* If whole units to rotate...  */
2572         if (units>0) {                  /* some to do  */
2573           /* Step 2: the units to touch are the whole ones in rotate,  */
2574           /*   if any, and the shift is DECDPUN-msudigits (which may be  */
2575           /*   0, again)  */
2576           shift=DECDPUN-msudigits;
2577           if (shift>0) {                /* not an exact number of units  */
2578             uInt save=res->lsu[0]%powers[shift];  /* save low digit(s)  */
2579             decShiftToLeast(res->lsu, units, shift);
2580             *msumax=*msumax+(Unit)(save*powers[msudigits]);
2581             } /* partial shift needed  */
2582 
2583           /* Step 3: rotate the units array using triple reverse  */
2584           /* (reversing is easy and fast)  */
2585           decReverse(res->lsu+units, msumax);     /* left part  */
2586           decReverse(res->lsu, res->lsu+units-1); /* right part  */
2587           decReverse(res->lsu, msumax);           /* whole  */
2588           } /* whole units to rotate  */
2589         /* the rotation may have left an undetermined number of zeros  */
2590         /* on the left, so true length needs to be calculated  */
2591         res->digits=decGetDigits(res->lsu, static_cast<int32_t>(msumax-res->lsu+1));
2592         } /* rotate needed  */
2593       } /* rhs OK  */
2594     } /* numerics  */
2595   if (status!=0) decStatus(res, status, set);
2596   return res;
2597   } /* decNumberRotate  */
2598 
2599 /* ------------------------------------------------------------------ */
2600 /* decNumberSameQuantum -- test for equal exponents                   */
2601 /*                                                                    */
2602 /*   res is the result number, which will contain either 0 or 1       */
2603 /*   lhs is a number to test                                          */
2604 /*   rhs is the second (usually a pattern)                            */
2605 /*                                                                    */
2606 /* No errors are possible and no context is needed.                   */
2607 /* ------------------------------------------------------------------ */
uprv_decNumberSameQuantum(decNumber * res,const decNumber * lhs,const decNumber * rhs)2608 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2609                                  const decNumber *rhs) {
2610   Unit ret=0;                      /* return value  */
2611 
2612   #if DECCHECK
2613   if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2614   #endif
2615 
2616   if (SPECIALARGS) {
2617     if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2618      else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2619      /* [anything else with a special gives 0]  */
2620     }
2621    else if (lhs->exponent==rhs->exponent) ret=1;
2622 
2623   uprv_decNumberZero(res);              /* OK to overwrite an operand now  */
2624   *res->lsu=ret;
2625   return res;
2626   } /* decNumberSameQuantum  */
2627 
2628 /* ------------------------------------------------------------------ */
2629 /* decNumberScaleB -- multiply by a power of 10                       */
2630 /*                                                                    */
2631 /* This computes C = A x 10**B where B is an integer (q=0) with       */
2632 /* maximum magnitude 2*(emax+digits)                                  */
2633 /*                                                                    */
2634 /*   res is C, the result.  C may be A or B                           */
2635 /*   lhs is A, the number to adjust                                   */
2636 /*   rhs is B, the requested power of ten to use                      */
2637 /*   set is the context                                               */
2638 /*                                                                    */
2639 /* C must have space for set->digits digits.                          */
2640 /*                                                                    */
2641 /* The result may underflow or overflow.                              */
2642 /* ------------------------------------------------------------------ */
uprv_decNumberScaleB(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2643 U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2644                             const decNumber *rhs, decContext *set) {
2645   Int  reqexp;                /* requested exponent change [B]  */
2646   uInt status=0;              /* accumulator  */
2647   Int  residue;               /* work  */
2648 
2649   #if DECCHECK
2650   if (decCheckOperands(res, lhs, rhs, set)) return res;
2651   #endif
2652 
2653   /* Handle special values except lhs infinite  */
2654   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2655     decNaNs(res, lhs, rhs, set, &status);
2656     /* rhs must be an integer  */
2657    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2658     status=DEC_Invalid_operation;
2659    else {
2660     /* lhs is a number; rhs is a finite with q==0  */
2661     reqexp=decGetInt(rhs);                   /* [cannot fail]  */
2662     if (reqexp==BADINT                       /* something bad ..  */
2663      || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big ..  */
2664      || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range  */
2665       status=DEC_Invalid_operation;
2666      else {                                  /* rhs is OK  */
2667       uprv_decNumberCopy(res, lhs);               /* all done if infinite lhs  */
2668       if (!decNumberIsInfinite(res)) {       /* prepare to scale  */
2669         res->exponent+=reqexp;               /* adjust the exponent  */
2670         residue=0;
2671         decFinalize(res, set, &residue, &status); /* .. and check  */
2672         } /* finite LHS  */
2673       } /* rhs OK  */
2674     } /* rhs finite  */
2675   if (status!=0) decStatus(res, status, set);
2676   return res;
2677   } /* decNumberScaleB  */
2678 
2679 /* ------------------------------------------------------------------ */
2680 /* decNumberShift -- shift the coefficient of a Number left or right  */
2681 /*                                                                    */
2682 /*   This computes C = A << B or C = A >> -B  (in base ten).          */
2683 /*                                                                    */
2684 /*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2685 /*   lhs is A                                                         */
2686 /*   rhs is B, the number of digits to shift (-ve to right)           */
2687 /*   set is the context                                               */
2688 /*                                                                    */
2689 /* The digits of the coefficient of A are shifted to the left (if B   */
2690 /* is positive) or to the right (if B is negative) without adjusting  */
2691 /* the exponent or the sign of A.                                     */
2692 /*                                                                    */
2693 /* B must be an integer (q=0) and in the range -set->digits through   */
2694 /* +set->digits.                                                      */
2695 /* C must have space for set->digits digits.                          */
2696 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2697 /* B must be valid).  No status is set unless B is invalid or an      */
2698 /* operand is an sNaN.                                                */
2699 /* ------------------------------------------------------------------ */
uprv_decNumberShift(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)2700 U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2701                            const decNumber *rhs, decContext *set) {
2702   uInt status=0;              /* accumulator  */
2703   Int  shift;                 /* rhs as an Int  */
2704 
2705   #if DECCHECK
2706   if (decCheckOperands(res, lhs, rhs, set)) return res;
2707   #endif
2708 
2709   /* NaNs propagate as normal  */
2710   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2711     decNaNs(res, lhs, rhs, set, &status);
2712    /* rhs must be an integer  */
2713    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2714     status=DEC_Invalid_operation;
2715    else { /* both numeric, rhs is an integer  */
2716     shift=decGetInt(rhs);                    /* [cannot fail]  */
2717     if (shift==BADINT                        /* something bad ..  */
2718      || shift==BIGODD || shift==BIGEVEN      /* .. very big ..  */
2719      || abs(shift)>set->digits)              /* .. or out of range  */
2720       status=DEC_Invalid_operation;
2721      else {                                  /* rhs is OK  */
2722       uprv_decNumberCopy(res, lhs);
2723       if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do  */
2724         if (shift>0) {                       /* to left  */
2725           if (shift==set->digits) {          /* removing all  */
2726             *res->lsu=0;                     /* so place 0  */
2727             res->digits=1;                   /* ..  */
2728             }
2729            else {                            /*  */
2730             /* first remove leading digits if necessary  */
2731             if (res->digits+shift>set->digits) {
2732               decDecap(res, res->digits+shift-set->digits);
2733               /* that updated res->digits; may have gone to 1 (for a  */
2734               /* single digit or for zero  */
2735               }
2736             if (res->digits>1 || *res->lsu)  /* if non-zero..  */
2737               res->digits=decShiftToMost(res->lsu, res->digits, shift);
2738             } /* partial left  */
2739           } /* left  */
2740          else { /* to right  */
2741           if (-shift>=res->digits) {         /* discarding all  */
2742             *res->lsu=0;                     /* so place 0  */
2743             res->digits=1;                   /* ..  */
2744             }
2745            else {
2746             decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2747             res->digits-=(-shift);
2748             }
2749           } /* to right  */
2750         } /* non-0 non-Inf shift  */
2751       } /* rhs OK  */
2752     } /* numerics  */
2753   if (status!=0) decStatus(res, status, set);
2754   return res;
2755   } /* decNumberShift  */
2756 
2757 /* ------------------------------------------------------------------ */
2758 /* decNumberSquareRoot -- square root operator                        */
2759 /*                                                                    */
2760 /*   This computes C = squareroot(A)                                  */
2761 /*                                                                    */
2762 /*   res is C, the result.  C may be A                                */
2763 /*   rhs is A                                                         */
2764 /*   set is the context; note that rounding mode has no effect        */
2765 /*                                                                    */
2766 /* C must have space for set->digits digits.                          */
2767 /* ------------------------------------------------------------------ */
2768 /* This uses the following varying-precision algorithm in:            */
2769 /*                                                                    */
2770 /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2771 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2772 /*   pp229-237, ACM, September 1985.                                  */
2773 /*                                                                    */
2774 /* The square-root is calculated using Newton's method, after which   */
2775 /* a check is made to ensure the result is correctly rounded.         */
2776 /*                                                                    */
2777 /* % [Reformatted original Numerical Turing source code follows.]     */
2778 /* function sqrt(x : real) : real                                     */
2779 /* % sqrt(x) returns the properly rounded approximation to the square */
2780 /* % root of x, in the precision of the calling environment, or it    */
2781 /* % fails if x < 0.                                                  */
2782 /* % t e hull and a abrham, august, 1984                              */
2783 /* if x <= 0 then                                                     */
2784 /*   if x < 0 then                                                    */
2785 /*     assert false                                                   */
2786 /*   else                                                             */
2787 /*     result 0                                                       */
2788 /*   end if                                                           */
2789 /* end if                                                             */
2790 /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2791 /* var e := getexp(x)     % exponent part of x                        */
2792 /* var approx : real                                                  */
2793 /* if e mod 2 = 0  then                                               */
2794 /*   approx := .259 + .819 * f   % approx to root of f                */
2795 /* else                                                               */
2796 /*   f := f/l0                   % adjustments                        */
2797 /*   e := e + 1                  %   for odd                          */
2798 /*   approx := .0819 + 2.59 * f  %   exponent                         */
2799 /* end if                                                             */
2800 /*                                                                    */
2801 /* var p:= 3                                                          */
2802 /* const maxp := currentprecision + 2                                 */
2803 /* loop                                                               */
2804 /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2805 /*   precision p                                                      */
2806 /*   approx := .5 * (approx + f/approx)                               */
2807 /*   exit when p = maxp                                               */
2808 /* end loop                                                           */
2809 /*                                                                    */
2810 /* % approx is now within 1 ulp of the properly rounded square root   */
2811 /* % of f; to ensure proper rounding, compare squares of (approx -    */
2812 /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2813 /* p := currentprecision                                              */
2814 /* begin                                                              */
2815 /*   precision p + 2                                                  */
2816 /*   const approxsubhalf := approx - setexp(.5, -p)                   */
2817 /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2818 /*     approx := approx - setexp(.l, -p + 1)                          */
2819 /*   else                                                             */
2820 /*     const approxaddhalf := approx + setexp(.5, -p)                 */
2821 /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2822 /*       approx := approx + setexp(.l, -p + 1)                        */
2823 /*     end if                                                         */
2824 /*   end if                                                           */
2825 /* end                                                                */
2826 /* result setexp(approx, e div 2)  % fix exponent                     */
2827 /* end sqrt                                                           */
2828 /* ------------------------------------------------------------------ */
2829 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
2830 #pragma GCC diagnostic push
2831 #pragma GCC diagnostic ignored "-Warray-bounds"
2832 #endif
uprv_decNumberSquareRoot(decNumber * res,const decNumber * rhs,decContext * set)2833 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2834                                 decContext *set) {
2835   decContext workset, approxset;   /* work contexts  */
2836   decNumber dzero;                 /* used for constant zero  */
2837   Int  maxp;                       /* largest working precision  */
2838   Int  workp;                      /* working precision  */
2839   Int  residue=0;                  /* rounding residue  */
2840   uInt status=0, ignore=0;         /* status accumulators  */
2841   uInt rstatus;                    /* ..  */
2842   Int  exp;                        /* working exponent  */
2843   Int  ideal;                      /* ideal (preferred) exponent  */
2844   Int  needbytes;                  /* work  */
2845   Int  dropped;                    /* ..  */
2846 
2847   #if DECSUBSET
2848   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2849   #endif
2850   /* buffer for f [needs +1 in case DECBUFFER 0]  */
2851   decNumber buff[D2N(DECBUFFER+1)];
2852   /* buffer for a [needs +2 to match likely maxp]  */
2853   decNumber bufa[D2N(DECBUFFER+2)];
2854   /* buffer for temporary, b [must be same size as a]  */
2855   decNumber bufb[D2N(DECBUFFER+2)];
2856   decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated  */
2857   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
2858   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
2859   decNumber *f=buff;               /* reduced fraction  */
2860   decNumber *a=bufa;               /* approximation to result  */
2861   decNumber *b=bufb;               /* intermediate result  */
2862   /* buffer for temporary variable, up to 3 digits  */
2863   decNumber buft[D2N(3)];
2864   decNumber *t=buft;               /* up-to-3-digit constant or work  */
2865 
2866   #if DECCHECK
2867   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2868   #endif
2869 
2870   do {                             /* protect allocated storage  */
2871     #if DECSUBSET
2872     if (!set->extended) {
2873       /* reduce operand and set lostDigits status, as needed  */
2874       if (rhs->digits>set->digits) {
2875         allocrhs=decRoundOperand(rhs, set, &status);
2876         if (allocrhs==NULL) break;
2877         /* [Note: 'f' allocation below could reuse this buffer if  */
2878         /* used, but as this is rare they are kept separate for clarity.]  */
2879         rhs=allocrhs;
2880         }
2881       }
2882     #endif
2883     /* [following code does not require input rounding]  */
2884 
2885     /* handle infinities and NaNs  */
2886     if (SPECIALARG) {
2887       if (decNumberIsInfinite(rhs)) {         /* an infinity  */
2888         if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2889          else uprv_decNumberCopy(res, rhs);        /* +Infinity  */
2890         }
2891        else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
2892       break;
2893       }
2894 
2895     /* calculate the ideal (preferred) exponent [floor(exp/2)]  */
2896     /* [It would be nicer to write: ideal=rhs->exponent>>1, but this  */
2897     /* generates a compiler warning.  Generated code is the same.]  */
2898     ideal=(rhs->exponent&~1)/2;         /* target  */
2899 
2900     /* handle zeros  */
2901     if (ISZERO(rhs)) {
2902       uprv_decNumberCopy(res, rhs);          /* could be 0 or -0  */
2903       res->exponent=ideal;              /* use the ideal [safe]  */
2904       /* use decFinish to clamp any out-of-range exponent, etc.  */
2905       decFinish(res, set, &residue, &status);
2906       break;
2907       }
2908 
2909     /* any other -x is an oops  */
2910     if (decNumberIsNegative(rhs)) {
2911       status|=DEC_Invalid_operation;
2912       break;
2913       }
2914 
2915     /* space is needed for three working variables  */
2916     /*   f -- the same precision as the RHS, reduced to 0.01->0.99...  */
2917     /*   a -- Hull's approximation -- precision, when assigned, is  */
2918     /*        currentprecision+1 or the input argument precision,  */
2919     /*        whichever is larger (+2 for use as temporary)  */
2920     /*   b -- intermediate temporary result (same size as a)  */
2921     /* if any is too long for local storage, then allocate  */
2922     workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision  */
2923     workp=MAXI(workp, 7);                    /* at least 7 for low cases  */
2924     maxp=workp+2;                            /* largest working precision  */
2925 
2926     needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2927     if (needbytes>(Int)sizeof(buff)) {
2928       allocbuff=(decNumber *)malloc(needbytes);
2929       if (allocbuff==NULL) {  /* hopeless -- abandon  */
2930         status|=DEC_Insufficient_storage;
2931         break;}
2932       f=allocbuff;            /* use the allocated space  */
2933       }
2934     /* a and b both need to be able to hold a maxp-length number  */
2935     needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2936     if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b]  */
2937       allocbufa=(decNumber *)malloc(needbytes);
2938       allocbufb=(decNumber *)malloc(needbytes);
2939       if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless  */
2940         status|=DEC_Insufficient_storage;
2941         break;}
2942       a=allocbufa;            /* use the allocated spaces  */
2943       b=allocbufb;            /* ..  */
2944       }
2945 
2946     /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1  */
2947     uprv_decNumberCopy(f, rhs);
2948     exp=f->exponent+f->digits;               /* adjusted to Hull rules  */
2949     f->exponent=-(f->digits);                /* to range  */
2950 
2951     /* set up working context  */
2952     uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2953     workset.emax=DEC_MAX_EMAX;
2954     workset.emin=DEC_MIN_EMIN;
2955 
2956     /* [Until further notice, no error is possible and status bits  */
2957     /* (Rounded, etc.) should be ignored, not accumulated.]  */
2958 
2959     /* Calculate initial approximation, and allow for odd exponent  */
2960     workset.digits=workp;                    /* p for initial calculation  */
2961     t->bits=0; t->digits=3;
2962     a->bits=0; a->digits=3;
2963     if ((exp & 1)==0) {                      /* even exponent  */
2964       /* Set t=0.259, a=0.819  */
2965       t->exponent=-3;
2966       a->exponent=-3;
2967       #if DECDPUN>=3
2968         t->lsu[0]=259;
2969         a->lsu[0]=819;
2970       #elif DECDPUN==2
2971         t->lsu[0]=59; t->lsu[1]=2;
2972         a->lsu[0]=19; a->lsu[1]=8;
2973       #else
2974         t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2975         a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2976       #endif
2977       }
2978      else {                                  /* odd exponent  */
2979       /* Set t=0.0819, a=2.59  */
2980       f->exponent--;                         /* f=f/10  */
2981       exp++;                                 /* e=e+1  */
2982       t->exponent=-4;
2983       a->exponent=-2;
2984       #if DECDPUN>=3
2985         t->lsu[0]=819;
2986         a->lsu[0]=259;
2987       #elif DECDPUN==2
2988         t->lsu[0]=19; t->lsu[1]=8;
2989         a->lsu[0]=59; a->lsu[1]=2;
2990       #else
2991         t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2992         a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2993       #endif
2994       }
2995 
2996     decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f  */
2997     decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t  */
2998     /* [a is now the initial approximation for sqrt(f), calculated with  */
2999     /* currentprecision, which is also a's precision.]  */
3000 
3001     /* the main calculation loop  */
3002     uprv_decNumberZero(&dzero);                   /* make 0  */
3003     uprv_decNumberZero(t);                        /* set t = 0.5  */
3004     t->lsu[0]=5;                             /* ..  */
3005     t->exponent=-1;                          /* ..  */
3006     workset.digits=3;                        /* initial p  */
3007     for (; workset.digits<maxp;) {
3008       /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]  */
3009       workset.digits=MINI(workset.digits*2-2, maxp);
3010       /* a = 0.5 * (a + f/a)  */
3011       /* [calculated at p then rounded to currentprecision]  */
3012       decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a  */
3013       decAddOp(b, b, a, &workset, 0, &ignore);         /* b=b+a  */
3014       decMultiplyOp(a, b, t, &workset, &ignore);       /* a=b*0.5  */
3015       } /* loop  */
3016 
3017     /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits  */
3018     /* now reduce to length, etc.; this needs to be done with a  */
3019     /* having the correct exponent so as to handle subnormals  */
3020     /* correctly  */
3021     approxset=*set;                          /* get emin, emax, etc.  */
3022     approxset.round=DEC_ROUND_HALF_EVEN;
3023     a->exponent+=exp/2;                      /* set correct exponent  */
3024     rstatus=0;                               /* clear status  */
3025     residue=0;                               /* .. and accumulator  */
3026     decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed)  */
3027     decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize  */
3028 
3029     /* Overflow was possible if the input exponent was out-of-range,  */
3030     /* in which case quit  */
3031     if (rstatus&DEC_Overflow) {
3032       status=rstatus;                        /* use the status as-is  */
3033       uprv_decNumberCopy(res, a);                 /* copy to result  */
3034       break;
3035       }
3036 
3037     /* Preserve status except Inexact/Rounded  */
3038     status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3039 
3040     /* Carry out the Hull correction  */
3041     a->exponent-=exp/2;                      /* back to 0.1->1  */
3042 
3043     /* a is now at final precision and within 1 ulp of the properly  */
3044     /* rounded square root of f; to ensure proper rounding, compare  */
3045     /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f.  */
3046     /* Here workset.digits=maxp and t=0.5, and a->digits determines  */
3047     /* the ulp  */
3048     workset.digits--;                             /* maxp-1 is OK now  */
3049     t->exponent=-a->digits-1;                     /* make 0.5 ulp  */
3050     decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp  */
3051     workset.round=DEC_ROUND_UP;
3052     decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b)  */
3053     decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed  */
3054     if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f]  */
3055       /* this is the more common adjustment, though both are rare  */
3056       t->exponent++;                              /* make 1.0 ulp  */
3057       t->lsu[0]=1;                                /* ..  */
3058       decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp  */
3059       /* assign to approx [round to length]  */
3060       approxset.emin-=exp/2;                      /* adjust to match a  */
3061       approxset.emax-=exp/2;
3062       decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3063       }
3064      else {
3065       decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp  */
3066       workset.round=DEC_ROUND_DOWN;
3067       decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b)  */
3068       decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f  */
3069       if (decNumberIsNegative(b)) {               /* b < f  */
3070         t->exponent++;                            /* make 1.0 ulp  */
3071         t->lsu[0]=1;                              /* ..  */
3072         decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp  */
3073         /* assign to approx [round to length]  */
3074         approxset.emin-=exp/2;                    /* adjust to match a  */
3075         approxset.emax-=exp/2;
3076         decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3077         }
3078       }
3079     /* [no errors are possible in the above, and rounding/inexact during  */
3080     /* estimation are irrelevant, so status was not accumulated]  */
3081 
3082     /* Here, 0.1 <= a < 1  (still), so adjust back  */
3083     a->exponent+=exp/2;                      /* set correct exponent  */
3084 
3085     /* count droppable zeros [after any subnormal rounding] by  */
3086     /* trimming a copy  */
3087     uprv_decNumberCopy(b, a);
3088     decTrim(b, set, 1, 1, &dropped);         /* [drops trailing zeros]  */
3089 
3090     /* Set Inexact and Rounded.  The answer can only be exact if  */
3091     /* it is short enough so that squaring it could fit in workp  */
3092     /* digits, so this is the only (relatively rare) condition that  */
3093     /* a careful check is needed  */
3094     if (b->digits*2-1 > workp) {             /* cannot fit  */
3095       status|=DEC_Inexact|DEC_Rounded;
3096       }
3097      else {                                  /* could be exact/unrounded  */
3098       uInt mstatus=0;                        /* local status  */
3099       decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply  */
3100       if (mstatus&DEC_Overflow) {            /* result just won't fit  */
3101         status|=DEC_Inexact|DEC_Rounded;
3102         }
3103        else {                                /* plausible  */
3104         decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs  */
3105         if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal  */
3106          else {                              /* is Exact  */
3107           /* here, dropped is the count of trailing zeros in 'a'  */
3108           /* use closest exponent to ideal...  */
3109           Int todrop=ideal-a->exponent;      /* most that can be dropped  */
3110           if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s  */
3111            else {                            /* unrounded  */
3112             /* there are some to drop, but emax may not allow all  */
3113             Int maxexp=set->emax-set->digits+1;
3114             Int maxdrop=maxexp-a->exponent;
3115             if (todrop>maxdrop && set->clamp) { /* apply clamping  */
3116               todrop=maxdrop;
3117               status|=DEC_Clamped;
3118               }
3119             if (dropped<todrop) {            /* clamp to those available  */
3120               todrop=dropped;
3121               status|=DEC_Clamped;
3122               }
3123             if (todrop>0) {                  /* have some to drop  */
3124               decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3125               a->exponent+=todrop;           /* maintain numerical value  */
3126               a->digits-=todrop;             /* new length  */
3127               }
3128             }
3129           }
3130         }
3131       }
3132 
3133     /* double-check Underflow, as perhaps the result could not have  */
3134     /* been subnormal (initial argument too big), or it is now Exact  */
3135     if (status&DEC_Underflow) {
3136       Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent  */
3137       /* check if truly subnormal  */
3138       #if DECEXTFLAG                         /* DEC_Subnormal too  */
3139         if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3140       #else
3141         if (ae>=set->emin*2) status&=~DEC_Underflow;
3142       #endif
3143       /* check if truly inexact  */
3144       if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3145       }
3146 
3147     uprv_decNumberCopy(res, a);                   /* a is now the result  */
3148     } while(0);                              /* end protected  */
3149 
3150   if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used  */
3151   if (allocbufa!=NULL) free(allocbufa);      /* ..  */
3152   if (allocbufb!=NULL) free(allocbufb);      /* ..  */
3153   #if DECSUBSET
3154   if (allocrhs !=NULL) free(allocrhs);       /* ..  */
3155   #endif
3156   if (status!=0) decStatus(res, status, set);/* then report status  */
3157   #if DECCHECK
3158   decCheckInexact(res, set);
3159   #endif
3160   return res;
3161   } /* decNumberSquareRoot  */
3162 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
3163 #pragma GCC diagnostic pop
3164 #endif
3165 
3166 /* ------------------------------------------------------------------ */
3167 /* decNumberSubtract -- subtract two Numbers                          */
3168 /*                                                                    */
3169 /*   This computes C = A - B                                          */
3170 /*                                                                    */
3171 /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3172 /*   lhs is A                                                         */
3173 /*   rhs is B                                                         */
3174 /*   set is the context                                               */
3175 /*                                                                    */
3176 /* C must have space for set->digits digits.                          */
3177 /* ------------------------------------------------------------------ */
uprv_decNumberSubtract(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)3178 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3179                               const decNumber *rhs, decContext *set) {
3180   uInt status=0;                        /* accumulator  */
3181 
3182   decAddOp(res, lhs, rhs, set, DECNEG, &status);
3183   if (status!=0) decStatus(res, status, set);
3184   #if DECCHECK
3185   decCheckInexact(res, set);
3186   #endif
3187   return res;
3188   } /* decNumberSubtract  */
3189 
3190 /* ------------------------------------------------------------------ */
3191 /* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3192 /* decNumberToIntegralValue -- round-to-integral-value                */
3193 /*                                                                    */
3194 /*   res is the result                                                */
3195 /*   rhs is input number                                              */
3196 /*   set is the context                                               */
3197 /*                                                                    */
3198 /* res must have space for any value of rhs.                          */
3199 /*                                                                    */
3200 /* This implements the IEEE special operators and therefore treats    */
3201 /* special values as valid.  For finite numbers it returns            */
3202 /* rescale(rhs, 0) if rhs->exponent is <0.                            */
3203 /* Otherwise the result is rhs (so no error is possible, except for   */
3204 /* sNaN).                                                             */
3205 /*                                                                    */
3206 /* The context is used for rounding mode and status after sNaN, but   */
3207 /* the digits setting is ignored.  The Exact version will signal      */
3208 /* Inexact if the result differs numerically from rhs; the other      */
3209 /* never signals Inexact.                                             */
3210 /* ------------------------------------------------------------------ */
uprv_decNumberToIntegralExact(decNumber * res,const decNumber * rhs,decContext * set)3211 U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3212                                      decContext *set) {
3213   decNumber dn;
3214   decContext workset;              /* working context  */
3215   uInt status=0;                   /* accumulator  */
3216 
3217   #if DECCHECK
3218   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3219   #endif
3220 
3221   /* handle infinities and NaNs  */
3222   if (SPECIALARG) {
3223     if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity  */
3224      else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
3225     }
3226    else { /* finite  */
3227     /* have a finite number; no error possible (res must be big enough)  */
3228     if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3229     /* that was easy, but if negative exponent there is work to do...  */
3230     workset=*set;                  /* clone rounding, etc.  */
3231     workset.digits=rhs->digits;    /* no length rounding  */
3232     workset.traps=0;               /* no traps  */
3233     uprv_decNumberZero(&dn);            /* make a number with exponent 0  */
3234     uprv_decNumberQuantize(res, rhs, &dn, &workset);
3235     status|=workset.status;
3236     }
3237   if (status!=0) decStatus(res, status, set);
3238   return res;
3239   } /* decNumberToIntegralExact  */
3240 
uprv_decNumberToIntegralValue(decNumber * res,const decNumber * rhs,decContext * set)3241 U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3242                                      decContext *set) {
3243   decContext workset=*set;         /* working context  */
3244   workset.traps=0;                 /* no traps  */
3245   uprv_decNumberToIntegralExact(res, rhs, &workset);
3246   /* this never affects set, except for sNaNs; NaN will have been set  */
3247   /* or propagated already, so no need to call decStatus  */
3248   set->status|=workset.status&DEC_Invalid_operation;
3249   return res;
3250   } /* decNumberToIntegralValue  */
3251 
3252 /* ------------------------------------------------------------------ */
3253 /* decNumberXor -- XOR two Numbers, digitwise                         */
3254 /*                                                                    */
3255 /*   This computes C = A ^ B                                          */
3256 /*                                                                    */
3257 /*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3258 /*   lhs is A                                                         */
3259 /*   rhs is B                                                         */
3260 /*   set is the context (used for result length and error report)     */
3261 /*                                                                    */
3262 /* C must have space for set->digits digits.                          */
3263 /*                                                                    */
3264 /* Logical function restrictions apply (see above); a NaN is          */
3265 /* returned with Invalid_operation if a restriction is violated.      */
3266 /* ------------------------------------------------------------------ */
uprv_decNumberXor(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)3267 U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3268                          const decNumber *rhs, decContext *set) {
3269   const Unit *ua, *ub;                  /* -> operands  */
3270   const Unit *msua, *msub;              /* -> operand msus  */
3271   Unit  *uc, *msuc;                     /* -> result and its msu  */
3272   Int   msudigs;                        /* digits in res msu  */
3273   #if DECCHECK
3274   if (decCheckOperands(res, lhs, rhs, set)) return res;
3275   #endif
3276 
3277   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3278    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3279     decStatus(res, DEC_Invalid_operation, set);
3280     return res;
3281     }
3282   /* operands are valid  */
3283   ua=lhs->lsu;                          /* bottom-up  */
3284   ub=rhs->lsu;                          /* ..  */
3285   uc=res->lsu;                          /* ..  */
3286   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
3287   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
3288   msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
3289   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
3290   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
3291     Unit a, b;                          /* extract units  */
3292     if (ua>msua) a=0;
3293      else a=*ua;
3294     if (ub>msub) b=0;
3295      else b=*ub;
3296     *uc=0;                              /* can now write back  */
3297     if (a|b) {                          /* maybe 1 bits to examine  */
3298       Int i, j;
3299       /* This loop could be unrolled and/or use BIN2BCD tables  */
3300       for (i=0; i<DECDPUN; i++) {
3301         if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR  */
3302         j=a%10;
3303         a=a/10;
3304         j|=b%10;
3305         b=b/10;
3306         if (j>1) {
3307           decStatus(res, DEC_Invalid_operation, set);
3308           return res;
3309           }
3310         if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
3311         } /* each digit  */
3312       } /* non-zero  */
3313     } /* each unit  */
3314   /* [here uc-1 is the msu of the result]  */
3315   res->digits=decGetDigits(res->lsu, static_cast<int32_t>(uc-res->lsu));
3316   res->exponent=0;                      /* integer  */
3317   res->bits=0;                          /* sign=0  */
3318   return res;  /* [no status to set]  */
3319   } /* decNumberXor  */
3320 
3321 
3322 /* ================================================================== */
3323 /* Utility routines                                                   */
3324 /* ================================================================== */
3325 
3326 /* ------------------------------------------------------------------ */
3327 /* decNumberClass -- return the decClass of a decNumber               */
3328 /*   dn -- the decNumber to test                                      */
3329 /*   set -- the context to use for Emin                               */
3330 /*   returns the decClass enum                                        */
3331 /* ------------------------------------------------------------------ */
uprv_decNumberClass(const decNumber * dn,decContext * set)3332 enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3333   if (decNumberIsSpecial(dn)) {
3334     if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3335     if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3336     /* must be an infinity  */
3337     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3338     return DEC_CLASS_POS_INF;
3339     }
3340   /* is finite  */
3341   if (uprv_decNumberIsNormal(dn, set)) { /* most common  */
3342     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3343     return DEC_CLASS_POS_NORMAL;
3344     }
3345   /* is subnormal or zero  */
3346   if (decNumberIsZero(dn)) {    /* most common  */
3347     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3348     return DEC_CLASS_POS_ZERO;
3349     }
3350   if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3351   return DEC_CLASS_POS_SUBNORMAL;
3352   } /* decNumberClass  */
3353 
3354 /* ------------------------------------------------------------------ */
3355 /* decNumberClassToString -- convert decClass to a string             */
3356 /*                                                                    */
3357 /*  eclass is a valid decClass                                        */
3358 /*  returns a constant string describing the class (max 13+1 chars)   */
3359 /* ------------------------------------------------------------------ */
uprv_decNumberClassToString(enum decClass eclass)3360 const char *uprv_decNumberClassToString(enum decClass eclass) {
3361   if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3362   if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3363   if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3364   if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3365   if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3366   if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3367   if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3368   if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3369   if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3370   if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3371   return DEC_ClassString_UN;           /* Unknown  */
3372   } /* decNumberClassToString  */
3373 
3374 /* ------------------------------------------------------------------ */
3375 /* decNumberCopy -- copy a number                                     */
3376 /*                                                                    */
3377 /*   dest is the target decNumber                                     */
3378 /*   src  is the source decNumber                                     */
3379 /*   returns dest                                                     */
3380 /*                                                                    */
3381 /* (dest==src is allowed and is a no-op)                              */
3382 /* All fields are updated as required.  This is a utility operation,  */
3383 /* so special values are unchanged and no error is possible.          */
3384 /* ------------------------------------------------------------------ */
uprv_decNumberCopy(decNumber * dest,const decNumber * src)3385 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3386 
3387   #if DECCHECK
3388   if (src==NULL) return uprv_decNumberZero(dest);
3389   #endif
3390 
3391   if (dest==src) return dest;                /* no copy required  */
3392 
3393   /* Use explicit assignments here as structure assignment could copy  */
3394   /* more than just the lsu (for small DECDPUN).  This would not affect  */
3395   /* the value of the results, but could disturb test harness spill  */
3396   /* checking.  */
3397   dest->bits=src->bits;
3398   dest->exponent=src->exponent;
3399   dest->digits=src->digits;
3400   dest->lsu[0]=src->lsu[0];
3401   if (src->digits>DECDPUN) {                 /* more Units to come  */
3402     const Unit *smsup, *s;                   /* work  */
3403     Unit  *d;                                /* ..  */
3404     /* memcpy for the remaining Units would be safe as they cannot  */
3405     /* overlap.  However, this explicit loop is faster in short cases.  */
3406     d=dest->lsu+1;                           /* -> first destination  */
3407     smsup=src->lsu+D2U(src->digits);         /* -> source msu+1  */
3408     for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3409     }
3410   return dest;
3411   } /* decNumberCopy  */
3412 
3413 /* ------------------------------------------------------------------ */
3414 /* decNumberCopyAbs -- quiet absolute value operator                  */
3415 /*                                                                    */
3416 /*   This sets C = abs(A)                                             */
3417 /*                                                                    */
3418 /*   res is C, the result.  C may be A                                */
3419 /*   rhs is A                                                         */
3420 /*                                                                    */
3421 /* C must have space for set->digits digits.                          */
3422 /* No exception or error can occur; this is a quiet bitwise operation.*/
3423 /* See also decNumberAbs for a checking version of this.              */
3424 /* ------------------------------------------------------------------ */
uprv_decNumberCopyAbs(decNumber * res,const decNumber * rhs)3425 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3426   #if DECCHECK
3427   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3428   #endif
3429   uprv_decNumberCopy(res, rhs);
3430   res->bits&=~DECNEG;                   /* turn off sign  */
3431   return res;
3432   } /* decNumberCopyAbs  */
3433 
3434 /* ------------------------------------------------------------------ */
3435 /* decNumberCopyNegate -- quiet negate value operator                 */
3436 /*                                                                    */
3437 /*   This sets C = negate(A)                                          */
3438 /*                                                                    */
3439 /*   res is C, the result.  C may be A                                */
3440 /*   rhs is A                                                         */
3441 /*                                                                    */
3442 /* C must have space for set->digits digits.                          */
3443 /* No exception or error can occur; this is a quiet bitwise operation.*/
3444 /* See also decNumberMinus for a checking version of this.            */
3445 /* ------------------------------------------------------------------ */
uprv_decNumberCopyNegate(decNumber * res,const decNumber * rhs)3446 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3447   #if DECCHECK
3448   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3449   #endif
3450   uprv_decNumberCopy(res, rhs);
3451   res->bits^=DECNEG;                    /* invert the sign  */
3452   return res;
3453   } /* decNumberCopyNegate  */
3454 
3455 /* ------------------------------------------------------------------ */
3456 /* decNumberCopySign -- quiet copy and set sign operator              */
3457 /*                                                                    */
3458 /*   This sets C = A with the sign of B                               */
3459 /*                                                                    */
3460 /*   res is C, the result.  C may be A                                */
3461 /*   lhs is A                                                         */
3462 /*   rhs is B                                                         */
3463 /*                                                                    */
3464 /* C must have space for set->digits digits.                          */
3465 /* No exception or error can occur; this is a quiet bitwise operation.*/
3466 /* ------------------------------------------------------------------ */
uprv_decNumberCopySign(decNumber * res,const decNumber * lhs,const decNumber * rhs)3467 U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3468                               const decNumber *rhs) {
3469   uByte sign;                           /* rhs sign  */
3470   #if DECCHECK
3471   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3472   #endif
3473   sign=rhs->bits & DECNEG;              /* save sign bit  */
3474   uprv_decNumberCopy(res, lhs);
3475   res->bits&=~DECNEG;                   /* clear the sign  */
3476   res->bits|=sign;                      /* set from rhs  */
3477   return res;
3478   } /* decNumberCopySign  */
3479 
3480 /* ------------------------------------------------------------------ */
3481 /* decNumberGetBCD -- get the coefficient in BCD8                     */
3482 /*   dn is the source decNumber                                       */
3483 /*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3484 /*     most-significant at offset 0                                   */
3485 /*   returns bcd                                                      */
3486 /*                                                                    */
3487 /* bcd must have at least dn->digits bytes.  No error is possible; if */
3488 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3489 /* ------------------------------------------------------------------ */
uprv_decNumberGetBCD(const decNumber * dn,uByte * bcd)3490 U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3491   uByte *ub=bcd+dn->digits-1;      /* -> lsd  */
3492   const Unit *up=dn->lsu;          /* Unit pointer, -> lsu  */
3493 
3494   #if DECDPUN==1                   /* trivial simple copy  */
3495     for (; ub>=bcd; ub--, up++) *ub=*up;
3496   #else                            /* chopping needed  */
3497     uInt u=*up;                    /* work  */
3498     uInt cut=DECDPUN;              /* downcounter through unit  */
3499     for (; ub>=bcd; ub--) {
3500       *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here]  */
3501       u=u/10;
3502       cut--;
3503       if (cut>0) continue;         /* more in this unit  */
3504       up++;
3505       u=*up;
3506       cut=DECDPUN;
3507       }
3508   #endif
3509   return bcd;
3510   } /* decNumberGetBCD  */
3511 
3512 /* ------------------------------------------------------------------ */
3513 /* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3514 /*   dn is the target decNumber                                       */
3515 /*   bcd is the uInt array that will source n BCD bytes, most-        */
3516 /*     significant at offset 0                                        */
3517 /*   n is the number of digits in the source BCD array (bcd)          */
3518 /*   returns dn                                                       */
3519 /*                                                                    */
3520 /* dn must have space for at least n digits.  No error is possible;   */
3521 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3522 /* and bcd[0] zero.                                                   */
3523 /* ------------------------------------------------------------------ */
uprv_decNumberSetBCD(decNumber * dn,const uByte * bcd,uInt n)3524 U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3525   Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer]  */
3526   const uByte *ub=bcd;                  /* -> source msd  */
3527 
3528   #if DECDPUN==1                        /* trivial simple copy  */
3529     for (; ub<bcd+n; ub++, up--) *up=*ub;
3530   #else                                 /* some assembly needed  */
3531     /* calculate how many digits in msu, and hence first cut  */
3532     Int cut=MSUDIGITS(n);               /* [faster than remainder]  */
3533     for (;up>=dn->lsu; up--) {          /* each Unit from msu  */
3534       *up=0;                            /* will take <=DECDPUN digits  */
3535       for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3536       cut=DECDPUN;                      /* next Unit has all digits  */
3537       }
3538   #endif
3539   dn->digits=n;                         /* set digit count  */
3540   return dn;
3541   } /* decNumberSetBCD  */
3542 
3543 /* ------------------------------------------------------------------ */
3544 /* decNumberIsNormal -- test normality of a decNumber                 */
3545 /*   dn is the decNumber to test                                      */
3546 /*   set is the context to use for Emin                               */
3547 /*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3548 /* ------------------------------------------------------------------ */
uprv_decNumberIsNormal(const decNumber * dn,decContext * set)3549 Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3550   Int ae;                               /* adjusted exponent  */
3551   #if DECCHECK
3552   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3553   #endif
3554 
3555   if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3556   if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3557 
3558   ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3559   if (ae<set->emin) return 0;           /* is subnormal  */
3560   return 1;
3561   } /* decNumberIsNormal  */
3562 
3563 /* ------------------------------------------------------------------ */
3564 /* decNumberIsSubnormal -- test subnormality of a decNumber           */
3565 /*   dn is the decNumber to test                                      */
3566 /*   set is the context to use for Emin                               */
3567 /*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3568 /* ------------------------------------------------------------------ */
uprv_decNumberIsSubnormal(const decNumber * dn,decContext * set)3569 Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3570   Int ae;                               /* adjusted exponent  */
3571   #if DECCHECK
3572   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3573   #endif
3574 
3575   if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3576   if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3577 
3578   ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3579   if (ae<set->emin) return 1;           /* is subnormal  */
3580   return 0;
3581   } /* decNumberIsSubnormal  */
3582 
3583 /* ------------------------------------------------------------------ */
3584 /* decNumberTrim -- remove insignificant zeros                        */
3585 /*                                                                    */
3586 /*   dn is the number to trim                                         */
3587 /*   returns dn                                                       */
3588 /*                                                                    */
3589 /* All fields are updated as required.  This is a utility operation,  */
3590 /* so special values are unchanged and no error is possible.  The     */
3591 /* zeros are removed unconditionally.                                 */
3592 /* ------------------------------------------------------------------ */
uprv_decNumberTrim(decNumber * dn)3593 U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3594   Int  dropped;                    /* work  */
3595   decContext set;                  /* ..  */
3596   #if DECCHECK
3597   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3598   #endif
3599   uprv_decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0  */
3600   return decTrim(dn, &set, 0, 1, &dropped);
3601   } /* decNumberTrim  */
3602 
3603 /* ------------------------------------------------------------------ */
3604 /* decNumberVersion -- return the name and version of this module     */
3605 /*                                                                    */
3606 /* No error is possible.                                              */
3607 /* ------------------------------------------------------------------ */
uprv_decNumberVersion(void)3608 const char * uprv_decNumberVersion(void) {
3609   return DECVERSION;
3610   } /* decNumberVersion  */
3611 
3612 /* ------------------------------------------------------------------ */
3613 /* decNumberZero -- set a number to 0                                 */
3614 /*                                                                    */
3615 /*   dn is the number to set, with space for one digit                */
3616 /*   returns dn                                                       */
3617 /*                                                                    */
3618 /* No error is possible.                                              */
3619 /* ------------------------------------------------------------------ */
3620 /* Memset is not used as it is much slower in some environments.  */
uprv_decNumberZero(decNumber * dn)3621 U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3622 
3623   #if DECCHECK
3624   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3625   #endif
3626 
3627   dn->bits=0;
3628   dn->exponent=0;
3629   dn->digits=1;
3630   dn->lsu[0]=0;
3631   return dn;
3632   } /* decNumberZero  */
3633 
3634 /* ================================================================== */
3635 /* Local routines                                                     */
3636 /* ================================================================== */
3637 
3638 /* ------------------------------------------------------------------ */
3639 /* decToString -- lay out a number into a string                      */
3640 /*                                                                    */
3641 /*   dn     is the number to lay out                                  */
3642 /*   string is where to lay out the number                            */
3643 /*   eng    is 1 if Engineering, 0 if Scientific                      */
3644 /*                                                                    */
3645 /* string must be at least dn->digits+14 characters long              */
3646 /* No error is possible.                                              */
3647 /*                                                                    */
3648 /* Note that this routine can generate a -0 or 0.000.  These are      */
3649 /* never generated in subset to-number or arithmetic, but can occur   */
3650 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3651 /* ------------------------------------------------------------------ */
3652 /* If DECCHECK is enabled the string "?" is returned if a number is  */
3653 /* invalid.  */
decToString(const decNumber * dn,char * string,Flag eng)3654 static void decToString(const decNumber *dn, char *string, Flag eng) {
3655   Int exp=dn->exponent;       /* local copy  */
3656   Int e;                      /* E-part value  */
3657   Int pre;                    /* digits before the '.'  */
3658   Int cut;                    /* for counting digits in a Unit  */
3659   char *c=string;             /* work [output pointer]  */
3660   const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer]  */
3661   uInt u, pow;                /* work  */
3662 
3663   #if DECCHECK
3664   if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3665     strcpy(string, "?");
3666     return;}
3667   #endif
3668 
3669   if (decNumberIsNegative(dn)) {   /* Negatives get a minus  */
3670     *c='-';
3671     c++;
3672     }
3673   if (dn->bits&DECSPECIAL) {       /* Is a special value  */
3674     if (decNumberIsInfinite(dn)) {
3675       strcpy(c,   "Inf");
3676       strcpy(c+3, "inity");
3677       return;}
3678     /* a NaN  */
3679     if (dn->bits&DECSNAN) {        /* signalling NaN  */
3680       *c='s';
3681       c++;
3682       }
3683     strcpy(c, "NaN");
3684     c+=3;                          /* step past  */
3685     /* if not a clean non-zero coefficient, that's all there is in a  */
3686     /* NaN string  */
3687     if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3688     /* [drop through to add integer]  */
3689     }
3690 
3691   /* calculate how many digits in msu, and hence first cut  */
3692   cut=MSUDIGITS(dn->digits);       /* [faster than remainder]  */
3693   cut--;                           /* power of ten for digit  */
3694 
3695   if (exp==0) {                    /* simple integer [common fastpath]  */
3696     for (;up>=dn->lsu; up--) {     /* each Unit from msu  */
3697       u=*up;                       /* contains DECDPUN digits to lay out  */
3698       for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3699       cut=DECDPUN-1;               /* next Unit has all digits  */
3700       }
3701     *c='\0';                       /* terminate the string  */
3702     return;}
3703 
3704   /* non-0 exponent -- assume plain form */
3705   pre=dn->digits+exp;              /* digits before '.'  */
3706   e=0;                             /* no E  */
3707   if ((exp>0) || (pre<-5)) {       /* need exponential form  */
3708     e=exp+dn->digits-1;            /* calculate E value  */
3709     pre=1;                         /* assume one digit before '.'  */
3710     if (eng && (e!=0)) {           /* engineering: may need to adjust  */
3711       Int adj;                     /* adjustment  */
3712       /* The C remainder operator is undefined for negative numbers, so  */
3713       /* a positive remainder calculation must be used here  */
3714       if (e<0) {
3715         adj=(-e)%3;
3716         if (adj!=0) adj=3-adj;
3717         }
3718        else { /* e>0  */
3719         adj=e%3;
3720         }
3721       e=e-adj;
3722       /* if dealing with zero still produce an exponent which is a  */
3723       /* multiple of three, as expected, but there will only be the  */
3724       /* one zero before the E, still.  Otherwise note the padding.  */
3725       if (!ISZERO(dn)) pre+=adj;
3726        else {  /* is zero  */
3727         if (adj!=0) {              /* 0.00Esnn needed  */
3728           e=e+3;
3729           pre=-(2-adj);
3730           }
3731         } /* zero  */
3732       } /* eng  */
3733     } /* need exponent  */
3734 
3735   /* lay out the digits of the coefficient, adding 0s and . as needed */
3736   u=*up;
3737   if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form  */
3738     Int n=pre;
3739     for (; pre>0; pre--, c++, cut--) {
3740       if (cut<0) {                 /* need new Unit  */
3741         if (up==dn->lsu) break;    /* out of input digits (pre>digits)  */
3742         up--;
3743         cut=DECDPUN-1;
3744         u=*up;
3745         }
3746       TODIGIT(u, cut, c, pow);
3747       }
3748     if (n<dn->digits) {            /* more to come, after '.'  */
3749       *c='.'; c++;
3750       for (;; c++, cut--) {
3751         if (cut<0) {               /* need new Unit  */
3752           if (up==dn->lsu) break;  /* out of input digits  */
3753           up--;
3754           cut=DECDPUN-1;
3755           u=*up;
3756           }
3757         TODIGIT(u, cut, c, pow);
3758         }
3759       }
3760      else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed  */
3761     }
3762    else {                          /* 0.xxx or 0.000xxx form  */
3763     *c='0'; c++;
3764     *c='.'; c++;
3765     for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.'  */
3766     for (; ; c++, cut--) {
3767       if (cut<0) {                 /* need new Unit  */
3768         if (up==dn->lsu) break;    /* out of input digits  */
3769         up--;
3770         cut=DECDPUN-1;
3771         u=*up;
3772         }
3773       TODIGIT(u, cut, c, pow);
3774       }
3775     }
3776 
3777   /* Finally add the E-part, if needed.  It will never be 0, has a
3778      base maximum and minimum of +999999999 through -999999999, but
3779      could range down to -1999999998 for anormal numbers */
3780   if (e!=0) {
3781     Flag had=0;               /* 1=had non-zero  */
3782     *c='E'; c++;
3783     *c='+'; c++;              /* assume positive  */
3784     u=e;                      /* ..  */
3785     if (e<0) {
3786       *(c-1)='-';             /* oops, need -  */
3787       u=-e;                   /* uInt, please  */
3788       }
3789     /* lay out the exponent [_itoa or equivalent is not ANSI C]  */
3790     for (cut=9; cut>=0; cut--) {
3791       TODIGIT(u, cut, c, pow);
3792       if (*c=='0' && !had) continue;    /* skip leading zeros  */
3793       had=1;                            /* had non-0  */
3794       c++;                              /* step for next  */
3795       } /* cut  */
3796     }
3797   *c='\0';          /* terminate the string (all paths)  */
3798   return;
3799   } /* decToString  */
3800 
3801 /* ------------------------------------------------------------------ */
3802 /* decAddOp -- add/subtract operation                                 */
3803 /*                                                                    */
3804 /*   This computes C = A + B                                          */
3805 /*                                                                    */
3806 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3807 /*   lhs is A                                                         */
3808 /*   rhs is B                                                         */
3809 /*   set is the context                                               */
3810 /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3811 /*   status accumulates status for the caller                         */
3812 /*                                                                    */
3813 /* C must have space for set->digits digits.                          */
3814 /* Inexact in status must be 0 for correct Exact zero sign in result  */
3815 /* ------------------------------------------------------------------ */
3816 /* If possible, the coefficient is calculated directly into C.        */
3817 /* However, if:                                                       */
3818 /*   -- a digits+1 calculation is needed because the numbers are      */
3819 /*      unaligned and span more than set->digits digits               */
3820 /*   -- a carry to digits+1 digits looks possible                     */
3821 /*   -- C is the same as A or B, and the result would destructively   */
3822 /*      overlap the A or B coefficient                                */
3823 /* then the result must be calculated into a temporary buffer.  In    */
3824 /* this case a local (stack) buffer is used if possible, and only if  */
3825 /* too long for that does malloc become the final resort.             */
3826 /*                                                                    */
3827 /* Misalignment is handled as follows:                                */
3828 /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3829 /*   BPad: Apply the padding by a combination of shifting (whole      */
3830 /*         units) and multiplication (part units).                    */
3831 /*                                                                    */
3832 /* Addition, especially x=x+1, is speed-critical.                     */
3833 /* The static buffer is larger than might be expected to allow for    */
3834 /* calls from higher-level funtions (notable exp).                    */
3835 /* ------------------------------------------------------------------ */
decAddOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,uByte negate,uInt * status)3836 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3837                             const decNumber *rhs, decContext *set,
3838                             uByte negate, uInt *status) {
3839   #if DECSUBSET
3840   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
3841   decNumber *allocrhs=NULL;        /* .., rhs  */
3842   #endif
3843   Int   rhsshift;                  /* working shift (in Units)  */
3844   Int   maxdigits;                 /* longest logical length  */
3845   Int   mult;                      /* multiplier  */
3846   Int   residue;                   /* rounding accumulator  */
3847   uByte bits;                      /* result bits  */
3848   Flag  diffsign;                  /* non-0 if arguments have different sign  */
3849   Unit  *acc;                      /* accumulator for result  */
3850   Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many  */
3851                                    /* allocations when called from  */
3852                                    /* other operations, notable exp]  */
3853   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
3854   Int   reqdigits=set->digits;     /* local copy; requested DIGITS  */
3855   Int   padding;                   /* work  */
3856 
3857   #if DECCHECK
3858   if (decCheckOperands(res, lhs, rhs, set)) return res;
3859   #endif
3860 
3861   do {                             /* protect allocated storage  */
3862     #if DECSUBSET
3863     if (!set->extended) {
3864       /* reduce operands and set lostDigits status, as needed  */
3865       if (lhs->digits>reqdigits) {
3866         alloclhs=decRoundOperand(lhs, set, status);
3867         if (alloclhs==NULL) break;
3868         lhs=alloclhs;
3869         }
3870       if (rhs->digits>reqdigits) {
3871         allocrhs=decRoundOperand(rhs, set, status);
3872         if (allocrhs==NULL) break;
3873         rhs=allocrhs;
3874         }
3875       }
3876     #endif
3877     /* [following code does not require input rounding]  */
3878 
3879     /* note whether signs differ [used all paths]  */
3880     diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3881 
3882     /* handle infinities and NaNs  */
3883     if (SPECIALARGS) {                  /* a special bit set  */
3884       if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN  */
3885         decNaNs(res, lhs, rhs, set, status);
3886        else { /* one or two infinities  */
3887         if (decNumberIsInfinite(lhs)) { /* LHS is infinity  */
3888           /* two infinities with different signs is invalid  */
3889           if (decNumberIsInfinite(rhs) && diffsign) {
3890             *status|=DEC_Invalid_operation;
3891             break;
3892             }
3893           bits=lhs->bits & DECNEG;      /* get sign from LHS  */
3894           }
3895          else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity  */
3896         bits|=DECINF;
3897         uprv_decNumberZero(res);
3898         res->bits=bits;                 /* set +/- infinity  */
3899         } /* an infinity  */
3900       break;
3901       }
3902 
3903     /* Quick exit for add 0s; return the non-0, modified as need be  */
3904     if (ISZERO(lhs)) {
3905       Int adjust;                       /* work  */
3906       Int lexp=lhs->exponent;           /* save in case LHS==RES  */
3907       bits=lhs->bits;                   /* ..  */
3908       residue=0;                        /* clear accumulator  */
3909       decCopyFit(res, rhs, set, &residue, status); /* copy (as needed)  */
3910       res->bits^=negate;                /* flip if rhs was negated  */
3911       #if DECSUBSET
3912       if (set->extended) {              /* exponents on zeros count  */
3913       #endif
3914         /* exponent will be the lower of the two  */
3915         adjust=lexp-res->exponent;      /* adjustment needed [if -ve]  */
3916         if (ISZERO(res)) {              /* both 0: special IEEE 754 rules  */
3917           if (adjust<0) res->exponent=lexp;  /* set exponent  */
3918           /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0  */
3919           if (diffsign) {
3920             if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3921              else res->bits=DECNEG;     /* preserve 0 sign  */
3922             }
3923           }
3924          else { /* non-0 res  */
3925           if (adjust<0) {     /* 0-padding needed  */
3926             if ((res->digits-adjust)>set->digits) {
3927               adjust=res->digits-set->digits;     /* to fit exactly  */
3928               *status|=DEC_Rounded;               /* [but exact]  */
3929               }
3930             res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3931             res->exponent+=adjust;                /* set the exponent.  */
3932             }
3933           } /* non-0 res  */
3934       #if DECSUBSET
3935         } /* extended  */
3936       #endif
3937       decFinish(res, set, &residue, status);      /* clean and finalize  */
3938       break;}
3939 
3940     if (ISZERO(rhs)) {                  /* [lhs is non-zero]  */
3941       Int adjust;                       /* work  */
3942       Int rexp=rhs->exponent;           /* save in case RHS==RES  */
3943       bits=rhs->bits;                   /* be clean  */
3944       residue=0;                        /* clear accumulator  */
3945       decCopyFit(res, lhs, set, &residue, status); /* copy (as needed)  */
3946       #if DECSUBSET
3947       if (set->extended) {              /* exponents on zeros count  */
3948       #endif
3949         /* exponent will be the lower of the two  */
3950         /* [0-0 case handled above]  */
3951         adjust=rexp-res->exponent;      /* adjustment needed [if -ve]  */
3952         if (adjust<0) {     /* 0-padding needed  */
3953           if ((res->digits-adjust)>set->digits) {
3954             adjust=res->digits-set->digits;     /* to fit exactly  */
3955             *status|=DEC_Rounded;               /* [but exact]  */
3956             }
3957           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3958           res->exponent+=adjust;                /* set the exponent.  */
3959           }
3960       #if DECSUBSET
3961         } /* extended  */
3962       #endif
3963       decFinish(res, set, &residue, status);      /* clean and finalize  */
3964       break;}
3965 
3966     /* [NB: both fastpath and mainpath code below assume these cases  */
3967     /* (notably 0-0) have already been handled]  */
3968 
3969     /* calculate the padding needed to align the operands  */
3970     padding=rhs->exponent-lhs->exponent;
3971 
3972     /* Fastpath cases where the numbers are aligned and normal, the RHS  */
3973     /* is all in one unit, no operand rounding is needed, and no carry,  */
3974     /* lengthening, or borrow is needed  */
3975     if (padding==0
3976         && rhs->digits<=DECDPUN
3977         && rhs->exponent>=set->emin     /* [some normals drop through]  */
3978         && rhs->exponent<=set->emax-set->digits+1 /* [could clamp]  */
3979         && rhs->digits<=reqdigits
3980         && lhs->digits<=reqdigits) {
3981       Int partial=*lhs->lsu;
3982       if (!diffsign) {                  /* adding  */
3983         partial+=*rhs->lsu;
3984         if ((partial<=DECDPUNMAX)       /* result fits in unit  */
3985          && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change  */
3986              partial<(Int)powers[lhs->digits])) { /* ..  */
3987           if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3988           *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS]  */
3989           break;
3990           }
3991         /* else drop out for careful add  */
3992         }
3993        else {                           /* signs differ  */
3994         partial-=*rhs->lsu;
3995         if (partial>0) { /* no borrow needed, and non-0 result  */
3996           if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3997           *res->lsu=(Unit)partial;
3998           /* this could have reduced digits [but result>0]  */
3999           res->digits=decGetDigits(res->lsu, D2U(res->digits));
4000           break;
4001           }
4002         /* else drop out for careful subtract  */
4003         }
4004       }
4005 
4006     /* Now align (pad) the lhs or rhs so they can be added or  */
4007     /* subtracted, as necessary.  If one number is much larger than  */
4008     /* the other (that is, if in plain form there is a least one  */
4009     /* digit between the lowest digit of one and the highest of the  */
4010     /* other) padding with up to DIGITS-1 trailing zeros may be  */
4011     /* needed; then apply rounding (as exotic rounding modes may be  */
4012     /* affected by the residue).  */
4013     rhsshift=0;               /* rhs shift to left (padding) in Units  */
4014     bits=lhs->bits;           /* assume sign is that of LHS  */
4015     mult=1;                   /* likely multiplier  */
4016 
4017     /* [if padding==0 the operands are aligned; no padding is needed]  */
4018     if (padding!=0) {
4019       /* some padding needed; always pad the RHS, as any required  */
4020       /* padding can then be effected by a simple combination of  */
4021       /* shifts and a multiply  */
4022       Flag swapped=0;
4023       if (padding<0) {                  /* LHS needs the padding  */
4024         const decNumber *t;
4025         padding=-padding;               /* will be +ve  */
4026         bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS  */
4027         t=lhs; lhs=rhs; rhs=t;
4028         swapped=1;
4029         }
4030 
4031       /* If, after pad, rhs would be longer than lhs by digits+1 or  */
4032       /* more then lhs cannot affect the answer, except as a residue,  */
4033       /* so only need to pad up to a length of DIGITS+1.  */
4034       if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4035         /* The RHS is sufficient  */
4036         /* for residue use the relative sign indication...  */
4037         Int shift=reqdigits-rhs->digits;     /* left shift needed  */
4038         residue=1;                           /* residue for rounding  */
4039         if (diffsign) residue=-residue;      /* signs differ  */
4040         /* copy, shortening if necessary  */
4041         decCopyFit(res, rhs, set, &residue, status);
4042         /* if it was already shorter, then need to pad with zeros  */
4043         if (shift>0) {
4044           res->digits=decShiftToMost(res->lsu, res->digits, shift);
4045           res->exponent-=shift;              /* adjust the exponent.  */
4046           }
4047         /* flip the result sign if unswapped and rhs was negated  */
4048         if (!swapped) res->bits^=negate;
4049         decFinish(res, set, &residue, status);    /* done  */
4050         break;}
4051 
4052       /* LHS digits may affect result  */
4053       rhsshift=D2U(padding+1)-1;        /* this much by Unit shift ..  */
4054       mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication  */
4055       } /* padding needed  */
4056 
4057     if (diffsign) mult=-mult;           /* signs differ  */
4058 
4059     /* determine the longer operand  */
4060     maxdigits=rhs->digits+padding;      /* virtual length of RHS  */
4061     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4062 
4063     /* Decide on the result buffer to use; if possible place directly  */
4064     /* into result.  */
4065     acc=res->lsu;                       /* assume add direct to result  */
4066     /* If destructive overlap, or the number is too long, or a carry or  */
4067     /* borrow to DIGITS+1 might be possible, a buffer must be used.  */
4068     /* [Might be worth more sophisticated tests when maxdigits==reqdigits]  */
4069     if ((maxdigits>=reqdigits)          /* is, or could be, too large  */
4070      || (res==rhs && rhsshift>0)) {     /* destructive overlap  */
4071       /* buffer needed, choose it; units for maxdigits digits will be  */
4072       /* needed, +1 Unit for carry or borrow  */
4073       Int need=D2U(maxdigits)+1;
4074       acc=accbuff;                      /* assume use local buffer  */
4075       if (need*sizeof(Unit)>sizeof(accbuff)) {
4076         /* printf("malloc add %ld %ld\n", need, sizeof(accbuff));  */
4077         allocacc=(Unit *)malloc(need*sizeof(Unit));
4078         if (allocacc==NULL) {           /* hopeless -- abandon  */
4079           *status|=DEC_Insufficient_storage;
4080           break;}
4081         acc=allocacc;
4082         }
4083       }
4084 
4085     res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite..  */
4086     res->exponent=lhs->exponent;        /* .. operands (even if aliased)  */
4087 
4088     #if DECTRACE
4089       decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4090       decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4091       printf("  :h: %ld %ld\n", rhsshift, mult);
4092     #endif
4093 
4094     /* add [A+B*m] or subtract [A+B*(-m)]  */
4095     U_ASSERT(rhs->digits > 0);
4096     U_ASSERT(lhs->digits > 0);
4097     res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4098                               rhs->lsu, D2U(rhs->digits),
4099                               rhsshift, acc, mult)
4100                *DECDPUN;           /* [units -> digits]  */
4101     if (res->digits<0) {           /* borrowed...  */
4102       res->digits=-res->digits;
4103       res->bits^=DECNEG;           /* flip the sign  */
4104       }
4105     #if DECTRACE
4106       decDumpAr('+', acc, D2U(res->digits));
4107     #endif
4108 
4109     /* If a buffer was used the result must be copied back, possibly  */
4110     /* shortening.  (If no buffer was used then the result must have  */
4111     /* fit, so can't need rounding and residue must be 0.)  */
4112     residue=0;                     /* clear accumulator  */
4113     if (acc!=res->lsu) {
4114       #if DECSUBSET
4115       if (set->extended) {         /* round from first significant digit  */
4116       #endif
4117         /* remove leading zeros that were added due to rounding up to  */
4118         /* integral Units -- before the test for rounding.  */
4119         if (res->digits>reqdigits)
4120           res->digits=decGetDigits(acc, D2U(res->digits));
4121         decSetCoeff(res, set, acc, res->digits, &residue, status);
4122       #if DECSUBSET
4123         }
4124        else { /* subset arithmetic rounds from original significant digit  */
4125         /* May have an underestimate.  This only occurs when both  */
4126         /* numbers fit in DECDPUN digits and are padding with a  */
4127         /* negative multiple (-10, -100...) and the top digit(s) become  */
4128         /* 0.  (This only matters when using X3.274 rules where the  */
4129         /* leading zero could be included in the rounding.)  */
4130         if (res->digits<maxdigits) {
4131           *(acc+D2U(res->digits))=0; /* ensure leading 0 is there  */
4132           res->digits=maxdigits;
4133           }
4134          else {
4135           /* remove leading zeros that added due to rounding up to  */
4136           /* integral Units (but only those in excess of the original  */
4137           /* maxdigits length, unless extended) before test for rounding.  */
4138           if (res->digits>reqdigits) {
4139             res->digits=decGetDigits(acc, D2U(res->digits));
4140             if (res->digits<maxdigits) res->digits=maxdigits;
4141             }
4142           }
4143         decSetCoeff(res, set, acc, res->digits, &residue, status);
4144         /* Now apply rounding if needed before removing leading zeros.  */
4145         /* This is safe because subnormals are not a possibility  */
4146         if (residue!=0) {
4147           decApplyRound(res, set, residue, status);
4148           residue=0;                 /* did what needed to be done  */
4149           }
4150         } /* subset  */
4151       #endif
4152       } /* used buffer  */
4153 
4154     /* strip leading zeros [these were left on in case of subset subtract]  */
4155     res->digits=decGetDigits(res->lsu, D2U(res->digits));
4156 
4157     /* apply checks and rounding  */
4158     decFinish(res, set, &residue, status);
4159 
4160     /* "When the sum of two operands with opposite signs is exactly  */
4161     /* zero, the sign of that sum shall be '+' in all rounding modes  */
4162     /* except round toward -Infinity, in which mode that sign shall be  */
4163     /* '-'."  [Subset zeros also never have '-', set by decFinish.]  */
4164     if (ISZERO(res) && diffsign
4165      #if DECSUBSET
4166      && set->extended
4167      #endif
4168      && (*status&DEC_Inexact)==0) {
4169       if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign -  */
4170                                   else res->bits&=~DECNEG;  /* sign +  */
4171       }
4172     } while(0);                              /* end protected  */
4173 
4174   if (allocacc!=NULL) free(allocacc);        /* drop any storage used  */
4175   #if DECSUBSET
4176   if (allocrhs!=NULL) free(allocrhs);        /* ..  */
4177   if (alloclhs!=NULL) free(alloclhs);        /* ..  */
4178   #endif
4179   return res;
4180   } /* decAddOp  */
4181 
4182 /* ------------------------------------------------------------------ */
4183 /* decDivideOp -- division operation                                  */
4184 /*                                                                    */
4185 /*  This routine performs the calculations for all four division      */
4186 /*  operators (divide, divideInteger, remainder, remainderNear).      */
4187 /*                                                                    */
4188 /*  C=A op B                                                          */
4189 /*                                                                    */
4190 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4191 /*   lhs is A                                                         */
4192 /*   rhs is B                                                         */
4193 /*   set is the context                                               */
4194 /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4195 /*   status is the usual accumulator                                  */
4196 /*                                                                    */
4197 /* C must have space for set->digits digits.                          */
4198 /*                                                                    */
4199 /* ------------------------------------------------------------------ */
4200 /*   The underlying algorithm of this routine is the same as in the   */
4201 /*   1981 S/370 implementation, that is, non-restoring long division  */
4202 /*   with bi-unit (rather than bi-digit) estimation for each unit     */
4203 /*   multiplier.  In this pseudocode overview, complications for the  */
4204 /*   Remainder operators and division residues for exact rounding are */
4205 /*   omitted for clarity.                                             */
4206 /*                                                                    */
4207 /*     Prepare operands and handle special values                     */
4208 /*     Test for x/0 and then 0/x                                      */
4209 /*     Exp =Exp1 - Exp2                                               */
4210 /*     Exp =Exp +len(var1) -len(var2)                                 */
4211 /*     Sign=Sign1 * Sign2                                             */
4212 /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4213 /*     Pad Var2 to same length as Var1                                */
4214 /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4215 /*     have=0                                                         */
4216 /*     Do until (have=digits+1 OR residue=0)                          */
4217 /*       if exp<0 then if integer divide/residue then leave           */
4218 /*       this_unit=0                                                  */
4219 /*       Do forever                                                   */
4220 /*          compare numbers                                           */
4221 /*          if <0 then leave inner_loop                               */
4222 /*          if =0 then (* quick exit without subtract *) do           */
4223 /*             this_unit=this_unit+1; output this_unit                */
4224 /*             leave outer_loop; end                                  */
4225 /*          Compare lengths of numbers (mantissae):                   */
4226 /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4227 /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4228 /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4229 /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4230 /*          if mult=0 then mult=1                                     */
4231 /*          this_unit=this_unit+mult                                  */
4232 /*          subtract                                                  */
4233 /*          end inner_loop                                            */
4234 /*        if have\=0 | this_unit\=0 then do                           */
4235 /*          output this_unit                                          */
4236 /*          have=have+1; end                                          */
4237 /*        var2=var2/10                                                */
4238 /*        exp=exp-1                                                   */
4239 /*        end outer_loop                                              */
4240 /*     exp=exp+1   -- set the proper exponent                         */
4241 /*     if have=0 then generate answer=0                               */
4242 /*     Return (Result is defined by Var1)                             */
4243 /*                                                                    */
4244 /* ------------------------------------------------------------------ */
4245 /* Two working buffers are needed during the division; one (digits+   */
4246 /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4247 /* long subtractions.  These are acc and var1 respectively.           */
4248 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4249 /* The static buffers may be larger than might be expected to allow   */
4250 /* for calls from higher-level funtions (notable exp).                */
4251 /* ------------------------------------------------------------------ */
decDivideOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,Flag op,uInt * status)4252 static decNumber * decDivideOp(decNumber *res,
4253                                const decNumber *lhs, const decNumber *rhs,
4254                                decContext *set, Flag op, uInt *status) {
4255   #if DECSUBSET
4256   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
4257   decNumber *allocrhs=NULL;        /* .., rhs  */
4258   #endif
4259   Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer  */
4260   Unit  *acc=accbuff;              /* -> accumulator array for result  */
4261   Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated  */
4262   Unit  *accnext;                  /* -> where next digit will go  */
4263   Int   acclength;                 /* length of acc needed [Units]  */
4264   Int   accunits;                  /* count of units accumulated  */
4265   Int   accdigits;                 /* count of digits accumulated  */
4266 
4267   Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  /* buffer for var1  */
4268   Unit  *var1=varbuff;             /* -> var1 array for long subtraction  */
4269   Unit  *varalloc=NULL;            /* -> allocated buffer, iff used  */
4270   Unit  *msu1;                     /* -> msu of var1  */
4271 
4272   const Unit *var2;                /* -> var2 array  */
4273   const Unit *msu2;                /* -> msu of var2  */
4274   Int   msu2plus;                  /* msu2 plus one [does not vary]  */
4275   eInt  msu2pair;                  /* msu2 pair plus one [does not vary]  */
4276 
4277   Int   var1units, var2units;      /* actual lengths  */
4278   Int   var2ulen;                  /* logical length (units)  */
4279   Int   var1initpad=0;             /* var1 initial padding (digits)  */
4280   Int   maxdigits;                 /* longest LHS or required acc length  */
4281   Int   mult;                      /* multiplier for subtraction  */
4282   Unit  thisunit;                  /* current unit being accumulated  */
4283   Int   residue;                   /* for rounding  */
4284   Int   reqdigits=set->digits;     /* requested DIGITS  */
4285   Int   exponent;                  /* working exponent  */
4286   Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded  */
4287   uByte bits;                      /* working sign  */
4288   Unit  *target;                   /* work  */
4289   const Unit *source;              /* ..  */
4290   uInt  const *pow;                /* ..  */
4291   Int   shift, cut;                /* ..  */
4292   #if DECSUBSET
4293   Int   dropped;                   /* work  */
4294   #endif
4295 
4296   #if DECCHECK
4297   if (decCheckOperands(res, lhs, rhs, set)) return res;
4298   #endif
4299 
4300   do {                             /* protect allocated storage  */
4301     #if DECSUBSET
4302     if (!set->extended) {
4303       /* reduce operands and set lostDigits status, as needed  */
4304       if (lhs->digits>reqdigits) {
4305         alloclhs=decRoundOperand(lhs, set, status);
4306         if (alloclhs==NULL) break;
4307         lhs=alloclhs;
4308         }
4309       if (rhs->digits>reqdigits) {
4310         allocrhs=decRoundOperand(rhs, set, status);
4311         if (allocrhs==NULL) break;
4312         rhs=allocrhs;
4313         }
4314       }
4315     #endif
4316     /* [following code does not require input rounding]  */
4317 
4318     bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions  */
4319 
4320     /* handle infinities and NaNs  */
4321     if (SPECIALARGS) {                  /* a special bit set  */
4322       if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4323         decNaNs(res, lhs, rhs, set, status);
4324         break;
4325         }
4326       /* one or two infinities  */
4327       if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite  */
4328         if (decNumberIsInfinite(rhs) || /* two infinities are invalid ..  */
4329             op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity  */
4330           *status|=DEC_Invalid_operation;
4331           break;
4332           }
4333         /* [Note that infinity/0 raises no exceptions]  */
4334         uprv_decNumberZero(res);
4335         res->bits=bits|DECINF;          /* set +/- infinity  */
4336         break;
4337         }
4338        else {                           /* RHS (divisor) is infinite  */
4339         residue=0;
4340         if (op&(REMAINDER|REMNEAR)) {
4341           /* result is [finished clone of] lhs  */
4342           decCopyFit(res, lhs, set, &residue, status);
4343           }
4344          else {  /* a division  */
4345           uprv_decNumberZero(res);
4346           res->bits=bits;               /* set +/- zero  */
4347           /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result  */
4348           /* is a 0 with infinitely negative exponent, clamped to minimum  */
4349           if (op&DIVIDE) {
4350             res->exponent=set->emin-set->digits+1;
4351             *status|=DEC_Clamped;
4352             }
4353           }
4354         decFinish(res, set, &residue, status);
4355         break;
4356         }
4357       }
4358 
4359     /* handle 0 rhs (x/0)  */
4360     if (ISZERO(rhs)) {                  /* x/0 is always exceptional  */
4361       if (ISZERO(lhs)) {
4362         uprv_decNumberZero(res);             /* [after lhs test]  */
4363         *status|=DEC_Division_undefined;/* 0/0 will become NaN  */
4364         }
4365        else {
4366         uprv_decNumberZero(res);
4367         if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4368          else {
4369           *status|=DEC_Division_by_zero; /* x/0  */
4370           res->bits=bits|DECINF;         /* .. is +/- Infinity  */
4371           }
4372         }
4373       break;}
4374 
4375     /* handle 0 lhs (0/x)  */
4376     if (ISZERO(lhs)) {                  /* 0/x [x!=0]  */
4377       #if DECSUBSET
4378       if (!set->extended) uprv_decNumberZero(res);
4379        else {
4380       #endif
4381         if (op&DIVIDE) {
4382           residue=0;
4383           exponent=lhs->exponent-rhs->exponent; /* ideal exponent  */
4384           uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4385           res->bits=bits;               /* sign as computed  */
4386           res->exponent=exponent;       /* exponent, too  */
4387           decFinalize(res, set, &residue, status);   /* check exponent  */
4388           }
4389          else if (op&DIVIDEINT) {
4390           uprv_decNumberZero(res);           /* integer 0  */
4391           res->bits=bits;               /* sign as computed  */
4392           }
4393          else {                         /* a remainder  */
4394           exponent=rhs->exponent;       /* [save in case overwrite]  */
4395           uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4396           if (exponent<res->exponent) res->exponent=exponent; /* use lower  */
4397           }
4398       #if DECSUBSET
4399         }
4400       #endif
4401       break;}
4402 
4403     /* Precalculate exponent.  This starts off adjusted (and hence fits  */
4404     /* in 31 bits) and becomes the usual unadjusted exponent as the  */
4405     /* division proceeds.  The order of evaluation is important, here,  */
4406     /* to avoid wrap.  */
4407     exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4408 
4409     /* If the working exponent is -ve, then some quick exits are  */
4410     /* possible because the quotient is known to be <1  */
4411     /* [for REMNEAR, it needs to be < -1, as -0.5 could need work]  */
4412     if (exponent<0 && !(op==DIVIDE)) {
4413       if (op&DIVIDEINT) {
4414         uprv_decNumberZero(res);                  /* integer part is 0  */
4415         #if DECSUBSET
4416         if (set->extended)
4417         #endif
4418           res->bits=bits;                    /* set +/- zero  */
4419         break;}
4420       /* fastpath remainders so long as the lhs has the smaller  */
4421       /* (or equal) exponent  */
4422       if (lhs->exponent<=rhs->exponent) {
4423         if (op&REMAINDER || exponent<-1) {
4424           /* It is REMAINDER or safe REMNEAR; result is [finished  */
4425           /* clone of] lhs  (r = x - 0*y)  */
4426           residue=0;
4427           decCopyFit(res, lhs, set, &residue, status);
4428           decFinish(res, set, &residue, status);
4429           break;
4430           }
4431         /* [unsafe REMNEAR drops through]  */
4432         }
4433       } /* fastpaths  */
4434 
4435     /* Long (slow) division is needed; roll up the sleeves... */
4436 
4437     /* The accumulator will hold the quotient of the division.  */
4438     /* If it needs to be too long for stack storage, then allocate.  */
4439     acclength=D2U(reqdigits+DECDPUN);   /* in Units  */
4440     if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4441       /* printf("malloc dvacc %ld units\n", acclength);  */
4442       allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4443       if (allocacc==NULL) {             /* hopeless -- abandon  */
4444         *status|=DEC_Insufficient_storage;
4445         break;}
4446       acc=allocacc;                     /* use the allocated space  */
4447       }
4448 
4449     /* var1 is the padded LHS ready for subtractions.  */
4450     /* If it needs to be too long for stack storage, then allocate.  */
4451     /* The maximum units needed for var1 (long subtraction) is:  */
4452     /* Enough for  */
4453     /*     (rhs->digits+reqdigits-1) -- to allow full slide to right  */
4454     /* or  (lhs->digits)             -- to allow for long lhs  */
4455     /* whichever is larger  */
4456     /*   +1                -- for rounding of slide to right  */
4457     /*   +1                -- for leading 0s  */
4458     /*   +1                -- for pre-adjust if a remainder or DIVIDEINT  */
4459     /* [Note: unused units do not participate in decUnitAddSub data]  */
4460     maxdigits=rhs->digits+reqdigits-1;
4461     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4462     var1units=D2U(maxdigits)+2;
4463     /* allocate a guard unit above msu1 for REMAINDERNEAR  */
4464     if (!(op&DIVIDE)) var1units++;
4465     if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4466       /* printf("malloc dvvar %ld units\n", var1units+1);  */
4467       varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4468       if (varalloc==NULL) {             /* hopeless -- abandon  */
4469         *status|=DEC_Insufficient_storage;
4470         break;}
4471       var1=varalloc;                    /* use the allocated space  */
4472       }
4473 
4474     /* Extend the lhs and rhs to full long subtraction length.  The lhs  */
4475     /* is truly extended into the var1 buffer, with 0 padding, so a  */
4476     /* subtract in place is always possible.  The rhs (var2) has  */
4477     /* virtual padding (implemented by decUnitAddSub).  */
4478     /* One guard unit was allocated above msu1 for rem=rem+rem in  */
4479     /* REMAINDERNEAR.  */
4480     msu1=var1+var1units-1;              /* msu of var1  */
4481     source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array  */
4482     for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4483     for (; target>=var1; target--) *target=0;
4484 
4485     /* rhs (var2) is left-aligned with var1 at the start  */
4486     var2ulen=var1units;                 /* rhs logical length (units)  */
4487     var2units=D2U(rhs->digits);         /* rhs actual length (units)  */
4488     var2=rhs->lsu;                      /* -> rhs array  */
4489     msu2=var2+var2units-1;              /* -> msu of var2 [never changes]  */
4490     /* now set up the variables which will be used for estimating the  */
4491     /* multiplication factor.  If these variables are not exact, add  */
4492     /* 1 to make sure that the multiplier is never overestimated.  */
4493     msu2plus=*msu2;                     /* it's value ..  */
4494     if (var2units>1) msu2plus++;        /* .. +1 if any more  */
4495     msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair ..  */
4496     if (var2units>1) {                  /* .. [else treat 2nd as 0]  */
4497       msu2pair+=*(msu2-1);              /* ..  */
4498       if (var2units>2) msu2pair++;      /* .. +1 if any more  */
4499       }
4500 
4501     /* The calculation is working in units, which may have leading zeros,  */
4502     /* but the exponent was calculated on the assumption that they are  */
4503     /* both left-aligned.  Adjust the exponent to compensate: add the  */
4504     /* number of leading zeros in var1 msu and subtract those in var2 msu.  */
4505     /* [This is actually done by counting the digits and negating, as  */
4506     /* lead1=DECDPUN-digits1, and similarly for lead2.]  */
4507     for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4508     for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4509 
4510     /* Now, if doing an integer divide or remainder, ensure that  */
4511     /* the result will be Unit-aligned.  To do this, shift the var1  */
4512     /* accumulator towards least if need be.  (It's much easier to  */
4513     /* do this now than to reassemble the residue afterwards, if  */
4514     /* doing a remainder.)  Also ensure the exponent is not negative.  */
4515     if (!(op&DIVIDE)) {
4516       Unit *u;                          /* work  */
4517       /* save the initial 'false' padding of var1, in digits  */
4518       var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4519       /* Determine the shift to do.  */
4520       if (exponent<0) cut=-exponent;
4521        else cut=DECDPUN-exponent%DECDPUN;
4522       decShiftToLeast(var1, var1units, cut);
4523       exponent+=cut;                    /* maintain numerical value  */
4524       var1initpad-=cut;                 /* .. and reduce padding  */
4525       /* clean any most-significant units which were just emptied  */
4526       for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4527       } /* align  */
4528      else { /* is DIVIDE  */
4529       maxexponent=lhs->exponent-rhs->exponent;    /* save  */
4530       /* optimization: if the first iteration will just produce 0,  */
4531       /* preadjust to skip it [valid for DIVIDE only]  */
4532       if (*msu1<*msu2) {
4533         var2ulen--;                     /* shift down  */
4534         exponent-=DECDPUN;              /* update the exponent  */
4535         }
4536       }
4537 
4538     /* ---- start the long-division loops ------------------------------  */
4539     accunits=0;                         /* no units accumulated yet  */
4540     accdigits=0;                        /* .. or digits  */
4541     accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1]  */
4542     for (;;) {                          /* outer forever loop  */
4543       thisunit=0;                       /* current unit assumed 0  */
4544       /* find the next unit  */
4545       for (;;) {                        /* inner forever loop  */
4546         /* strip leading zero units [from either pre-adjust or from  */
4547         /* subtract last time around].  Leave at least one unit.  */
4548         for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4549 
4550         if (var1units<var2ulen) break;       /* var1 too low for subtract  */
4551         if (var1units==var2ulen) {           /* unit-by-unit compare needed  */
4552           /* compare the two numbers, from msu  */
4553           const Unit *pv1, *pv2;
4554           Unit v2;                           /* units to compare  */
4555           pv2=msu2;                          /* -> msu  */
4556           for (pv1=msu1; ; pv1--, pv2--) {
4557             /* v1=*pv1 -- always OK  */
4558             v2=0;                            /* assume in padding  */
4559             if (pv2>=var2) v2=*pv2;          /* in range  */
4560             if (*pv1!=v2) break;             /* no longer the same  */
4561             if (pv1==var1) break;            /* done; leave pv1 as is  */
4562             }
4563           /* here when all inspected or a difference seen  */
4564           if (*pv1<v2) break;                /* var1 too low to subtract  */
4565           if (*pv1==v2) {                    /* var1 == var2  */
4566             /* reach here if var1 and var2 are identical; subtraction  */
4567             /* would increase digit by one, and the residue will be 0 so  */
4568             /* the calculation is done; leave the loop with residue=0.  */
4569             thisunit++;                      /* as though subtracted  */
4570             *var1=0;                         /* set var1 to 0  */
4571             var1units=1;                     /* ..  */
4572             break;  /* from inner  */
4573             } /* var1 == var2  */
4574           /* *pv1>v2.  Prepare for real subtraction; the lengths are equal  */
4575           /* Estimate the multiplier (there's always a msu1-1)...  */
4576           /* Bring in two units of var2 to provide a good estimate.  */
4577           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4578           } /* lengths the same  */
4579          else { /* var1units > var2ulen, so subtraction is safe  */
4580           /* The var2 msu is one unit towards the lsu of the var1 msu,  */
4581           /* so only one unit for var2 can be used.  */
4582           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4583           }
4584         if (mult==0) mult=1;                 /* must always be at least 1  */
4585         /* subtraction needed; var1 is > var2  */
4586         thisunit=(Unit)(thisunit+mult);      /* accumulate  */
4587         /* subtract var1-var2, into var1; only the overlap needs  */
4588         /* processing, as this is an in-place calculation  */
4589         shift=var2ulen-var2units;
4590         #if DECTRACE
4591           decDumpAr('1', &var1[shift], var1units-shift);
4592           decDumpAr('2', var2, var2units);
4593           printf("m=%ld\n", -mult);
4594         #endif
4595         decUnitAddSub(&var1[shift], var1units-shift,
4596                       var2, var2units, 0,
4597                       &var1[shift], -mult);
4598         #if DECTRACE
4599           decDumpAr('#', &var1[shift], var1units-shift);
4600         #endif
4601         /* var1 now probably has leading zeros; these are removed at the  */
4602         /* top of the inner loop.  */
4603         } /* inner loop  */
4604 
4605       /* The next unit has been calculated in full; unless it's a  */
4606       /* leading zero, add to acc  */
4607       if (accunits!=0 || thisunit!=0) {      /* is first or non-zero  */
4608         *accnext=thisunit;                   /* store in accumulator  */
4609         /* account exactly for the new digits  */
4610         if (accunits==0) {
4611           accdigits++;                       /* at least one  */
4612           for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4613           }
4614          else accdigits+=DECDPUN;
4615         accunits++;                          /* update count  */
4616         accnext--;                           /* ready for next  */
4617         if (accdigits>reqdigits) break;      /* have enough digits  */
4618         }
4619 
4620       /* if the residue is zero, the operation is done (unless divide  */
4621       /* or divideInteger and still not enough digits yet)  */
4622       if (*var1==0 && var1units==1) {        /* residue is 0  */
4623         if (op&(REMAINDER|REMNEAR)) break;
4624         if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4625         /* [drop through if divideInteger]  */
4626         }
4627       /* also done enough if calculating remainder or integer  */
4628       /* divide and just did the last ('units') unit  */
4629       if (exponent==0 && !(op&DIVIDE)) break;
4630 
4631       /* to get here, var1 is less than var2, so divide var2 by the per-  */
4632       /* Unit power of ten and go for the next digit  */
4633       var2ulen--;                            /* shift down  */
4634       exponent-=DECDPUN;                     /* update the exponent  */
4635       } /* outer loop  */
4636 
4637     /* ---- division is complete ---------------------------------------  */
4638     /* here: acc      has at least reqdigits+1 of good results (or fewer  */
4639     /*                if early stop), starting at accnext+1 (its lsu)  */
4640     /*       var1     has any residue at the stopping point  */
4641     /*       accunits is the number of digits collected in acc  */
4642     if (accunits==0) {             /* acc is 0  */
4643       accunits=1;                  /* show have a unit ..  */
4644       accdigits=1;                 /* ..  */
4645       *accnext=0;                  /* .. whose value is 0  */
4646       }
4647      else accnext++;               /* back to last placed  */
4648     /* accnext now -> lowest unit of result  */
4649 
4650     residue=0;                     /* assume no residue  */
4651     if (op&DIVIDE) {
4652       /* record the presence of any residue, for rounding  */
4653       if (*var1!=0 || var1units>1) residue=1;
4654        else { /* no residue  */
4655         /* Had an exact division; clean up spurious trailing 0s.  */
4656         /* There will be at most DECDPUN-1, from the final multiply,  */
4657         /* and then only if the result is non-0 (and even) and the  */
4658         /* exponent is 'loose'.  */
4659         #if DECDPUN>1
4660         Unit lsu=*accnext;
4661         if (!(lsu&0x01) && (lsu!=0)) {
4662           /* count the trailing zeros  */
4663           Int drop=0;
4664           for (;; drop++) {    /* [will terminate because lsu!=0]  */
4665             if (exponent>=maxexponent) break;     /* don't chop real 0s  */
4666             #if DECDPUN<=4
4667               if ((lsu-QUOT10(lsu, drop+1)
4668                   *powers[drop+1])!=0) break;     /* found non-0 digit  */
4669             #else
4670               if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit  */
4671             #endif
4672             exponent++;
4673             }
4674           if (drop>0) {
4675             accunits=decShiftToLeast(accnext, accunits, drop);
4676             accdigits=decGetDigits(accnext, accunits);
4677             accunits=D2U(accdigits);
4678             /* [exponent was adjusted in the loop]  */
4679             }
4680           } /* neither odd nor 0  */
4681         #endif
4682         } /* exact divide  */
4683       } /* divide  */
4684      else /* op!=DIVIDE */ {
4685       /* check for coefficient overflow  */
4686       if (accdigits+exponent>reqdigits) {
4687         *status|=DEC_Division_impossible;
4688         break;
4689         }
4690       if (op & (REMAINDER|REMNEAR)) {
4691         /* [Here, the exponent will be 0, because var1 was adjusted  */
4692         /* appropriately.]  */
4693         Int postshift;                       /* work  */
4694         Flag wasodd=0;                       /* integer was odd  */
4695         Unit *quotlsu;                       /* for save  */
4696         Int  quotdigits;                     /* ..  */
4697 
4698         bits=lhs->bits;                      /* remainder sign is always as lhs  */
4699 
4700         /* Fastpath when residue is truly 0 is worthwhile [and  */
4701         /* simplifies the code below]  */
4702         if (*var1==0 && var1units==1) {      /* residue is 0  */
4703           Int exp=lhs->exponent;             /* save min(exponents)  */
4704           if (rhs->exponent<exp) exp=rhs->exponent;
4705           uprv_decNumberZero(res);                /* 0 coefficient  */
4706           #if DECSUBSET
4707           if (set->extended)
4708           #endif
4709           res->exponent=exp;                 /* .. with proper exponent  */
4710           res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4711           decFinish(res, set, &residue, status);   /* might clamp  */
4712           break;
4713           }
4714         /* note if the quotient was odd  */
4715         if (*accnext & 0x01) wasodd=1;       /* acc is odd  */
4716         quotlsu=accnext;                     /* save in case need to reinspect  */
4717         quotdigits=accdigits;                /* ..  */
4718 
4719         /* treat the residue, in var1, as the value to return, via acc  */
4720         /* calculate the unused zero digits.  This is the smaller of:  */
4721         /*   var1 initial padding (saved above)  */
4722         /*   var2 residual padding, which happens to be given by:  */
4723         postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4724         /* [the 'exponent' term accounts for the shifts during divide]  */
4725         if (var1initpad<postshift) postshift=var1initpad;
4726 
4727         /* shift var1 the requested amount, and adjust its digits  */
4728         var1units=decShiftToLeast(var1, var1units, postshift);
4729         accnext=var1;
4730         accdigits=decGetDigits(var1, var1units);
4731         accunits=D2U(accdigits);
4732 
4733         exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs  */
4734         if (rhs->exponent<exponent) exponent=rhs->exponent;
4735 
4736         /* Now correct the result if doing remainderNear; if it  */
4737         /* (looking just at coefficients) is > rhs/2, or == rhs/2 and  */
4738         /* the integer was odd then the result should be rem-rhs.  */
4739         if (op&REMNEAR) {
4740           Int compare, tarunits;        /* work  */
4741           Unit *up;                     /* ..  */
4742           /* calculate remainder*2 into the var1 buffer (which has  */
4743           /* 'headroom' of an extra unit and hence enough space)  */
4744           /* [a dedicated 'double' loop would be faster, here]  */
4745           tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4746                                  0, accnext, 1);
4747           /* decDumpAr('r', accnext, tarunits);  */
4748 
4749           /* Here, accnext (var1) holds tarunits Units with twice the  */
4750           /* remainder's coefficient, which must now be compared to the  */
4751           /* RHS.  The remainder's exponent may be smaller than the RHS's.  */
4752           compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4753                                  rhs->exponent-exponent);
4754           if (compare==BADINT) {             /* deep trouble  */
4755             *status|=DEC_Insufficient_storage;
4756             break;}
4757 
4758           /* now restore the remainder by dividing by two; the lsu  */
4759           /* is known to be even.  */
4760           for (up=accnext; up<accnext+tarunits; up++) {
4761             Int half;              /* half to add to lower unit  */
4762             half=*up & 0x01;
4763             *up/=2;                /* [shift]  */
4764             if (!half) continue;
4765             *(up-1)+=(DECDPUNMAX+1)/2;
4766             }
4767           /* [accunits still describes the original remainder length]  */
4768 
4769           if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed  */
4770             Int exp, expunits, exprem;       /* work  */
4771             /* This is effectively causing round-up of the quotient,  */
4772             /* so if it was the rare case where it was full and all  */
4773             /* nines, it would overflow and hence division-impossible  */
4774             /* should be raised  */
4775             Flag allnines=0;                 /* 1 if quotient all nines  */
4776             if (quotdigits==reqdigits) {     /* could be borderline  */
4777               for (up=quotlsu; ; up++) {
4778                 if (quotdigits>DECDPUN) {
4779                   if (*up!=DECDPUNMAX) break;/* non-nines  */
4780                   }
4781                  else {                      /* this is the last Unit  */
4782                   if (*up==powers[quotdigits]-1) allnines=1;
4783                   break;
4784                   }
4785                 quotdigits-=DECDPUN;         /* checked those digits  */
4786                 } /* up  */
4787               } /* borderline check  */
4788             if (allnines) {
4789               *status|=DEC_Division_impossible;
4790               break;}
4791 
4792             /* rem-rhs is needed; the sign will invert.  Again, var1  */
4793             /* can safely be used for the working Units array.  */
4794             exp=rhs->exponent-exponent;      /* RHS padding needed  */
4795             /* Calculate units and remainder from exponent.  */
4796             expunits=exp/DECDPUN;
4797             exprem=exp%DECDPUN;
4798             /* subtract [A+B*(-m)]; the result will always be negative  */
4799             accunits=-decUnitAddSub(accnext, accunits,
4800                                     rhs->lsu, D2U(rhs->digits),
4801                                     expunits, accnext, -(Int)powers[exprem]);
4802             accdigits=decGetDigits(accnext, accunits); /* count digits exactly  */
4803             accunits=D2U(accdigits);    /* and recalculate the units for copy  */
4804             /* [exponent is as for original remainder]  */
4805             bits^=DECNEG;               /* flip the sign  */
4806             }
4807           } /* REMNEAR  */
4808         } /* REMAINDER or REMNEAR  */
4809       } /* not DIVIDE  */
4810 
4811     /* Set exponent and bits  */
4812     res->exponent=exponent;
4813     res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4814 
4815     /* Now the coefficient.  */
4816     decSetCoeff(res, set, accnext, accdigits, &residue, status);
4817 
4818     decFinish(res, set, &residue, status);   /* final cleanup  */
4819 
4820     #if DECSUBSET
4821     /* If a divide then strip trailing zeros if subset [after round]  */
4822     if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4823     #endif
4824     } while(0);                              /* end protected  */
4825 
4826   if (varalloc!=NULL) free(varalloc);   /* drop any storage used  */
4827   if (allocacc!=NULL) free(allocacc);   /* ..  */
4828   #if DECSUBSET
4829   if (allocrhs!=NULL) free(allocrhs);   /* ..  */
4830   if (alloclhs!=NULL) free(alloclhs);   /* ..  */
4831   #endif
4832   return res;
4833   } /* decDivideOp  */
4834 
4835 /* ------------------------------------------------------------------ */
4836 /* decMultiplyOp -- multiplication operation                          */
4837 /*                                                                    */
4838 /*  This routine performs the multiplication C=A x B.                 */
4839 /*                                                                    */
4840 /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4841 /*   lhs is A                                                         */
4842 /*   rhs is B                                                         */
4843 /*   set is the context                                               */
4844 /*   status is the usual accumulator                                  */
4845 /*                                                                    */
4846 /* C must have space for set->digits digits.                          */
4847 /*                                                                    */
4848 /* ------------------------------------------------------------------ */
4849 /* 'Classic' multiplication is used rather than Karatsuba, as the     */
4850 /* latter would give only a minor improvement for the short numbers   */
4851 /* expected to be handled most (and uses much more memory).           */
4852 /*                                                                    */
4853 /* There are two major paths here: the general-purpose ('old code')   */
4854 /* path which handles all DECDPUN values, and a fastpath version      */
4855 /* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4856 /* than two calls to decUnitAddSub would be made.                     */
4857 /*                                                                    */
4858 /* The fastpath version lumps units together into 8-digit or 9-digit  */
4859 /* chunks, and also uses a lazy carry strategy to minimise expensive  */
4860 /* 64-bit divisions.  The chunks are then broken apart again into     */
4861 /* units for continuing processing.  Despite this overhead, the       */
4862 /* fastpath can speed up some 16-digit operations by 10x (and much    */
4863 /* more for higher-precision calculations).                           */
4864 /*                                                                    */
4865 /* A buffer always has to be used for the accumulator; in the         */
4866 /* fastpath, buffers are also always needed for the chunked copies of */
4867 /* of the operand coefficients.                                       */
4868 /* Static buffers are larger than needed just for multiply, to allow  */
4869 /* for calls from other operations (notably exp).                     */
4870 /* ------------------------------------------------------------------ */
4871 #define FASTMUL (DECUSE64 && DECDPUN<5)
decMultiplyOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,uInt * status)4872 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4873                                  const decNumber *rhs, decContext *set,
4874                                  uInt *status) {
4875   Int    accunits;                 /* Units of accumulator in use  */
4876   Int    exponent;                 /* work  */
4877   Int    residue=0;                /* rounding residue  */
4878   uByte  bits;                     /* result sign  */
4879   Unit  *acc;                      /* -> accumulator Unit array  */
4880   Int    needbytes;                /* size calculator  */
4881   void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated  */
4882   Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0,  */
4883                                    /* *4 for calls from other operations)  */
4884   const Unit *mer, *mermsup;       /* work  */
4885   Int   madlength;                 /* Units in multiplicand  */
4886   Int   shift;                     /* Units to shift multiplicand by  */
4887 
4888   #if FASTMUL
4889     /* if DECDPUN is 1 or 3 work in base 10**9, otherwise  */
4890     /* (DECDPUN is 2 or 4) then work in base 10**8  */
4891     #if DECDPUN & 1                /* odd  */
4892       #define FASTBASE 1000000000  /* base  */
4893       #define FASTDIGS          9  /* digits in base  */
4894       #define FASTLAZY         18  /* carry resolution point [1->18]  */
4895     #else
4896       #define FASTBASE  100000000
4897       #define FASTDIGS          8
4898       #define FASTLAZY       1844  /* carry resolution point [1->1844]  */
4899     #endif
4900     /* three buffers are used, two for chunked copies of the operands  */
4901     /* (base 10**8 or base 10**9) and one base 2**64 accumulator with  */
4902     /* lazy carry evaluation  */
4903     uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4904     uInt  *zlhi=zlhibuff;                 /* -> lhs array  */
4905     uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated  */
4906     uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4907     uInt  *zrhi=zrhibuff;                 /* -> rhs array  */
4908     uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated  */
4909     uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0)  */
4910     /* [allocacc is shared for both paths, as only one will run]  */
4911     uLong *zacc=zaccbuff;          /* -> accumulator array for exact result  */
4912     #if DECDPUN==1
4913     Int    zoff;                   /* accumulator offset  */
4914     #endif
4915     uInt  *lip, *rip;              /* item pointers  */
4916     uInt  *lmsi, *rmsi;            /* most significant items  */
4917     Int    ilhs, irhs, iacc;       /* item counts in the arrays  */
4918     Int    lazy;                   /* lazy carry counter  */
4919     uLong  lcarry;                 /* uLong carry  */
4920     uInt   carry;                  /* carry (NB not uLong)  */
4921     Int    count;                  /* work  */
4922     const  Unit *cup;              /* ..  */
4923     Unit  *up;                     /* ..  */
4924     uLong *lp;                     /* ..  */
4925     Int    p;                      /* ..  */
4926   #endif
4927 
4928   #if DECSUBSET
4929     decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated  */
4930     decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated  */
4931   #endif
4932 
4933   #if DECCHECK
4934   if (decCheckOperands(res, lhs, rhs, set)) return res;
4935   #endif
4936 
4937   /* precalculate result sign  */
4938   bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4939 
4940   /* handle infinities and NaNs  */
4941   if (SPECIALARGS) {               /* a special bit set  */
4942     if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4943       decNaNs(res, lhs, rhs, set, status);
4944       return res;}
4945     /* one or two infinities; Infinity * 0 is invalid  */
4946     if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4947       ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4948       *status|=DEC_Invalid_operation;
4949       return res;}
4950     uprv_decNumberZero(res);
4951     res->bits=bits|DECINF;         /* infinity  */
4952     return res;}
4953 
4954   /* For best speed, as in DMSRCN [the original Rexx numerics  */
4955   /* module], use the shorter number as the multiplier (rhs) and  */
4956   /* the longer as the multiplicand (lhs) to minimise the number of  */
4957   /* adds (partial products)  */
4958   if (lhs->digits<rhs->digits) {   /* swap...  */
4959     const decNumber *hold=lhs;
4960     lhs=rhs;
4961     rhs=hold;
4962     }
4963 
4964   do {                             /* protect allocated storage  */
4965     #if DECSUBSET
4966     if (!set->extended) {
4967       /* reduce operands and set lostDigits status, as needed  */
4968       if (lhs->digits>set->digits) {
4969         alloclhs=decRoundOperand(lhs, set, status);
4970         if (alloclhs==NULL) break;
4971         lhs=alloclhs;
4972         }
4973       if (rhs->digits>set->digits) {
4974         allocrhs=decRoundOperand(rhs, set, status);
4975         if (allocrhs==NULL) break;
4976         rhs=allocrhs;
4977         }
4978       }
4979     #endif
4980     /* [following code does not require input rounding]  */
4981 
4982     #if FASTMUL                    /* fastpath can be used  */
4983     /* use the fast path if there are enough digits in the shorter  */
4984     /* operand to make the setup and takedown worthwhile  */
4985     #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls  */
4986     if (rhs->digits>NEEDTWO) {     /* use fastpath...  */
4987       /* calculate the number of elements in each array  */
4988       ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling]  */
4989       irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* ..  */
4990       iacc=ilhs+irhs;
4991 
4992       /* allocate buffers if required, as usual  */
4993       needbytes=ilhs*sizeof(uInt);
4994       if (needbytes>(Int)sizeof(zlhibuff)) {
4995         alloclhi=(uInt *)malloc(needbytes);
4996         zlhi=alloclhi;}
4997       needbytes=irhs*sizeof(uInt);
4998       if (needbytes>(Int)sizeof(zrhibuff)) {
4999         allocrhi=(uInt *)malloc(needbytes);
5000         zrhi=allocrhi;}
5001 
5002       /* Allocating the accumulator space needs a special case when  */
5003       /* DECDPUN=1 because when converting the accumulator to Units  */
5004       /* after the multiplication each 8-byte item becomes 9 1-byte  */
5005       /* units.  Therefore iacc extra bytes are needed at the front  */
5006       /* (rounded up to a multiple of 8 bytes), and the uLong  */
5007       /* accumulator starts offset the appropriate number of units  */
5008       /* to the right to avoid overwrite during the unchunking.  */
5009 
5010       /* Make sure no signed int overflow below. This is always true */
5011       /* if the given numbers have less digits than DEC_MAX_DIGITS. */
5012       U_ASSERT((uint32_t)iacc <= INT32_MAX/sizeof(uLong));
5013       needbytes=iacc*sizeof(uLong);
5014       #if DECDPUN==1
5015       zoff=(iacc+7)/8;        /* items to offset by  */
5016       needbytes+=zoff*8;
5017       #endif
5018       if (needbytes>(Int)sizeof(zaccbuff)) {
5019         allocacc=(uLong *)malloc(needbytes);
5020         zacc=(uLong *)allocacc;}
5021       if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
5022         *status|=DEC_Insufficient_storage;
5023         break;}
5024 
5025       acc=(Unit *)zacc;       /* -> target Unit array  */
5026       #if DECDPUN==1
5027       zacc+=zoff;             /* start uLong accumulator to right  */
5028       #endif
5029 
5030       /* assemble the chunked copies of the left and right sides  */
5031       for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5032         for (p=0, *lip=0; p<FASTDIGS && count>0;
5033              p+=DECDPUN, cup++, count-=DECDPUN)
5034           *lip+=*cup*powers[p];
5035       lmsi=lip-1;     /* save -> msi  */
5036       for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5037         for (p=0, *rip=0; p<FASTDIGS && count>0;
5038              p+=DECDPUN, cup++, count-=DECDPUN)
5039           *rip+=*cup*powers[p];
5040       rmsi=rip-1;     /* save -> msi  */
5041 
5042       /* zero the accumulator  */
5043       for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5044 
5045       /* Start the multiplication */
5046       /* Resolving carries can dominate the cost of accumulating the  */
5047       /* partial products, so this is only done when necessary.  */
5048       /* Each uLong item in the accumulator can hold values up to  */
5049       /* 2**64-1, and each partial product can be as large as  */
5050       /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to  */
5051       /* itself 18.4 times in a uLong without overflowing, so during  */
5052       /* the main calculation resolution is carried out every 18th  */
5053       /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the  */
5054       /* partial products can be added to themselves 1844.6 times in  */
5055       /* a uLong without overflowing, so intermediate carry  */
5056       /* resolution occurs only every 14752 digits.  Hence for common  */
5057       /* short numbers usually only the one final carry resolution  */
5058       /* occurs.  */
5059       /* (The count is set via FASTLAZY to simplify experiments to  */
5060       /* measure the value of this approach: a 35% improvement on a  */
5061       /* [34x34] multiply.)  */
5062       lazy=FASTLAZY;                         /* carry delay count  */
5063       for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs  */
5064         lp=zacc+(rip-zrhi);                  /* where to add the lhs  */
5065         for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs  */
5066           *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line]  */
5067           } /* lip loop  */
5068         lazy--;
5069         if (lazy>0 && rip!=rmsi) continue;
5070         lazy=FASTLAZY;                       /* reset delay count  */
5071         /* spin up the accumulator resolving overflows  */
5072         for (lp=zacc; lp<zacc+iacc; lp++) {
5073           if (*lp<FASTBASE) continue;        /* it fits  */
5074           lcarry=*lp/FASTBASE;               /* top part [slow divide]  */
5075           /* lcarry can exceed 2**32-1, so check again; this check  */
5076           /* and occasional extra divide (slow) is well worth it, as  */
5077           /* it allows FASTLAZY to be increased to 18 rather than 4  */
5078           /* in the FASTDIGS=9 case  */
5079           if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual]  */
5080            else { /* two-place carry [fairly rare]  */
5081             uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part  */
5082             *(lp+2)+=carry2;                        /* add to item+2  */
5083             *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow]  */
5084             carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline]  */
5085             }
5086           *(lp+1)+=carry;                    /* add to item above [inline]  */
5087           *lp-=((uLong)FASTBASE*carry);      /* [inline]  */
5088           } /* carry resolution  */
5089         } /* rip loop  */
5090 
5091       /* The multiplication is complete; time to convert back into  */
5092       /* units.  This can be done in-place in the accumulator and in  */
5093       /* 32-bit operations, because carries were resolved after the  */
5094       /* final add.  This needs N-1 divides and multiplies for  */
5095       /* each item in the accumulator (which will become up to N  */
5096       /* units, where 2<=N<=9).  */
5097       for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5098         uInt item=(uInt)*lp;                 /* decapitate to uInt  */
5099         for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5100           uInt part=item/(DECDPUNMAX+1);
5101           *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5102           item=part;
5103           } /* p  */
5104         *up=(Unit)item; up++;                /* [final needs no division]  */
5105         } /* lp  */
5106       accunits = static_cast<int32_t>(up-acc);                       /* count of units  */
5107       }
5108      else { /* here to use units directly, without chunking ['old code']  */
5109     #endif
5110 
5111       /* if accumulator will be too long for local storage, then allocate  */
5112       acc=accbuff;                 /* -> assume buffer for accumulator  */
5113       needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5114       if (needbytes>(Int)sizeof(accbuff)) {
5115         allocacc=(Unit *)malloc(needbytes);
5116         if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5117         acc=(Unit *)allocacc;                /* use the allocated space  */
5118         }
5119 
5120       /* Now the main long multiplication loop */
5121       /* Unlike the equivalent in the IBM Java implementation, there  */
5122       /* is no advantage in calculating from msu to lsu.  So, do it  */
5123       /* by the book, as it were.  */
5124       /* Each iteration calculates ACC=ACC+MULTAND*MULT  */
5125       accunits=1;                  /* accumulator starts at '0'  */
5126       *acc=0;                      /* .. (lsu=0)  */
5127       shift=0;                     /* no multiplicand shift at first  */
5128       madlength=D2U(lhs->digits);  /* this won't change  */
5129       mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier  */
5130 
5131       for (mer=rhs->lsu; mer<mermsup; mer++) {
5132         /* Here, *mer is the next Unit in the multiplier to use  */
5133         /* If non-zero [optimization] add it...  */
5134         if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5135                                             lhs->lsu, madlength, 0,
5136                                             &acc[shift], *mer)
5137                                             + shift;
5138          else { /* extend acc with a 0; it will be used shortly  */
5139           *(acc+accunits)=0;       /* [this avoids length of <=0 later]  */
5140           accunits++;
5141           }
5142         /* multiply multiplicand by 10**DECDPUN for next Unit to left  */
5143         shift++;                   /* add this for 'logical length'  */
5144         } /* n  */
5145     #if FASTMUL
5146       } /* unchunked units  */
5147     #endif
5148     /* common end-path  */
5149     #if DECTRACE
5150       decDumpAr('*', acc, accunits);         /* Show exact result  */
5151     #endif
5152 
5153     /* acc now contains the exact result of the multiplication,  */
5154     /* possibly with a leading zero unit; build the decNumber from  */
5155     /* it, noting if any residue  */
5156     res->bits=bits;                          /* set sign  */
5157     res->digits=decGetDigits(acc, accunits); /* count digits exactly  */
5158 
5159     /* There can be a 31-bit wrap in calculating the exponent.  */
5160     /* This can only happen if both input exponents are negative and  */
5161     /* both their magnitudes are large.  If there was a wrap, set a  */
5162     /* safe very negative exponent, from which decFinalize() will  */
5163     /* raise a hard underflow shortly.  */
5164     exponent=lhs->exponent+rhs->exponent;    /* calculate exponent  */
5165     if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5166       exponent=-2*DECNUMMAXE;                /* force underflow  */
5167     res->exponent=exponent;                  /* OK to overwrite now  */
5168 
5169 
5170     /* Set the coefficient.  If any rounding, residue records  */
5171     decSetCoeff(res, set, acc, res->digits, &residue, status);
5172     decFinish(res, set, &residue, status);   /* final cleanup  */
5173     } while(0);                         /* end protected  */
5174 
5175   if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
5176   #if DECSUBSET
5177   if (allocrhs!=NULL) free(allocrhs);   /* ..  */
5178   if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5179   #endif
5180   #if FASTMUL
5181   if (allocrhi!=NULL) free(allocrhi);   /* ..  */
5182   if (alloclhi!=NULL) free(alloclhi);   /* ..  */
5183   #endif
5184   return res;
5185   } /* decMultiplyOp  */
5186 
5187 /* ------------------------------------------------------------------ */
5188 /* decExpOp -- effect exponentiation                                  */
5189 /*                                                                    */
5190 /*   This computes C = exp(A)                                         */
5191 /*                                                                    */
5192 /*   res is C, the result.  C may be A                                */
5193 /*   rhs is A                                                         */
5194 /*   set is the context; note that rounding mode has no effect        */
5195 /*                                                                    */
5196 /* C must have space for set->digits digits. status is updated but    */
5197 /* not set.                                                           */
5198 /*                                                                    */
5199 /* Restrictions:                                                      */
5200 /*                                                                    */
5201 /*   digits, emax, and -emin in the context must be less than         */
5202 /*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5203 /*   bounds or a zero.  This is an internal routine, so these         */
5204 /*   restrictions are contractual and not enforced.                   */
5205 /*                                                                    */
5206 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5207 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5208 /* error in rare cases.                                               */
5209 /*                                                                    */
5210 /* Finite results will always be full precision and Inexact, except   */
5211 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5212 /* ------------------------------------------------------------------ */
5213 /* This approach used here is similar to the algorithm described in   */
5214 /*                                                                    */
5215 /*   Variable Precision Exponential Function, T. E. Hull and          */
5216 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5217 /*   pp79-91, ACM, June 1986.                                         */
5218 /*                                                                    */
5219 /* with the main difference being that the iterations in the series   */
5220 /* evaluation are terminated dynamically (which does not require the  */
5221 /* extra variable-precision variables which are expensive in this     */
5222 /* context).                                                          */
5223 /*                                                                    */
5224 /* The error analysis in Hull & Abrham's paper applies except for the */
5225 /* round-off error accumulation during the series evaluation.  This   */
5226 /* code does not precalculate the number of iterations and so cannot  */
5227 /* use Horner's scheme.  Instead, the accumulation is done at double- */
5228 /* precision, which ensures that the additions of the terms are exact */
5229 /* and do not accumulate round-off (and any round-off errors in the   */
5230 /* terms themselves move 'to the right' faster than they can          */
5231 /* accumulate).  This code also extends the calculation by allowing,  */
5232 /* in the spirit of other decNumber operators, the input to be more   */
5233 /* precise than the result (the precision used is based on the more   */
5234 /* precise of the input or requested result).                         */
5235 /*                                                                    */
5236 /* Implementation notes:                                              */
5237 /*                                                                    */
5238 /* 1. This is separated out as decExpOp so it can be called from      */
5239 /*    other Mathematical functions (notably Ln) with a wider range    */
5240 /*    than normal.  In particular, it can handle the slightly wider   */
5241 /*    (double) range needed by Ln (which has to be able to calculate  */
5242 /*    exp(-x) where x can be the tiniest number (Ntiny).              */
5243 /*                                                                    */
5244 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5245 /*    iterations by appoximately a third with additional (although    */
5246 /*    diminishing) returns as the range is reduced to even smaller    */
5247 /*    fractions.  However, h (the power of 10 used to correct the     */
5248 /*    result at the end, see below) must be kept <=8 as otherwise     */
5249 /*    the final result cannot be computed.  Hence the leverage is a   */
5250 /*    sliding value (8-h), where potentially the range is reduced     */
5251 /*    more for smaller values.                                        */
5252 /*                                                                    */
5253 /*    The leverage that can be applied in this way is severely        */
5254 /*    limited by the cost of the raise-to-the power at the end,       */
5255 /*    which dominates when the number of iterations is small (less    */
5256 /*    than ten) or when rhs is short.  As an example, the adjustment  */
5257 /*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5258 /*                                                                    */
5259 /* 3. The restrictions (especially precision) could be raised with    */
5260 /*    care, but the full decNumber range seems very hard within the   */
5261 /*    32-bit limits.                                                  */
5262 /*                                                                    */
5263 /* 4. The working precisions for the static buffers are twice the     */
5264 /*    obvious size to allow for calls from decNumberPower.            */
5265 /* ------------------------------------------------------------------ */
decExpOp(decNumber * res,const decNumber * rhs,decContext * set,uInt * status)5266 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5267                          decContext *set, uInt *status) {
5268   uInt ignore=0;                   /* working status  */
5269   Int h;                           /* adjusted exponent for 0.xxxx  */
5270   Int p;                           /* working precision  */
5271   Int residue;                     /* rounding residue  */
5272   uInt needbytes;                  /* for space calculations  */
5273   const decNumber *x=rhs;          /* (may point to safe copy later)  */
5274   decContext aset, tset, dset;     /* working contexts  */
5275   Int comp;                        /* work  */
5276 
5277   /* the argument is often copied to normalize it, so (unusually) it  */
5278   /* is treated like other buffers, using DECBUFFER, +1 in case  */
5279   /* DECBUFFER is 0  */
5280   decNumber bufr[D2N(DECBUFFER*2+1)];
5281   decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated  */
5282 
5283   /* the working precision will be no more than set->digits+8+1  */
5284   /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER  */
5285   /* is 0 (and twice that for the accumulator)  */
5286 
5287   /* buffer for t, term (working precision plus)  */
5288   decNumber buft[D2N(DECBUFFER*2+9+1)];
5289   decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated  */
5290   decNumber *t=buft;               /* term  */
5291   /* buffer for a, accumulator (working precision * 2), at least 9  */
5292   decNumber bufa[D2N(DECBUFFER*4+18+1)];
5293   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5294   decNumber *a=bufa;               /* accumulator  */
5295   /* decNumber for the divisor term; this needs at most 9 digits  */
5296   /* and so can be fixed size [16 so can use standard context]  */
5297   decNumber bufd[D2N(16)];
5298   decNumber *d=bufd;               /* divisor  */
5299   decNumber numone;                /* constant 1  */
5300 
5301   #if DECCHECK
5302   Int iterations=0;                /* for later sanity check  */
5303   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5304   #endif
5305 
5306   do {                                  /* protect allocated storage  */
5307     if (SPECIALARG) {                   /* handle infinities and NaNs  */
5308       if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5309         if (decNumberIsNegative(rhs))   /* -Infinity -> +0  */
5310           uprv_decNumberZero(res);
5311          else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5312         }
5313        else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5314       break;}
5315 
5316     if (ISZERO(rhs)) {                  /* zeros -> exact 1  */
5317       uprv_decNumberZero(res);               /* make clean 1  */
5318       *res->lsu=1;                      /* ..  */
5319       break;}                           /* [no status to set]  */
5320 
5321     /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path  */
5322     /* positive and negative tiny cases which will result in inexact  */
5323     /* 1.  This also allows the later add-accumulate to always be  */
5324     /* exact (because its length will never be more than twice the  */
5325     /* working precision).  */
5326     /* The comparator (tiny) needs just one digit, so use the  */
5327     /* decNumber d for it (reused as the divisor, etc., below); its  */
5328     /* exponent is such that if x is positive it will have  */
5329     /* set->digits-1 zeros between the decimal point and the digit,  */
5330     /* which is 4, and if x is negative one more zero there as the  */
5331     /* more precise result will be of the form 0.9999999 rather than  */
5332     /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0  */
5333     /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than  */
5334     /* this then the result will be 1.000000  */
5335     uprv_decNumberZero(d);                   /* clean  */
5336     *d->lsu=4;                          /* set 4 ..  */
5337     d->exponent=-set->digits;           /* * 10**(-d)  */
5338     if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case  */
5339     comp=decCompare(d, rhs, 1);         /* signless compare  */
5340     if (comp==BADINT) {
5341       *status|=DEC_Insufficient_storage;
5342       break;}
5343     if (comp>=0) {                      /* rhs < d  */
5344       Int shift=set->digits-1;
5345       uprv_decNumberZero(res);               /* set 1  */
5346       *res->lsu=1;                      /* ..  */
5347       res->digits=decShiftToMost(res->lsu, 1, shift);
5348       res->exponent=-shift;                  /* make 1.0000...  */
5349       *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly  */
5350       break;} /* tiny  */
5351 
5352     /* set up the context to be used for calculating a, as this is  */
5353     /* used on both paths below  */
5354     uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5355     /* accumulator bounds are as requested (could underflow)  */
5356     aset.emax=set->emax;                /* usual bounds  */
5357     aset.emin=set->emin;                /* ..  */
5358     aset.clamp=0;                       /* and no concrete format  */
5359 
5360     /* calculate the adjusted (Hull & Abrham) exponent (where the  */
5361     /* decimal point is just to the left of the coefficient msd)  */
5362     h=rhs->exponent+rhs->digits;
5363     /* if h>8 then 10**h cannot be calculated safely; however, when  */
5364     /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at  */
5365     /* least 6.59E+4342944, so (due to the restriction on Emax/Emin)  */
5366     /* overflow (or underflow to 0) is guaranteed -- so this case can  */
5367     /* be handled by simply forcing the appropriate excess  */
5368     if (h>8) {                          /* overflow/underflow  */
5369       /* set up here so Power call below will over or underflow to  */
5370       /* zero; set accumulator to either 2 or 0.02  */
5371       /* [stack buffer for a is always big enough for this]  */
5372       uprv_decNumberZero(a);
5373       *a->lsu=2;                        /* not 1 but < exp(1)  */
5374       if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02  */
5375       h=8;                              /* clamp so 10**h computable  */
5376       p=9;                              /* set a working precision  */
5377       }
5378      else {                             /* h<=8  */
5379       Int maxlever=(rhs->digits>8?1:0);
5380       /* [could/should increase this for precisions >40 or so, too]  */
5381 
5382       /* if h is 8, cannot normalize to a lower upper limit because  */
5383       /* the final result will not be computable (see notes above),  */
5384       /* but leverage can be applied whenever h is less than 8.  */
5385       /* Apply as much as possible, up to a MAXLEVER digits, which  */
5386       /* sets the tradeoff against the cost of the later a**(10**h).  */
5387       /* As h is increased, the working precision below also  */
5388       /* increases to compensate for the "constant digits at the  */
5389       /* front" effect.  */
5390       Int lever=MINI(8-h, maxlever);    /* leverage attainable  */
5391       Int use=-rhs->digits-lever;       /* exponent to use for RHS  */
5392       h+=lever;                         /* apply leverage selected  */
5393       if (h<0) {                        /* clamp  */
5394         use+=h;                         /* [may end up subnormal]  */
5395         h=0;
5396         }
5397       /* Take a copy of RHS if it needs normalization (true whenever x>=1)  */
5398       if (rhs->exponent!=use) {
5399         decNumber *newrhs=bufr;         /* assume will fit on stack  */
5400         needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5401         if (needbytes>sizeof(bufr)) {   /* need malloc space  */
5402           allocrhs=(decNumber *)malloc(needbytes);
5403           if (allocrhs==NULL) {         /* hopeless -- abandon  */
5404             *status|=DEC_Insufficient_storage;
5405             break;}
5406           newrhs=allocrhs;              /* use the allocated space  */
5407           }
5408         uprv_decNumberCopy(newrhs, rhs);     /* copy to safe space  */
5409         newrhs->exponent=use;           /* normalize; now <1  */
5410         x=newrhs;                       /* ready for use  */
5411         /* decNumberShow(x);  */
5412         }
5413 
5414       /* Now use the usual power series to evaluate exp(x).  The  */
5415       /* series starts as 1 + x + x^2/2 ... so prime ready for the  */
5416       /* third term by setting the term variable t=x, the accumulator  */
5417       /* a=1, and the divisor d=2.  */
5418 
5419       /* First determine the working precision.  From Hull & Abrham  */
5420       /* this is set->digits+h+2.  However, if x is 'over-precise' we  */
5421       /* need to allow for all its digits to potentially participate  */
5422       /* (consider an x where all the excess digits are 9s) so in  */
5423       /* this case use x->digits+h+2  */
5424       p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8]  */
5425 
5426       /* a and t are variable precision, and depend on p, so space  */
5427       /* must be allocated for them if necessary  */
5428 
5429       /* the accumulator needs to be able to hold 2p digits so that  */
5430       /* the additions on the second and subsequent iterations are  */
5431       /* sufficiently exact.  */
5432       needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5433       if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5434         allocbufa=(decNumber *)malloc(needbytes);
5435         if (allocbufa==NULL) {          /* hopeless -- abandon  */
5436           *status|=DEC_Insufficient_storage;
5437           break;}
5438         a=allocbufa;                    /* use the allocated space  */
5439         }
5440       /* the term needs to be able to hold p digits (which is  */
5441       /* guaranteed to be larger than x->digits, so the initial copy  */
5442       /* is safe); it may also be used for the raise-to-power  */
5443       /* calculation below, which needs an extra two digits  */
5444       needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5445       if (needbytes>sizeof(buft)) {     /* need malloc space  */
5446         allocbuft=(decNumber *)malloc(needbytes);
5447         if (allocbuft==NULL) {          /* hopeless -- abandon  */
5448           *status|=DEC_Insufficient_storage;
5449           break;}
5450         t=allocbuft;                    /* use the allocated space  */
5451         }
5452 
5453       uprv_decNumberCopy(t, x);              /* term=x  */
5454       uprv_decNumberZero(a); *a->lsu=1;      /* accumulator=1  */
5455       uprv_decNumberZero(d); *d->lsu=2;      /* divisor=2  */
5456       uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment  */
5457 
5458       /* set up the contexts for calculating a, t, and d  */
5459       uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5460       dset=tset;
5461       /* accumulator bounds are set above, set precision now  */
5462       aset.digits=p*2;                  /* double  */
5463       /* term bounds avoid any underflow or overflow  */
5464       tset.digits=p;
5465       tset.emin=DEC_MIN_EMIN;           /* [emax is plenty]  */
5466       /* [dset.digits=16, etc., are sufficient]  */
5467 
5468       /* finally ready to roll  */
5469       for (;;) {
5470         #if DECCHECK
5471         iterations++;
5472         #endif
5473         /* only the status from the accumulation is interesting  */
5474         /* [but it should remain unchanged after first add]  */
5475         decAddOp(a, a, t, &aset, 0, status);           /* a=a+t  */
5476         decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x  */
5477         decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d  */
5478         /* the iteration ends when the term cannot affect the result,  */
5479         /* if rounded to p digits, which is when its value is smaller  */
5480         /* than the accumulator by p+1 digits.  There must also be  */
5481         /* full precision in a.  */
5482         if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5483             && (a->digits>=p)) break;
5484         decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1  */
5485         } /* iterate  */
5486 
5487       #if DECCHECK
5488       /* just a sanity check; comment out test to show always  */
5489       if (iterations>p+3)
5490         printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5491                (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5492       #endif
5493       } /* h<=8  */
5494 
5495     /* apply postconditioning: a=a**(10**h) -- this is calculated  */
5496     /* at a slightly higher precision than Hull & Abrham suggest  */
5497     if (h>0) {
5498       Int seenbit=0;               /* set once a 1-bit is seen  */
5499       Int i;                       /* counter  */
5500       Int n=powers[h];             /* always positive  */
5501       aset.digits=p+2;             /* sufficient precision  */
5502       /* avoid the overhead and many extra digits of decNumberPower  */
5503       /* as all that is needed is the short 'multipliers' loop; here  */
5504       /* accumulate the answer into t  */
5505       uprv_decNumberZero(t); *t->lsu=1; /* acc=1  */
5506       for (i=1;;i++){              /* for each bit [top bit ignored]  */
5507         /* abandon if have had overflow or terminal underflow  */
5508         if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
5509           if (*status&DEC_Overflow || ISZERO(t)) break;}
5510         n=n<<1;                    /* move next bit to testable position  */
5511         if (n<0) {                 /* top bit is set  */
5512           seenbit=1;               /* OK, have a significant bit  */
5513           decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x  */
5514           }
5515         if (i==31) break;          /* that was the last bit  */
5516         if (!seenbit) continue;    /* no need to square 1  */
5517         decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square]  */
5518         } /*i*/ /* 32 bits  */
5519       /* decNumberShow(t);  */
5520       a=t;                         /* and carry on using t instead of a  */
5521       }
5522 
5523     /* Copy and round the result to res  */
5524     residue=1;                          /* indicate dirt to right ..  */
5525     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5526     aset.digits=set->digits;            /* [use default rounding]  */
5527     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5528     decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5529     } while(0);                         /* end protected  */
5530 
5531   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
5532   if (allocbufa!=NULL) free(allocbufa); /* ..  */
5533   if (allocbuft!=NULL) free(allocbuft); /* ..  */
5534   /* [status is handled by caller]  */
5535   return res;
5536   } /* decExpOp  */
5537 
5538 /* ------------------------------------------------------------------ */
5539 /* Initial-estimate natural logarithm table                           */
5540 /*                                                                    */
5541 /*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5542 /*           The result is a 4-digit encode of the coefficient (c=the */
5543 /*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5544 /*           exponent (e=the bottom 2 bits encoding 0-3)              */
5545 /*                                                                    */
5546 /*           The resulting value is given by:                         */
5547 /*                                                                    */
5548 /*             v = -c * 10**(-e-3)                                    */
5549 /*                                                                    */
5550 /*           where e and c are extracted from entry k = LNnn[x-10]    */
5551 /*           where x is truncated (NB) into the range 10 through 99,  */
5552 /*           and then c = k>>2 and e = k&3.                           */
5553 /* ------------------------------------------------------------------ */
5554 static const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5555   6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5556   5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5557  39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5558  29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5559  22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5560  15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5561  10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5562   5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5563  10130,  6046, 20055};
5564 
5565 /* ------------------------------------------------------------------ */
5566 /* decLnOp -- effect natural logarithm                                */
5567 /*                                                                    */
5568 /*   This computes C = ln(A)                                          */
5569 /*                                                                    */
5570 /*   res is C, the result.  C may be A                                */
5571 /*   rhs is A                                                         */
5572 /*   set is the context; note that rounding mode has no effect        */
5573 /*                                                                    */
5574 /* C must have space for set->digits digits.                          */
5575 /*                                                                    */
5576 /* Notable cases:                                                     */
5577 /*   A<0 -> Invalid                                                   */
5578 /*   A=0 -> -Infinity (Exact)                                         */
5579 /*   A=+Infinity -> +Infinity (Exact)                                 */
5580 /*   A=1 exactly -> 0 (Exact)                                         */
5581 /*                                                                    */
5582 /* Restrictions (as for Exp):                                         */
5583 /*                                                                    */
5584 /*   digits, emax, and -emin in the context must be less than         */
5585 /*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5586 /*   bounds or a zero.  This is an internal routine, so these         */
5587 /*   restrictions are contractual and not enforced.                   */
5588 /*                                                                    */
5589 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5590 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5591 /* error in rare cases.                                               */
5592 /* ------------------------------------------------------------------ */
5593 /* The result is calculated using Newton's method, with each          */
5594 /* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5595 /* Epperson 1989.                                                     */
5596 /*                                                                    */
5597 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5598 /* This has to be calculated at the sum of the precision of x and the */
5599 /* working precision.                                                 */
5600 /*                                                                    */
5601 /* Implementation notes:                                              */
5602 /*                                                                    */
5603 /* 1. This is separated out as decLnOp so it can be called from       */
5604 /*    other Mathematical functions (e.g., Log 10) with a wider range  */
5605 /*    than normal.  In particular, it can handle the slightly wider   */
5606 /*    (+9+2) range needed by a power function.                        */
5607 /*                                                                    */
5608 /* 2. The speed of this function is about 10x slower than exp, as     */
5609 /*    it typically needs 4-6 iterations for short numbers, and the    */
5610 /*    extra precision needed adds a squaring effect, twice.           */
5611 /*                                                                    */
5612 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5613 /*    as these are common requests.  ln(10) is used by log10(x).      */
5614 /*                                                                    */
5615 /* 4. An iteration might be saved by widening the LNnn table, and     */
5616 /*    would certainly save at least one if it were made ten times     */
5617 /*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5618 /*    However, for most practical evaluations, at least four or five  */
5619 /*    iterations will be neede -- so this would only speed up by      */
5620 /*    20-25% and that probably does not justify increasing the table  */
5621 /*    size.                                                           */
5622 /*                                                                    */
5623 /* 5. The static buffers are larger than might be expected to allow   */
5624 /*    for calls from decNumberPower.                                  */
5625 /* ------------------------------------------------------------------ */
5626 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
5627 #pragma GCC diagnostic push
5628 #pragma GCC diagnostic ignored "-Warray-bounds"
5629 #endif
decLnOp(decNumber * res,const decNumber * rhs,decContext * set,uInt * status)5630 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5631                     decContext *set, uInt *status) {
5632   uInt ignore=0;                   /* working status accumulator  */
5633   uInt needbytes;                  /* for space calculations  */
5634   Int residue;                     /* rounding residue  */
5635   Int r;                           /* rhs=f*10**r [see below]  */
5636   Int p;                           /* working precision  */
5637   Int pp;                          /* precision for iteration  */
5638   Int t;                           /* work  */
5639 
5640   /* buffers for a (accumulator, typically precision+2) and b  */
5641   /* (adjustment calculator, same size)  */
5642   decNumber bufa[D2N(DECBUFFER+12)];
5643   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5644   decNumber *a=bufa;               /* accumulator/work  */
5645   decNumber bufb[D2N(DECBUFFER*2+2)];
5646   decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated  */
5647   decNumber *b=bufb;               /* adjustment/work  */
5648 
5649   decNumber  numone;               /* constant 1  */
5650   decNumber  cmp;                  /* work  */
5651   decContext aset, bset;           /* working contexts  */
5652 
5653   #if DECCHECK
5654   Int iterations=0;                /* for later sanity check  */
5655   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5656   #endif
5657 
5658   do {                                  /* protect allocated storage  */
5659     if (SPECIALARG) {                   /* handle infinities and NaNs  */
5660       if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5661         if (decNumberIsNegative(rhs))   /* -Infinity -> error  */
5662           *status|=DEC_Invalid_operation;
5663          else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5664         }
5665        else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5666       break;}
5667 
5668     if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity  */
5669       uprv_decNumberZero(res);               /* make clean  */
5670       res->bits=DECINF|DECNEG;          /* set - infinity  */
5671       break;}                           /* [no status to set]  */
5672 
5673     /* Non-zero negatives are bad...  */
5674     if (decNumberIsNegative(rhs)) {     /* -x -> error  */
5675       *status|=DEC_Invalid_operation;
5676       break;}
5677 
5678     /* Here, rhs is positive, finite, and in range  */
5679 
5680     /* lookaside fastpath code for ln(2) and ln(10) at common lengths  */
5681     if (rhs->exponent==0 && set->digits<=40) {
5682       #if DECDPUN==1
5683       if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10)  */
5684       #else
5685       if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10)  */
5686       #endif
5687         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5688         #define LN10 "2.302585092994045684017991454684364207601"
5689         uprv_decNumberFromString(res, LN10, &aset);
5690         *status|=(DEC_Inexact | DEC_Rounded); /* is inexact  */
5691         break;}
5692       if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2)  */
5693         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5694         #define LN2 "0.6931471805599453094172321214581765680755"
5695         uprv_decNumberFromString(res, LN2, &aset);
5696         *status|=(DEC_Inexact | DEC_Rounded);
5697         break;}
5698       } /* integer and short  */
5699 
5700     /* Determine the working precision.  This is normally the  */
5701     /* requested precision + 2, with a minimum of 9.  However, if  */
5702     /* the rhs is 'over-precise' then allow for all its digits to  */
5703     /* potentially participate (consider an rhs where all the excess  */
5704     /* digits are 9s) so in this case use rhs->digits+2.  */
5705     p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5706 
5707     /* Allocate space for the accumulator and the high-precision  */
5708     /* adjustment calculator, if necessary.  The accumulator must  */
5709     /* be able to hold p digits, and the adjustment up to  */
5710     /* rhs->digits+p digits.  They are also made big enough for 16  */
5711     /* digits so that they can be used for calculating the initial  */
5712     /* estimate.  */
5713     needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5714     if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5715       allocbufa=(decNumber *)malloc(needbytes);
5716       if (allocbufa==NULL) {          /* hopeless -- abandon  */
5717         *status|=DEC_Insufficient_storage;
5718         break;}
5719       a=allocbufa;                    /* use the allocated space  */
5720       }
5721     pp=p+rhs->digits;
5722     needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5723     if (needbytes>sizeof(bufb)) {     /* need malloc space  */
5724       allocbufb=(decNumber *)malloc(needbytes);
5725       if (allocbufb==NULL) {          /* hopeless -- abandon  */
5726         *status|=DEC_Insufficient_storage;
5727         break;}
5728       b=allocbufb;                    /* use the allocated space  */
5729       }
5730 
5731     /* Prepare an initial estimate in acc. Calculate this by  */
5732     /* considering the coefficient of x to be a normalized fraction,  */
5733     /* f, with the decimal point at far left and multiplied by  */
5734     /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and  */
5735     /*   ln(x) = ln(f) + ln(10)*r  */
5736     /* Get the initial estimate for ln(f) from a small lookup  */
5737     /* table (see above) indexed by the first two digits of f,  */
5738     /* truncated.  */
5739 
5740     uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended  */
5741     r=rhs->exponent+rhs->digits;        /* 'normalised' exponent  */
5742     uprv_decNumberFromInt32(a, r);           /* a=r  */
5743     uprv_decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585)  */
5744     b->exponent=-6;                     /*  ..  */
5745     decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b  */
5746     /* now get top two digits of rhs into b by simple truncate and  */
5747     /* force to integer  */
5748     residue=0;                          /* (no residue)  */
5749     aset.digits=2; aset.round=DEC_ROUND_DOWN;
5750     decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten  */
5751     b->exponent=0;                      /* make integer  */
5752     t=decGetInt(b);                     /* [cannot fail]  */
5753     if (t<10) t=X10(t);                 /* adjust single-digit b  */
5754     t=LNnn[t-10];                       /* look up ln(b)  */
5755     uprv_decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient  */
5756     b->exponent=-(t&3)-3;               /* set exponent  */
5757     b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve  */
5758     aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore  */
5759     decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b  */
5760     /* the initial estimate is now in a, with up to 4 digits correct.  */
5761     /* When rhs is at or near Nmax the estimate will be low, so we  */
5762     /* will approach it from below, avoiding overflow when calling exp.  */
5763 
5764     uprv_decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment  */
5765 
5766     /* accumulator bounds are as requested (could underflow, but  */
5767     /* cannot overflow)  */
5768     aset.emax=set->emax;
5769     aset.emin=set->emin;
5770     aset.clamp=0;                       /* no concrete format  */
5771     /* set up a context to be used for the multiply and subtract  */
5772     bset=aset;
5773     bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the  */
5774     bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation  */
5775                                         /* [see decExpOp call below]  */
5776     /* for each iteration double the number of digits to calculate,  */
5777     /* up to a maximum of p  */
5778     pp=9;                               /* initial precision  */
5779     /* [initially 9 as then the sequence starts 7+2, 16+2, and  */
5780     /* 34+2, which is ideal for standard-sized numbers]  */
5781     aset.digits=pp;                     /* working context  */
5782     bset.digits=pp+rhs->digits;         /* wider context  */
5783     for (;;) {                          /* iterate  */
5784       #if DECCHECK
5785       iterations++;
5786       if (iterations>24) break;         /* consider 9 * 2**24  */
5787       #endif
5788       /* calculate the adjustment (exp(-a)*x-1) into b.  This is a  */
5789       /* catastrophic subtraction but it really is the difference  */
5790       /* from 1 that is of interest.  */
5791       /* Use the internal entry point to Exp as it allows the double  */
5792       /* range for calculating exp(-a) when a is the tiniest subnormal.  */
5793       a->bits^=DECNEG;                  /* make -a  */
5794       decExpOp(b, a, &bset, &ignore);   /* b=exp(-a)  */
5795       a->bits^=DECNEG;                  /* restore sign of a  */
5796       /* now multiply by rhs and subtract 1, at the wider precision  */
5797       decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs  */
5798       decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1  */
5799 
5800       /* the iteration ends when the adjustment cannot affect the  */
5801       /* result by >=0.5 ulp (at the requested digits), which  */
5802       /* is when its value is smaller than the accumulator by  */
5803       /* set->digits+1 digits (or it is zero) -- this is a looser  */
5804       /* requirement than for Exp because all that happens to the  */
5805       /* accumulator after this is the final rounding (but note that  */
5806       /* there must also be full precision in a, or a=0).  */
5807 
5808       if (decNumberIsZero(b) ||
5809           (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5810         if (a->digits==p) break;
5811         if (decNumberIsZero(a)) {
5812           decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ?  */
5813           if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0  */
5814            else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact  */
5815           break;
5816           }
5817         /* force padding if adjustment has gone to 0 before full length  */
5818         if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5819         }
5820 
5821       /* not done yet ...  */
5822       decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate  */
5823       if (pp==p) continue;                   /* precision is at maximum  */
5824       /* lengthen the next calculation  */
5825       pp=pp*2;                               /* double precision  */
5826       if (pp>p) pp=p;                        /* clamp to maximum  */
5827       aset.digits=pp;                        /* working context  */
5828       bset.digits=pp+rhs->digits;            /* wider context  */
5829       } /* Newton's iteration  */
5830 
5831     #if DECCHECK
5832     /* just a sanity check; remove the test to show always  */
5833     if (iterations>24)
5834       printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5835             (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5836     #endif
5837 
5838     /* Copy and round the result to res  */
5839     residue=1;                          /* indicate dirt to right  */
5840     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5841     aset.digits=set->digits;            /* [use default rounding]  */
5842     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5843     decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5844     } while(0);                         /* end protected  */
5845 
5846   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
5847   if (allocbufb!=NULL) free(allocbufb); /* ..  */
5848   /* [status is handled by caller]  */
5849   return res;
5850   } /* decLnOp  */
5851 #if defined(__clang__) || U_GCC_MAJOR_MINOR >= 406
5852 #pragma GCC diagnostic pop
5853 #endif
5854 
5855 /* ------------------------------------------------------------------ */
5856 /* decQuantizeOp  -- force exponent to requested value                */
5857 /*                                                                    */
5858 /*   This computes C = op(A, B), where op adjusts the coefficient     */
5859 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
5860 /*   of C has the value B or matches the exponent of B.               */
5861 /*   The numerical value of C will equal A, except for the effects of */
5862 /*   any rounding that occurred.                                      */
5863 /*                                                                    */
5864 /*   res is C, the result.  C may be A or B                           */
5865 /*   lhs is A, the number to adjust                                   */
5866 /*   rhs is B, the requested exponent                                 */
5867 /*   set is the context                                               */
5868 /*   quant is 1 for quantize or 0 for rescale                         */
5869 /*   status is the status accumulator (this can be called without     */
5870 /*          risk of control loss)                                     */
5871 /*                                                                    */
5872 /* C must have space for set->digits digits.                          */
5873 /*                                                                    */
5874 /* Unless there is an error or the result is infinite, the exponent   */
5875 /* after the operation is guaranteed to be that requested.            */
5876 /* ------------------------------------------------------------------ */
5877 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5878                                  const decNumber *rhs, decContext *set,
5879                                  Flag quant, uInt *status) {
5880   #if DECSUBSET
5881   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
5882   decNumber *allocrhs=NULL;        /* .., rhs  */
5883   #endif
5884   const decNumber *inrhs=rhs;      /* save original rhs  */
5885   Int   reqdigits=set->digits;     /* requested DIGITS  */
5886   Int   reqexp;                    /* requested exponent [-scale]  */
5887   Int   residue=0;                 /* rounding residue  */
5888   Int   etiny=set->emin-(reqdigits-1);
5889 
5890   #if DECCHECK
5891   if (decCheckOperands(res, lhs, rhs, set)) return res;
5892   #endif
5893 
5894   do {                             /* protect allocated storage  */
5895     #if DECSUBSET
5896     if (!set->extended) {
5897       /* reduce operands and set lostDigits status, as needed  */
5898       if (lhs->digits>reqdigits) {
5899         alloclhs=decRoundOperand(lhs, set, status);
5900         if (alloclhs==NULL) break;
5901         lhs=alloclhs;
5902         }
5903       if (rhs->digits>reqdigits) { /* [this only checks lostDigits]  */
5904         allocrhs=decRoundOperand(rhs, set, status);
5905         if (allocrhs==NULL) break;
5906         rhs=allocrhs;
5907         }
5908       }
5909     #endif
5910     /* [following code does not require input rounding]  */
5911 
5912     /* Handle special values  */
5913     if (SPECIALARGS) {
5914       /* NaNs get usual processing  */
5915       if (SPECIALARGS & (DECSNAN | DECNAN))
5916         decNaNs(res, lhs, rhs, set, status);
5917       /* one infinity but not both is bad  */
5918       else if ((lhs->bits ^ rhs->bits) & DECINF)
5919         *status|=DEC_Invalid_operation;
5920       /* both infinity: return lhs  */
5921       else uprv_decNumberCopy(res, lhs);          /* [nop if in place]  */
5922       break;
5923       }
5924 
5925     /* set requested exponent  */
5926     if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents  */
5927      else {                             /* rescale -- use value of rhs  */
5928       /* Original rhs must be an integer that fits and is in range,  */
5929       /* which could be from -1999999997 to +999999999, thanks to  */
5930       /* subnormals  */
5931       reqexp=decGetInt(inrhs);               /* [cannot fail]  */
5932       }
5933 
5934     #if DECSUBSET
5935     if (!set->extended) etiny=set->emin;     /* no subnormals  */
5936     #endif
5937 
5938     if (reqexp==BADINT                       /* bad (rescale only) or ..  */
5939      || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or ..  */
5940      || (reqexp<etiny)                       /* < lowest  */
5941      || (reqexp>set->emax)) {                /* > emax  */
5942       *status|=DEC_Invalid_operation;
5943       break;}
5944 
5945     /* the RHS has been processed, so it can be overwritten now if necessary  */
5946     if (ISZERO(lhs)) {                       /* zero coefficient unchanged  */
5947       uprv_decNumberCopy(res, lhs);               /* [nop if in place]  */
5948       res->exponent=reqexp;                  /* .. just set exponent  */
5949       #if DECSUBSET
5950       if (!set->extended) res->bits=0;       /* subset specification; no -0  */
5951       #endif
5952       }
5953      else {                                  /* non-zero lhs  */
5954       Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed  */
5955       /* if adjusted coefficient will definitely not fit, give up now  */
5956       if ((lhs->digits-adjust)>reqdigits) {
5957         *status|=DEC_Invalid_operation;
5958         break;
5959         }
5960 
5961       if (adjust>0) {                        /* increasing exponent  */
5962         /* this will decrease the length of the coefficient by adjust  */
5963         /* digits, and must round as it does so  */
5964         decContext workset;                  /* work  */
5965         workset=*set;                        /* clone rounding, etc.  */
5966         workset.digits=lhs->digits-adjust;   /* set requested length  */
5967         /* [note that the latter can be <1, here]  */
5968         decCopyFit(res, lhs, &workset, &residue, status); /* fit to result  */
5969         decApplyRound(res, &workset, residue, status);    /* .. and round  */
5970         residue=0;                                        /* [used]  */
5971         /* If just rounded a 999s case, exponent will be off by one;  */
5972         /* adjust back (after checking space), if so.  */
5973         if (res->exponent>reqexp) {
5974           /* re-check needed, e.g., for quantize(0.9999, 0.001) under  */
5975           /* set->digits==3  */
5976           if (res->digits==reqdigits) {      /* cannot shift by 1  */
5977             *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these]  */
5978             *status|=DEC_Invalid_operation;
5979             break;
5980             }
5981           res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift  */
5982           res->exponent--;                   /* (re)adjust the exponent.  */
5983           }
5984         #if DECSUBSET
5985         if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0  */
5986         #endif
5987         } /* increase  */
5988        else /* adjust<=0 */ {                /* decreasing or = exponent  */
5989         /* this will increase the length of the coefficient by -adjust  */
5990         /* digits, by adding zero or more trailing zeros; this is  */
5991         /* already checked for fit, above  */
5992         uprv_decNumberCopy(res, lhs);             /* [it will fit]  */
5993         /* if padding needed (adjust<0), add it now...  */
5994         if (adjust<0) {
5995           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5996           res->exponent+=adjust;             /* adjust the exponent  */
5997           }
5998         } /* decrease  */
5999       } /* non-zero  */
6000 
6001     /* Check for overflow [do not use Finalize in this case, as an  */
6002     /* overflow here is a "don't fit" situation]  */
6003     if (res->exponent>set->emax-res->digits+1) {  /* too big  */
6004       *status|=DEC_Invalid_operation;
6005       break;
6006       }
6007      else {
6008       decFinalize(res, set, &residue, status);    /* set subnormal flags  */
6009       *status&=~DEC_Underflow;          /* suppress Underflow [as per 754]  */
6010       }
6011     } while(0);                         /* end protected  */
6012 
6013   #if DECSUBSET
6014   if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used  */
6015   if (alloclhs!=NULL) free(alloclhs);   /* ..  */
6016   #endif
6017   return res;
6018   } /* decQuantizeOp  */
6019 
6020 /* ------------------------------------------------------------------ */
6021 /* decCompareOp -- compare, min, or max two Numbers                   */
6022 /*                                                                    */
6023 /*   This computes C = A ? B and carries out one of four operations:  */
6024 /*     COMPARE    -- returns the signum (as a number) giving the      */
6025 /*                   result of a comparison unless one or both        */
6026 /*                   operands is a NaN (in which case a NaN results)  */
6027 /*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
6028 /*                   Invalid operation.                               */
6029 /*     COMPMAX    -- returns the larger of the operands, using the    */
6030 /*                   754 maxnum operation                             */
6031 /*     COMPMAXMAG -- ditto, comparing absolute values                 */
6032 /*     COMPMIN    -- the 754 minnum operation                         */
6033 /*     COMPMINMAG -- ditto, comparing absolute values                 */
6034 /*     COMTOTAL   -- returns the signum (as a number) giving the      */
6035 /*                   result of a comparison using 754 total ordering  */
6036 /*                                                                    */
6037 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
6038 /*   lhs is A                                                         */
6039 /*   rhs is B                                                         */
6040 /*   set is the context                                               */
6041 /*   op  is the operation flag                                        */
6042 /*   status is the usual accumulator                                  */
6043 /*                                                                    */
6044 /* C must have space for one digit for COMPARE or set->digits for     */
6045 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6046 /* ------------------------------------------------------------------ */
6047 /* The emphasis here is on speed for common cases, and avoiding       */
6048 /* coefficient comparison if possible.                                */
6049 /* ------------------------------------------------------------------ */
6050 static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6051                          const decNumber *rhs, decContext *set,
6052                          Flag op, uInt *status) {
6053   #if DECSUBSET
6054   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
6055   decNumber *allocrhs=NULL;        /* .., rhs  */
6056   #endif
6057   Int   result=0;                  /* default result value  */
6058   uByte merged;                    /* work  */
6059 
6060   #if DECCHECK
6061   if (decCheckOperands(res, lhs, rhs, set)) return res;
6062   #endif
6063 
6064   do {                             /* protect allocated storage  */
6065     #if DECSUBSET
6066     if (!set->extended) {
6067       /* reduce operands and set lostDigits status, as needed  */
6068       if (lhs->digits>set->digits) {
6069         alloclhs=decRoundOperand(lhs, set, status);
6070         if (alloclhs==NULL) {result=BADINT; break;}
6071         lhs=alloclhs;
6072         }
6073       if (rhs->digits>set->digits) {
6074         allocrhs=decRoundOperand(rhs, set, status);
6075         if (allocrhs==NULL) {result=BADINT; break;}
6076         rhs=allocrhs;
6077         }
6078       }
6079     #endif
6080     /* [following code does not require input rounding]  */
6081 
6082     /* If total ordering then handle differing signs 'up front'  */
6083     if (op==COMPTOTAL) {                /* total ordering  */
6084       if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) {
6085         result=-1;
6086         break;
6087         }
6088       if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) {
6089         result=+1;
6090         break;
6091         }
6092       }
6093 
6094     /* handle NaNs specially; let infinities drop through  */
6095     /* This assumes sNaN (even just one) leads to NaN.  */
6096     merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6097     if (merged) {                       /* a NaN bit set  */
6098       if (op==COMPARE);                 /* result will be NaN  */
6099        else if (op==COMPSIG)            /* treat qNaN as sNaN  */
6100         *status|=DEC_Invalid_operation | DEC_sNaN;
6101        else if (op==COMPTOTAL) {        /* total ordering, always finite  */
6102         /* signs are known to be the same; compute the ordering here  */
6103         /* as if the signs are both positive, then invert for negatives  */
6104         if (!decNumberIsNaN(lhs)) result=-1;
6105          else if (!decNumberIsNaN(rhs)) result=+1;
6106          /* here if both NaNs  */
6107          else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6108          else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6109          else { /* both NaN or both sNaN  */
6110           /* now it just depends on the payload  */
6111           result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6112                                 rhs->lsu, D2U(rhs->digits), 0);
6113           /* [Error not possible, as these are 'aligned']  */
6114           } /* both same NaNs  */
6115         if (decNumberIsNegative(lhs)) result=-result;
6116         break;
6117         } /* total order  */
6118 
6119        else if (merged & DECSNAN);           /* sNaN -> qNaN  */
6120        else { /* here if MIN or MAX and one or two quiet NaNs  */
6121         /* min or max -- 754 rules ignore single NaN  */
6122         if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6123           /* just one NaN; force choice to be the non-NaN operand  */
6124           op=COMPMAX;
6125           if (lhs->bits & DECNAN) result=-1; /* pick rhs  */
6126                              else result=+1; /* pick lhs  */
6127           break;
6128           }
6129         } /* max or min  */
6130       op=COMPNAN;                            /* use special path  */
6131       decNaNs(res, lhs, rhs, set, status);   /* propagate NaN  */
6132       break;
6133       }
6134     /* have numbers  */
6135     if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6136      else result=decCompare(lhs, rhs, 0);    /* sign matters  */
6137     } while(0);                              /* end protected  */
6138 
6139   if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare  */
6140    else {
6141     if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum  */
6142       if (op==COMPTOTAL && result==0) {
6143         /* operands are numerically equal or same NaN (and same sign,  */
6144         /* tested first); if identical, leave result 0  */
6145         if (lhs->exponent!=rhs->exponent) {
6146           if (lhs->exponent<rhs->exponent) result=-1;
6147            else result=+1;
6148           if (decNumberIsNegative(lhs)) result=-result;
6149           } /* lexp!=rexp  */
6150         } /* total-order by exponent  */
6151       uprv_decNumberZero(res);               /* [always a valid result]  */
6152       if (result!=0) {                  /* must be -1 or +1  */
6153         *res->lsu=1;
6154         if (result<0) res->bits=DECNEG;
6155         }
6156       }
6157      else if (op==COMPNAN);             /* special, drop through  */
6158      else {                             /* MAX or MIN, non-NaN result  */
6159       Int residue=0;                    /* rounding accumulator  */
6160       /* choose the operand for the result  */
6161       const decNumber *choice;
6162       if (result==0) { /* operands are numerically equal  */
6163         /* choose according to sign then exponent (see 754)  */
6164         uByte slhs=(lhs->bits & DECNEG);
6165         uByte srhs=(rhs->bits & DECNEG);
6166         #if DECSUBSET
6167         if (!set->extended) {           /* subset: force left-hand  */
6168           op=COMPMAX;
6169           result=+1;
6170           }
6171         else
6172         #endif
6173         if (slhs!=srhs) {          /* signs differ  */
6174           if (slhs) result=-1;     /* rhs is max  */
6175                else result=+1;     /* lhs is max  */
6176           }
6177          else if (slhs && srhs) {  /* both negative  */
6178           if (lhs->exponent<rhs->exponent) result=+1;
6179                                       else result=-1;
6180           /* [if equal, use lhs, technically identical]  */
6181           }
6182          else {                    /* both positive  */
6183           if (lhs->exponent>rhs->exponent) result=+1;
6184                                       else result=-1;
6185           /* [ditto]  */
6186           }
6187         } /* numerically equal  */
6188       /* here result will be non-0; reverse if looking for MIN  */
6189       if (op==COMPMIN || op==COMPMINMAG) result=-result;
6190       choice=(result>0 ? lhs : rhs);    /* choose  */
6191       /* copy chosen to result, rounding if need be  */
6192       decCopyFit(res, choice, set, &residue, status);
6193       decFinish(res, set, &residue, status);
6194       }
6195     }
6196   #if DECSUBSET
6197   if (allocrhs!=NULL) free(allocrhs);   /* free any storage used  */
6198   if (alloclhs!=NULL) free(alloclhs);   /* ..  */
6199   #endif
6200   return res;
6201   } /* decCompareOp  */
6202 
6203 /* ------------------------------------------------------------------ */
6204 /* decCompare -- compare two decNumbers by numerical value            */
6205 /*                                                                    */
6206 /*  This routine compares A ? B without altering them.                */
6207 /*                                                                    */
6208 /*  Arg1 is A, a decNumber which is not a NaN                         */
6209 /*  Arg2 is B, a decNumber which is not a NaN                         */
6210 /*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6211 /*                                                                    */
6212 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6213 /*  (the only possible failure is an allocation error)                */
6214 /* ------------------------------------------------------------------ */
6215 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6216                       Flag abs_c) {
6217   Int   result;                    /* result value  */
6218   Int   sigr;                      /* rhs signum  */
6219   Int   compare;                   /* work  */
6220 
6221   result=1;                                  /* assume signum(lhs)  */
6222   if (ISZERO(lhs)) result=0;
6223   if (abs_c) {
6224     if (ISZERO(rhs)) return result;          /* LHS wins or both 0  */
6225     /* RHS is non-zero  */
6226     if (result==0) return -1;                /* LHS is 0; RHS wins  */
6227     /* [here, both non-zero, result=1]  */
6228     }
6229    else {                                    /* signs matter  */
6230     if (result && decNumberIsNegative(lhs)) result=-1;
6231     sigr=1;                                  /* compute signum(rhs)  */
6232     if (ISZERO(rhs)) sigr=0;
6233      else if (decNumberIsNegative(rhs)) sigr=-1;
6234     if (result > sigr) return +1;            /* L > R, return 1  */
6235     if (result < sigr) return -1;            /* L < R, return -1  */
6236     if (result==0) return 0;                   /* both 0  */
6237     }
6238 
6239   /* signums are the same; both are non-zero  */
6240   if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities  */
6241     if (decNumberIsInfinite(rhs)) {
6242       if (decNumberIsInfinite(lhs)) result=0;/* both infinite  */
6243        else result=-result;                  /* only rhs infinite  */
6244       }
6245     return result;
6246     }
6247   /* must compare the coefficients, allowing for exponents  */
6248   if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger  */
6249     /* swap sides, and sign  */
6250     const decNumber *temp=lhs;
6251     lhs=rhs;
6252     rhs=temp;
6253     result=-result;
6254     }
6255   compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6256                          rhs->lsu, D2U(rhs->digits),
6257                          rhs->exponent-lhs->exponent);
6258   if (compare!=BADINT) compare*=result;      /* comparison succeeded  */
6259   return compare;
6260   } /* decCompare  */
6261 
6262 /* ------------------------------------------------------------------ */
6263 /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6264 /*                                                                    */
6265 /*  This routine compares A ? B*10**E where A and B are unit arrays   */
6266 /*  A is a plain integer                                              */
6267 /*  B has an exponent of E (which must be non-negative)               */
6268 /*                                                                    */
6269 /*  Arg1 is A first Unit (lsu)                                        */
6270 /*  Arg2 is A length in Units                                         */
6271 /*  Arg3 is B first Unit (lsu)                                        */
6272 /*  Arg4 is B length in Units                                         */
6273 /*  Arg5 is E (0 if the units are aligned)                            */
6274 /*                                                                    */
6275 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6276 /*  (the only possible failure is an allocation error, which can      */
6277 /*  only occur if E!=0)                                               */
6278 /* ------------------------------------------------------------------ */
6279 static Int decUnitCompare(const Unit *a, Int alength,
6280                           const Unit *b, Int blength, Int exp) {
6281   Unit  *acc;                      /* accumulator for result  */
6282   Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer  */
6283   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
6284   Int   accunits, need;            /* units in use or needed for acc  */
6285   const Unit *l, *r, *u;           /* work  */
6286   Int   expunits, exprem, result;  /* ..  */
6287 
6288   if (exp==0) {                    /* aligned; fastpath  */
6289     if (alength>blength) return 1;
6290     if (alength<blength) return -1;
6291     /* same number of units in both -- need unit-by-unit compare  */
6292     l=a+alength-1;
6293     r=b+alength-1;
6294     for (;l>=a; l--, r--) {
6295       if (*l>*r) return 1;
6296       if (*l<*r) return -1;
6297       }
6298     return 0;                      /* all units match  */
6299     } /* aligned  */
6300 
6301   /* Unaligned.  If one is >1 unit longer than the other, padded  */
6302   /* approximately, then can return easily  */
6303   if (alength>blength+(Int)D2U(exp)) return 1;
6304   if (alength+1<blength+(Int)D2U(exp)) return -1;
6305 
6306   /* Need to do a real subtract.  For this, a result buffer is needed  */
6307   /* even though only the sign is of interest.  Its length needs  */
6308   /* to be the larger of alength and padded blength, +2  */
6309   need=blength+D2U(exp);                /* maximum real length of B  */
6310   if (need<alength) need=alength;
6311   need+=2;
6312   acc=accbuff;                          /* assume use local buffer  */
6313   if (need*sizeof(Unit)>sizeof(accbuff)) {
6314     allocacc=(Unit *)malloc(need*sizeof(Unit));
6315     if (allocacc==NULL) return BADINT;  /* hopeless -- abandon  */
6316     acc=allocacc;
6317     }
6318   /* Calculate units and remainder from exponent.  */
6319   expunits=exp/DECDPUN;
6320   exprem=exp%DECDPUN;
6321   /* subtract [A+B*(-m)]  */
6322   accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6323                          -(Int)powers[exprem]);
6324   /* [UnitAddSub result may have leading zeros, even on zero]  */
6325   if (accunits<0) result=-1;            /* negative result  */
6326    else {                               /* non-negative result  */
6327     /* check units of the result before freeing any storage  */
6328     for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6329     result=(*u==0 ? 0 : +1);
6330     }
6331   /* clean up and return the result  */
6332   if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
6333   return result;
6334   } /* decUnitCompare  */
6335 
6336 /* ------------------------------------------------------------------ */
6337 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6338 /*                                                                    */
6339 /*  This routine performs the calculation:                            */
6340 /*                                                                    */
6341 /*  C=A+(B*M)                                                         */
6342 /*                                                                    */
6343 /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6344 /*                                                                    */
6345 /*  A may be shorter or longer than B.                                */
6346 /*                                                                    */
6347 /*  Leading zeros are not removed after a calculation.  The result is */
6348 /*  either the same length as the longer of A and B (adding any       */
6349 /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6350 /*                                                                    */
6351 /*  A and B content are not altered unless C is also A or B.          */
6352 /*  C may be the same array as A or B, but only if no zero padding is */
6353 /*  requested (that is, C may be B only if bshift==0).                */
6354 /*  C is filled from the lsu; only those units necessary to complete  */
6355 /*  the calculation are referenced.                                   */
6356 /*                                                                    */
6357 /*  Arg1 is A first Unit (lsu)                                        */
6358 /*  Arg2 is A length in Units                                         */
6359 /*  Arg3 is B first Unit (lsu)                                        */
6360 /*  Arg4 is B length in Units                                         */
6361 /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6362 /*  Arg6 is C first Unit (lsu)                                        */
6363 /*  Arg7 is M, the multiplier                                         */
6364 /*                                                                    */
6365 /*  returns the count of Units written to C, which will be non-zero   */
6366 /*  and negated if the result is negative.  That is, the sign of the  */
6367 /*  returned Int is the sign of the result (positive for zero) and    */
6368 /*  the absolute value of the Int is the count of Units.              */
6369 /*                                                                    */
6370 /*  It is the caller's responsibility to make sure that C size is     */
6371 /*  safe, allowing space if necessary for a one-Unit carry.           */
6372 /*                                                                    */
6373 /*  This routine is severely performance-critical; *any* change here  */
6374 /*  must be measured (timed) to assure no performance degradation.    */
6375 /*  In particular, trickery here tends to be counter-productive, as   */
6376 /*  increased complexity of code hurts register optimizations on      */
6377 /*  register-poor architectures.  Avoiding divisions is nearly        */
6378 /*  always a Good Idea, however.                                      */
6379 /*                                                                    */
6380 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6381 /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6382 /* ------------------------------------------------------------------ */
6383 static Int decUnitAddSub(const Unit *a, Int alength,
6384                          const Unit *b, Int blength, Int bshift,
6385                          Unit *c, Int m) {
6386   const Unit *alsu=a;              /* A lsu [need to remember it]  */
6387   Unit *clsu=c;                    /* C ditto  */
6388   Unit *minC;                      /* low water mark for C  */
6389   Unit *maxC;                      /* high water mark for C  */
6390   eInt carry=0;                    /* carry integer (could be Long)  */
6391   Int  add;                        /* work  */
6392   #if DECDPUN<=4                   /* myriadal, millenary, etc.  */
6393   Int  est;                        /* estimated quotient  */
6394   #endif
6395 
6396   #if DECTRACE
6397   if (alength<1 || blength<1)
6398     printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6399   #endif
6400 
6401   maxC=c+alength;                  /* A is usually the longer  */
6402   minC=c+blength;                  /* .. and B the shorter  */
6403   if (bshift!=0) {                 /* B is shifted; low As copy across  */
6404     minC+=bshift;
6405     /* if in place [common], skip copy unless there's a gap [rare]  */
6406     if (a==c && bshift<=alength) {
6407       c+=bshift;
6408       a+=bshift;
6409       }
6410      else for (; c<clsu+bshift; a++, c++) {  /* copy needed  */
6411       if (a<alsu+alength) *c=*a;
6412        else *c=0;
6413       }
6414     }
6415   if (minC>maxC) { /* swap  */
6416     Unit *hold=minC;
6417     minC=maxC;
6418     maxC=hold;
6419     }
6420 
6421   /* For speed, do the addition as two loops; the first where both A  */
6422   /* and B contribute, and the second (if necessary) where only one or  */
6423   /* other of the numbers contribute.  */
6424   /* Carry handling is the same (i.e., duplicated) in each case.  */
6425   for (; c<minC; c++) {
6426     carry+=*a;
6427     a++;
6428     carry+=((eInt)*b)*m;                /* [special-casing m=1/-1  */
6429     b++;                                /* here is not a win]  */
6430     /* here carry is new Unit of digits; it could be +ve or -ve  */
6431     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6432       *c=(Unit)carry;
6433       carry=0;
6434       continue;
6435       }
6436     #if DECDPUN==4                           /* use divide-by-multiply  */
6437       if (carry>=0) {
6438         est=(((ueInt)carry>>11)*53687)>>18;
6439         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6440         carry=est;                           /* likely quotient [89%]  */
6441         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6442         carry++;
6443         *c-=DECDPUNMAX+1;
6444         continue;
6445         }
6446       /* negative case  */
6447       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6448       est=(((ueInt)carry>>11)*53687)>>18;
6449       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6450       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6451       if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6452       carry++;
6453       *c-=DECDPUNMAX+1;
6454     #elif DECDPUN==3
6455       if (carry>=0) {
6456         est=(((ueInt)carry>>3)*16777)>>21;
6457         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6458         carry=est;                           /* likely quotient [99%]  */
6459         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6460         carry++;
6461         *c-=DECDPUNMAX+1;
6462         continue;
6463         }
6464       /* negative case  */
6465       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6466       est=(((ueInt)carry>>3)*16777)>>21;
6467       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6468       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6469       if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6470       carry++;
6471       *c-=DECDPUNMAX+1;
6472     #elif DECDPUN<=2
6473       /* Can use QUOT10 as carry <= 4 digits  */
6474       if (carry>=0) {
6475         est=QUOT10(carry, DECDPUN);
6476         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6477         carry=est;                           /* quotient  */
6478         continue;
6479         }
6480       /* negative case  */
6481       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6482       est=QUOT10(carry, DECDPUN);
6483       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6484       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6485     #else
6486       /* remainder operator is undefined if negative, so must test  */
6487       if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1  */
6488         *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions]  */
6489         carry=1;
6490         continue;
6491         }
6492       if (carry>=0) {
6493         *c=(Unit)(carry%(DECDPUNMAX+1));
6494         carry=carry/(DECDPUNMAX+1);
6495         continue;
6496         }
6497       /* negative case  */
6498       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6499       *c=(Unit)(carry%(DECDPUNMAX+1));
6500       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6501     #endif
6502     } /* c  */
6503 
6504   /* now may have one or other to complete  */
6505   /* [pretest to avoid loop setup/shutdown]  */
6506   if (c<maxC) for (; c<maxC; c++) {
6507     if (a<alsu+alength) {               /* still in A  */
6508       carry+=*a;
6509       a++;
6510       }
6511      else {                             /* inside B  */
6512       carry+=((eInt)*b)*m;
6513       b++;
6514       }
6515     /* here carry is new Unit of digits; it could be +ve or -ve and  */
6516     /* magnitude up to DECDPUNMAX squared  */
6517     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6518       *c=(Unit)carry;
6519       carry=0;
6520       continue;
6521       }
6522     /* result for this unit is negative or >DECDPUNMAX  */
6523     #if DECDPUN==4                           /* use divide-by-multiply  */
6524       if (carry>=0) {
6525         est=(((ueInt)carry>>11)*53687)>>18;
6526         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6527         carry=est;                           /* likely quotient [79.7%]  */
6528         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6529         carry++;
6530         *c-=DECDPUNMAX+1;
6531         continue;
6532         }
6533       /* negative case  */
6534       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6535       est=(((ueInt)carry>>11)*53687)>>18;
6536       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6537       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6538       if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6539       carry++;
6540       *c-=DECDPUNMAX+1;
6541     #elif DECDPUN==3
6542       if (carry>=0) {
6543         est=(((ueInt)carry>>3)*16777)>>21;
6544         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6545         carry=est;                           /* likely quotient [99%]  */
6546         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6547         carry++;
6548         *c-=DECDPUNMAX+1;
6549         continue;
6550         }
6551       /* negative case  */
6552       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6553       est=(((ueInt)carry>>3)*16777)>>21;
6554       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6555       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6556       if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6557       carry++;
6558       *c-=DECDPUNMAX+1;
6559     #elif DECDPUN<=2
6560       if (carry>=0) {
6561         est=QUOT10(carry, DECDPUN);
6562         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6563         carry=est;                           /* quotient  */
6564         continue;
6565         }
6566       /* negative case  */
6567       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6568       est=QUOT10(carry, DECDPUN);
6569       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6570       carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6571     #else
6572       if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1  */
6573         *c=(Unit)(carry-(DECDPUNMAX+1));
6574         carry=1;
6575         continue;
6576         }
6577       /* remainder operator is undefined if negative, so must test  */
6578       if (carry>=0) {
6579         *c=(Unit)(carry%(DECDPUNMAX+1));
6580         carry=carry/(DECDPUNMAX+1);
6581         continue;
6582         }
6583       /* negative case  */
6584       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6585       *c=(Unit)(carry%(DECDPUNMAX+1));
6586       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6587     #endif
6588     } /* c  */
6589 
6590   /* OK, all A and B processed; might still have carry or borrow  */
6591   /* return number of Units in the result, negated if a borrow  */
6592   if (carry==0) return static_cast<int32_t>(c-clsu);     /* no carry, so no more to do  */
6593   if (carry>0) {                   /* positive carry  */
6594     *c=(Unit)carry;                /* place as new unit  */
6595     c++;                           /* ..  */
6596     return static_cast<int32_t>(c-clsu);
6597     }
6598   /* -ve carry: it's a borrow; complement needed  */
6599   add=1;                           /* temporary carry...  */
6600   for (c=clsu; c<maxC; c++) {
6601     add=DECDPUNMAX+add-*c;
6602     if (add<=DECDPUNMAX) {
6603       *c=(Unit)add;
6604       add=0;
6605       }
6606      else {
6607       *c=0;
6608       add=1;
6609       }
6610     }
6611   /* add an extra unit iff it would be non-zero  */
6612   #if DECTRACE
6613     printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6614   #endif
6615   if ((add-carry-1)!=0) {
6616     *c=(Unit)(add-carry-1);
6617     c++;                      /* interesting, include it  */
6618     }
6619   return static_cast<int32_t>(clsu-c);              /* -ve result indicates borrowed  */
6620   } /* decUnitAddSub  */
6621 
6622 /* ------------------------------------------------------------------ */
6623 /* decTrim -- trim trailing zeros or normalize                        */
6624 /*                                                                    */
6625 /*   dn is the number to trim or normalize                            */
6626 /*   set is the context to use to check for clamp                     */
6627 /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6628 /*   noclamp is 1 to unconditional (unclamped) trim                   */
6629 /*   dropped returns the number of discarded trailing zeros           */
6630 /*   returns dn                                                       */
6631 /*                                                                    */
6632 /* If clamp is set in the context then the number of zeros trimmed    */
6633 /* may be limited if the exponent is high.                            */
6634 /* All fields are updated as required.  This is a utility operation,  */
6635 /* so special values are unchanged and no error is possible.          */
6636 /* ------------------------------------------------------------------ */
6637 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6638                            Flag noclamp, Int *dropped) {
6639   Int   d, exp;                    /* work  */
6640   uInt  cut;                       /* ..  */
6641   Unit  *up;                       /* -> current Unit  */
6642 
6643   #if DECCHECK
6644   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6645   #endif
6646 
6647   *dropped=0;                           /* assume no zeros dropped  */
6648   if ((dn->bits & DECSPECIAL)           /* fast exit if special ..  */
6649     || (*dn->lsu & 0x01)) return dn;    /* .. or odd  */
6650   if (ISZERO(dn)) {                     /* .. or 0  */
6651     dn->exponent=0;                     /* (sign is preserved)  */
6652     return dn;
6653     }
6654 
6655   /* have a finite number which is even  */
6656   exp=dn->exponent;
6657   cut=1;                           /* digit (1-DECDPUN) in Unit  */
6658   up=dn->lsu;                      /* -> current Unit  */
6659   for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit]  */
6660     /* slice by powers  */
6661     #if DECDPUN<=4
6662       uInt quot=QUOT10(*up, cut);
6663       if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit  */
6664     #else
6665       if (*up%powers[cut]!=0) break;         /* found non-0 digit  */
6666     #endif
6667     /* have a trailing 0  */
6668     if (!all) {                    /* trimming  */
6669       /* [if exp>0 then all trailing 0s are significant for trim]  */
6670       if (exp<=0) {                /* if digit might be significant  */
6671         if (exp==0) break;         /* then quit  */
6672         exp++;                     /* next digit might be significant  */
6673         }
6674       }
6675     cut++;                         /* next power  */
6676     if (cut>DECDPUN) {             /* need new Unit  */
6677       up++;
6678       cut=1;
6679       }
6680     } /* d  */
6681   if (d==0) return dn;             /* none to drop  */
6682 
6683   /* may need to limit drop if clamping  */
6684   if (set->clamp && !noclamp) {
6685     Int maxd=set->emax-set->digits+1-dn->exponent;
6686     if (maxd<=0) return dn;        /* nothing possible  */
6687     if (d>maxd) d=maxd;
6688     }
6689 
6690   /* effect the drop  */
6691   decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6692   dn->exponent+=d;                 /* maintain numerical value  */
6693   dn->digits-=d;                   /* new length  */
6694   *dropped=d;                      /* report the count  */
6695   return dn;
6696   } /* decTrim  */
6697 
6698 /* ------------------------------------------------------------------ */
6699 /* decReverse -- reverse a Unit array in place                        */
6700 /*                                                                    */
6701 /*   ulo    is the start of the array                                 */
6702 /*   uhi    is the end of the array (highest Unit to include)         */
6703 /*                                                                    */
6704 /* The units ulo through uhi are reversed in place (if the number     */
6705 /* of units is odd, the middle one is untouched).  Note that the      */
6706 /* digit(s) in each unit are unaffected.                              */
6707 /* ------------------------------------------------------------------ */
6708 static void decReverse(Unit *ulo, Unit *uhi) {
6709   Unit temp;
6710   for (; ulo<uhi; ulo++, uhi--) {
6711     temp=*ulo;
6712     *ulo=*uhi;
6713     *uhi=temp;
6714     }
6715   return;
6716   } /* decReverse  */
6717 
6718 /* ------------------------------------------------------------------ */
6719 /* decShiftToMost -- shift digits in array towards most significant   */
6720 /*                                                                    */
6721 /*   uar    is the array                                              */
6722 /*   digits is the count of digits in use in the array                */
6723 /*   shift  is the number of zeros to pad with (least significant);   */
6724 /*     it must be zero or positive                                    */
6725 /*                                                                    */
6726 /*   returns the new length of the integer in the array, in digits    */
6727 /*                                                                    */
6728 /* No overflow is permitted (that is, the uar array must be known to  */
6729 /* be large enough to hold the result, after shifting).               */
6730 /* ------------------------------------------------------------------ */
6731 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6732   Unit  *target, *source, *first;  /* work  */
6733   Int   cut;                       /* odd 0's to add  */
6734   uInt  next;                      /* work  */
6735 
6736   if (shift==0) return digits;     /* [fastpath] nothing to do  */
6737   if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case  */
6738     *uar=(Unit)(*uar*powers[shift]);
6739     return digits+shift;
6740     }
6741 
6742   next=0;                          /* all paths  */
6743   source=uar+D2U(digits)-1;        /* where msu comes from  */
6744   target=source+D2U(shift);        /* where upper part of first cut goes  */
6745   cut=DECDPUN-MSUDIGITS(shift);    /* where to slice  */
6746   if (cut==0) {                    /* unit-boundary case  */
6747     for (; source>=uar; source--, target--) *target=*source;
6748     }
6749    else {
6750     first=uar+D2U(digits+shift)-1; /* where msu of source will end up  */
6751     for (; source>=uar; source--, target--) {
6752       /* split the source Unit and accumulate remainder for next  */
6753       #if DECDPUN<=4
6754         uInt quot=QUOT10(*source, cut);
6755         uInt rem=*source-quot*powers[cut];
6756         next+=quot;
6757       #else
6758         uInt rem=*source%powers[cut];
6759         next+=*source/powers[cut];
6760       #endif
6761       if (target<=first) *target=(Unit)next;   /* write to target iff valid  */
6762       next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit  */
6763       }
6764     } /* shift-move  */
6765 
6766   /* propagate any partial unit to one below and clear the rest  */
6767   for (; target>=uar; target--) {
6768     *target=(Unit)next;
6769     next=0;
6770     }
6771   return digits+shift;
6772   } /* decShiftToMost  */
6773 
6774 /* ------------------------------------------------------------------ */
6775 /* decShiftToLeast -- shift digits in array towards least significant */
6776 /*                                                                    */
6777 /*   uar   is the array                                               */
6778 /*   units is length of the array, in units                           */
6779 /*   shift is the number of digits to remove from the lsu end; it     */
6780 /*     must be zero or positive and <= than units*DECDPUN.            */
6781 /*                                                                    */
6782 /*   returns the new length of the integer in the array, in units     */
6783 /*                                                                    */
6784 /* Removed digits are discarded (lost).  Units not required to hold   */
6785 /* the final result are unchanged.                                    */
6786 /* ------------------------------------------------------------------ */
6787 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6788   Unit  *target, *up;              /* work  */
6789   Int   cut, count;                /* work  */
6790   Int   quot, rem;                 /* for division  */
6791 
6792   if (shift==0) return units;      /* [fastpath] nothing to do  */
6793   if (shift==units*DECDPUN) {      /* [fastpath] little to do  */
6794     *uar=0;                        /* all digits cleared gives zero  */
6795     return 1;                      /* leaves just the one  */
6796     }
6797 
6798   target=uar;                      /* both paths  */
6799   cut=MSUDIGITS(shift);
6800   if (cut==DECDPUN) {              /* unit-boundary case; easy  */
6801     up=uar+D2U(shift);
6802     for (; up<uar+units; target++, up++) *target=*up;
6803     return static_cast<int32_t>(target-uar);
6804     }
6805 
6806   /* messier  */
6807   up=uar+D2U(shift-cut);           /* source; correct to whole Units  */
6808   count=units*DECDPUN-shift;       /* the maximum new length  */
6809   #if DECDPUN<=4
6810     quot=QUOT10(*up, cut);
6811   #else
6812     quot=*up/powers[cut];
6813   #endif
6814   for (; ; target++) {
6815     *target=(Unit)quot;
6816     count-=(DECDPUN-cut);
6817     if (count<=0) break;
6818     up++;
6819     quot=*up;
6820     #if DECDPUN<=4
6821       quot=QUOT10(quot, cut);
6822       rem=*up-quot*powers[cut];
6823     #else
6824       rem=quot%powers[cut];
6825       quot=quot/powers[cut];
6826     #endif
6827     *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6828     count-=cut;
6829     if (count<=0) break;
6830     }
6831   return static_cast<int32_t>(target-uar+1);
6832   } /* decShiftToLeast  */
6833 
6834 #if DECSUBSET
6835 /* ------------------------------------------------------------------ */
6836 /* decRoundOperand -- round an operand  [used for subset only]        */
6837 /*                                                                    */
6838 /*   dn is the number to round (dn->digits is > set->digits)          */
6839 /*   set is the relevant context                                      */
6840 /*   status is the status accumulator                                 */
6841 /*                                                                    */
6842 /*   returns an allocated decNumber with the rounded result.          */
6843 /*                                                                    */
6844 /* lostDigits and other status may be set by this.                    */
6845 /*                                                                    */
6846 /* Since the input is an operand, it must not be modified.            */
6847 /* Instead, return an allocated decNumber, rounded as required.       */
6848 /* It is the caller's responsibility to free the allocated storage.   */
6849 /*                                                                    */
6850 /* If no storage is available then the result cannot be used, so NULL */
6851 /* is returned.                                                       */
6852 /* ------------------------------------------------------------------ */
6853 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6854                                   uInt *status) {
6855   decNumber *res;                       /* result structure  */
6856   uInt newstatus=0;                     /* status from round  */
6857   Int  residue=0;                       /* rounding accumulator  */
6858 
6859   /* Allocate storage for the returned decNumber, big enough for the  */
6860   /* length specified by the context  */
6861   res=(decNumber *)malloc(sizeof(decNumber)
6862                           +(D2U(set->digits)-1)*sizeof(Unit));
6863   if (res==NULL) {
6864     *status|=DEC_Insufficient_storage;
6865     return NULL;
6866     }
6867   decCopyFit(res, dn, set, &residue, &newstatus);
6868   decApplyRound(res, set, residue, &newstatus);
6869 
6870   /* If that set Inexact then "lost digits" is raised...  */
6871   if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6872   *status|=newstatus;
6873   return res;
6874   } /* decRoundOperand  */
6875 #endif
6876 
6877 /* ------------------------------------------------------------------ */
6878 /* decCopyFit -- copy a number, truncating the coefficient if needed  */
6879 /*                                                                    */
6880 /*   dest is the target decNumber                                     */
6881 /*   src  is the source decNumber                                     */
6882 /*   set is the context [used for length (digits) and rounding mode]  */
6883 /*   residue is the residue accumulator                               */
6884 /*   status contains the current status to be updated                 */
6885 /*                                                                    */
6886 /* (dest==src is allowed and will be a no-op if fits)                 */
6887 /* All fields are updated as required.                                */
6888 /* ------------------------------------------------------------------ */
6889 static void decCopyFit(decNumber *dest, const decNumber *src,
6890                        decContext *set, Int *residue, uInt *status) {
6891   dest->bits=src->bits;
6892   dest->exponent=src->exponent;
6893   decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6894   } /* decCopyFit  */
6895 
6896 /* ------------------------------------------------------------------ */
6897 /* decSetCoeff -- set the coefficient of a number                     */
6898 /*                                                                    */
6899 /*   dn    is the number whose coefficient array is to be set.        */
6900 /*         It must have space for set->digits digits                  */
6901 /*   set   is the context [for size]                                  */
6902 /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6903 /*   len   is digits in the source coefficient [may be dn->digits]    */
6904 /*   residue is the residue accumulator.  This has values as in       */
6905 /*         decApplyRound, and will be unchanged unless the            */
6906 /*         target size is less than len.  In this case, the           */
6907 /*         coefficient is truncated and the residue is updated to     */
6908 /*         reflect the previous residue and the dropped digits.       */
6909 /*   status is the status accumulator, as usual                       */
6910 /*                                                                    */
6911 /* The coefficient may already be in the number, or it can be an      */
6912 /* external intermediate array.  If it is in the number, lsu must ==  */
6913 /* dn->lsu and len must == dn->digits.                                */
6914 /*                                                                    */
6915 /* Note that the coefficient length (len) may be < set->digits, and   */
6916 /* in this case this merely copies the coefficient (or is a no-op     */
6917 /* if dn->lsu==lsu).                                                  */
6918 /*                                                                    */
6919 /* Note also that (only internally, from decQuantizeOp and            */
6920 /* decSetSubnormal) the value of set->digits may be less than one,    */
6921 /* indicating a round to left.  This routine handles that case        */
6922 /* correctly; caller ensures space.                                   */
6923 /*                                                                    */
6924 /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6925 /* updated as necessary.   dn->bits (sign) is unchanged.              */
6926 /*                                                                    */
6927 /* DEC_Rounded status is set if any digits are discarded.             */
6928 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6929 /*                       incoming residue was non-0 (implies rounded) */
6930 /* ------------------------------------------------------------------ */
6931 /* mapping array: maps 0-9 to canonical residues, so that a residue  */
6932 /* can be adjusted in the range [-1, +1] and achieve correct rounding  */
6933 /*                             0  1  2  3  4  5  6  7  8  9  */
6934 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6935 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6936                         Int len, Int *residue, uInt *status) {
6937   Int   discard;              /* number of digits to discard  */
6938   uInt  cut;                  /* cut point in Unit  */
6939   const Unit *up;             /* work  */
6940   Unit  *target;              /* ..  */
6941   Int   count;                /* ..  */
6942   #if DECDPUN<=4
6943   uInt  temp;                 /* ..  */
6944   #endif
6945 
6946   discard=len-set->digits;    /* digits to discard  */
6947   if (discard<=0) {           /* no digits are being discarded  */
6948     if (dn->lsu!=lsu) {       /* copy needed  */
6949       /* copy the coefficient array to the result number; no shift needed  */
6950       count=len;              /* avoids D2U  */
6951       up=lsu;
6952       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6953         *target=*up;
6954       dn->digits=len;         /* set the new length  */
6955       }
6956     /* dn->exponent and residue are unchanged, record any inexactitude  */
6957     if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6958     return;
6959     }
6960 
6961   /* some digits must be discarded ...  */
6962   dn->exponent+=discard;      /* maintain numerical value  */
6963   *status|=DEC_Rounded;       /* accumulate Rounded status  */
6964   if (*residue>1) *residue=1; /* previous residue now to right, so reduce  */
6965 
6966   if (discard>len) {          /* everything, +1, is being discarded  */
6967     /* guard digit is 0  */
6968     /* residue is all the number [NB could be all 0s]  */
6969     if (*residue<=0) {        /* not already positive  */
6970       count=len;              /* avoids D2U  */
6971       for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0  */
6972         *residue=1;
6973         break;                /* no need to check any others  */
6974         }
6975       }
6976     if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
6977     *dn->lsu=0;               /* coefficient will now be 0  */
6978     dn->digits=1;             /* ..  */
6979     return;
6980     } /* total discard  */
6981 
6982   /* partial discard [most common case]  */
6983   /* here, at least the first (most significant) discarded digit exists  */
6984 
6985   /* spin up the number, noting residue during the spin, until get to  */
6986   /* the Unit with the first discarded digit.  When reach it, extract  */
6987   /* it and remember its position  */
6988   count=0;
6989   for (up=lsu;; up++) {
6990     count+=DECDPUN;
6991     if (count>=discard) break; /* full ones all checked  */
6992     if (*up!=0) *residue=1;
6993     } /* up  */
6994 
6995   /* here up -> Unit with first discarded digit  */
6996   cut=discard-(count-DECDPUN)-1;
6997   if (cut==DECDPUN-1) {       /* unit-boundary case (fast)  */
6998     Unit half=(Unit)powers[DECDPUN]>>1;
6999     /* set residue directly  */
7000     if (*up>=half) {
7001       if (*up>half) *residue=7;
7002       else *residue+=5;       /* add sticky bit  */
7003       }
7004      else { /* <half  */
7005       if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit]  */
7006       }
7007     if (set->digits<=0) {     /* special for Quantize/Subnormal :-(  */
7008       *dn->lsu=0;             /* .. result is 0  */
7009       dn->digits=1;           /* ..  */
7010       }
7011      else {                   /* shift to least  */
7012       count=set->digits;      /* now digits to end up with  */
7013       dn->digits=count;       /* set the new length  */
7014       up++;                   /* move to next  */
7015       /* on unit boundary, so shift-down copy loop is simple  */
7016       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
7017         *target=*up;
7018       }
7019     } /* unit-boundary case  */
7020 
7021    else { /* discard digit is in low digit(s), and not top digit  */
7022     uInt  discard1;                /* first discarded digit  */
7023     uInt  quot, rem;               /* for divisions  */
7024     if (cut==0) quot=*up;          /* is at bottom of unit  */
7025      else /* cut>0 */ {            /* it's not at bottom of unit  */
7026       #if DECDPUN<=4
7027         U_ASSERT(/* cut >= 0 &&*/ cut <= 4);
7028         quot=QUOT10(*up, cut);
7029         rem=*up-quot*powers[cut];
7030       #else
7031         rem=*up%powers[cut];
7032         quot=*up/powers[cut];
7033       #endif
7034       if (rem!=0) *residue=1;
7035       }
7036     /* discard digit is now at bottom of quot  */
7037     #if DECDPUN<=4
7038       temp=(quot*6554)>>16;        /* fast /10  */
7039       /* Vowels algorithm here not a win (9 instructions)  */
7040       discard1=quot-X10(temp);
7041       quot=temp;
7042     #else
7043       discard1=quot%10;
7044       quot=quot/10;
7045     #endif
7046     /* here, discard1 is the guard digit, and residue is everything  */
7047     /* else [use mapping array to accumulate residue safely]  */
7048     *residue+=resmap[discard1];
7049     cut++;                         /* update cut  */
7050     /* here: up -> Unit of the array with bottom digit  */
7051     /*       cut is the division point for each Unit  */
7052     /*       quot holds the uncut high-order digits for the current unit  */
7053     if (set->digits<=0) {          /* special for Quantize/Subnormal :-(  */
7054       *dn->lsu=0;                  /* .. result is 0  */
7055       dn->digits=1;                /* ..  */
7056       }
7057      else {                        /* shift to least needed  */
7058       count=set->digits;           /* now digits to end up with  */
7059       dn->digits=count;            /* set the new length  */
7060       /* shift-copy the coefficient array to the result number  */
7061       for (target=dn->lsu; ; target++) {
7062         *target=(Unit)quot;
7063         count-=(DECDPUN-cut);
7064         if (count<=0) break;
7065         up++;
7066         quot=*up;
7067         #if DECDPUN<=4
7068           quot=QUOT10(quot, cut);
7069           rem=*up-quot*powers[cut];
7070         #else
7071           rem=quot%powers[cut];
7072           quot=quot/powers[cut];
7073         #endif
7074         *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7075         count-=cut;
7076         if (count<=0) break;
7077         } /* shift-copy loop  */
7078       } /* shift to least  */
7079     } /* not unit boundary  */
7080 
7081   if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
7082   return;
7083   } /* decSetCoeff  */
7084 
7085 /* ------------------------------------------------------------------ */
7086 /* decApplyRound -- apply pending rounding to a number                */
7087 /*                                                                    */
7088 /*   dn    is the number, with space for set->digits digits           */
7089 /*   set   is the context [for size and rounding mode]                */
7090 /*   residue indicates pending rounding, being any accumulated        */
7091 /*         guard and sticky information.  It may be:                  */
7092 /*         6-9: rounding digit is >5                                  */
7093 /*         5:   rounding digit is exactly half-way                    */
7094 /*         1-4: rounding digit is <5 and >0                           */
7095 /*         0:   the coefficient is exact                              */
7096 /*        -1:   as 1, but the hidden digits are subtractive, that     */
7097 /*              is, of the opposite sign to dn.  In this case the     */
7098 /*              coefficient must be non-0.  This case occurs when     */
7099 /*              subtracting a small number (which can be reduced to   */
7100 /*              a sticky bit); see decAddOp.                          */
7101 /*   status is the status accumulator, as usual                       */
7102 /*                                                                    */
7103 /* This routine applies rounding while keeping the length of the      */
7104 /* coefficient constant.  The exponent and status are unchanged       */
7105 /* except if:                                                         */
7106 /*                                                                    */
7107 /*   -- the coefficient was increased and is all nines (in which      */
7108 /*      case Overflow could occur, and is handled directly here so    */
7109 /*      the caller does not need to re-test for overflow)             */
7110 /*                                                                    */
7111 /*   -- the coefficient was decreased and becomes all nines (in which */
7112 /*      case Underflow could occur, and is also handled directly).    */
7113 /*                                                                    */
7114 /* All fields in dn are updated as required.                          */
7115 /*                                                                    */
7116 /* ------------------------------------------------------------------ */
7117 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7118                           uInt *status) {
7119   Int  bump;                  /* 1 if coefficient needs to be incremented  */
7120                               /* -1 if coefficient needs to be decremented  */
7121 
7122   if (residue==0) return;     /* nothing to apply  */
7123 
7124   bump=0;                     /* assume a smooth ride  */
7125 
7126   /* now decide whether, and how, to round, depending on mode  */
7127   switch (set->round) {
7128     case DEC_ROUND_05UP: {    /* round zero or five up (for reround)  */
7129       /* This is the same as DEC_ROUND_DOWN unless there is a  */
7130       /* positive residue and the lsd of dn is 0 or 5, in which case  */
7131       /* it is bumped; when residue is <0, the number is therefore  */
7132       /* bumped down unless the final digit was 1 or 6 (in which  */
7133       /* case it is bumped down and then up -- a no-op)  */
7134       Int lsd5=*dn->lsu%5;     /* get lsd and quintate  */
7135       if (residue<0 && lsd5!=1) bump=-1;
7136        else if (residue>0 && lsd5==0) bump=1;
7137       /* [bump==1 could be applied directly; use common path for clarity]  */
7138       break;} /* r-05  */
7139 
7140     case DEC_ROUND_DOWN: {
7141       /* no change, except if negative residue  */
7142       if (residue<0) bump=-1;
7143       break;} /* r-d  */
7144 
7145     case DEC_ROUND_HALF_DOWN: {
7146       if (residue>5) bump=1;
7147       break;} /* r-h-d  */
7148 
7149     case DEC_ROUND_HALF_EVEN: {
7150       if (residue>5) bump=1;            /* >0.5 goes up  */
7151        else if (residue==5) {           /* exactly 0.5000...  */
7152         /* 0.5 goes up iff [new] lsd is odd  */
7153         if (*dn->lsu & 0x01) bump=1;
7154         }
7155       break;} /* r-h-e  */
7156 
7157     case DEC_ROUND_HALF_UP: {
7158       if (residue>=5) bump=1;
7159       break;} /* r-h-u  */
7160 
7161     case DEC_ROUND_UP: {
7162       if (residue>0) bump=1;
7163       break;} /* r-u  */
7164 
7165     case DEC_ROUND_CEILING: {
7166       /* same as _UP for positive numbers, and as _DOWN for negatives  */
7167       /* [negative residue cannot occur on 0]  */
7168       if (decNumberIsNegative(dn)) {
7169         if (residue<0) bump=-1;
7170         }
7171        else {
7172         if (residue>0) bump=1;
7173         }
7174       break;} /* r-c  */
7175 
7176     case DEC_ROUND_FLOOR: {
7177       /* same as _UP for negative numbers, and as _DOWN for positive  */
7178       /* [negative residue cannot occur on 0]  */
7179       if (!decNumberIsNegative(dn)) {
7180         if (residue<0) bump=-1;
7181         }
7182        else {
7183         if (residue>0) bump=1;
7184         }
7185       break;} /* r-f  */
7186 
7187     default: {      /* e.g., DEC_ROUND_MAX  */
7188       *status|=DEC_Invalid_context;
7189       #if DECTRACE || (DECCHECK && DECVERB)
7190       printf("Unknown rounding mode: %d\n", set->round);
7191       #endif
7192       break;}
7193     } /* switch  */
7194 
7195   /* now bump the number, up or down, if need be  */
7196   if (bump==0) return;                       /* no action required  */
7197 
7198   /* Simply use decUnitAddSub unless bumping up and the number is  */
7199   /* all nines.  In this special case set to 100... explicitly  */
7200   /* and adjust the exponent by one (as otherwise could overflow  */
7201   /* the array)  */
7202   /* Similarly handle all-nines result if bumping down.  */
7203   if (bump>0) {
7204     Unit *up;                                /* work  */
7205     uInt count=dn->digits;                   /* digits to be checked  */
7206     for (up=dn->lsu; ; up++) {
7207       if (count<=DECDPUN) {
7208         /* this is the last Unit (the msu)  */
7209         if (*up!=powers[count]-1) break;     /* not still 9s  */
7210         /* here if it, too, is all nines  */
7211         *up=(Unit)powers[count-1];           /* here 999 -> 100 etc.  */
7212         for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0  */
7213         dn->exponent++;                      /* and bump exponent  */
7214         /* [which, very rarely, could cause Overflow...]  */
7215         if ((dn->exponent+dn->digits)>set->emax+1) {
7216           decSetOverflow(dn, set, status);
7217           }
7218         return;                              /* done  */
7219         }
7220       /* a full unit to check, with more to come  */
7221       if (*up!=DECDPUNMAX) break;            /* not still 9s  */
7222       count-=DECDPUN;
7223       } /* up  */
7224     } /* bump>0  */
7225    else {                                    /* -1  */
7226     /* here checking for a pre-bump of 1000... (leading 1, all  */
7227     /* other digits zero)  */
7228     Unit *up, *sup;                          /* work  */
7229     uInt count=dn->digits;                   /* digits to be checked  */
7230     for (up=dn->lsu; ; up++) {
7231       if (count<=DECDPUN) {
7232         /* this is the last Unit (the msu)  */
7233         if (*up!=powers[count-1]) break;     /* not 100..  */
7234         /* here if have the 1000... case  */
7235         sup=up;                              /* save msu pointer  */
7236         *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999  */
7237         /* others all to all-nines, too  */
7238         for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7239         dn->exponent--;                      /* and bump exponent  */
7240 
7241         /* iff the number was at the subnormal boundary (exponent=etiny)  */
7242         /* then the exponent is now out of range, so it will in fact get  */
7243         /* clamped to etiny and the final 9 dropped.  */
7244         /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin,  */
7245         /*        dn->exponent, set->digits);  */
7246         if (dn->exponent+1==set->emin-set->digits+1) {
7247           if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9]  */
7248            else {
7249             *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99..  */
7250             dn->digits--;
7251             }
7252           dn->exponent++;
7253           *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7254           }
7255         return;                              /* done  */
7256         }
7257 
7258       /* a full unit to check, with more to come  */
7259       if (*up!=0) break;                     /* not still 0s  */
7260       count-=DECDPUN;
7261       } /* up  */
7262 
7263     } /* bump<0  */
7264 
7265   /* Actual bump needed.  Do it.  */
7266   decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7267   } /* decApplyRound  */
7268 
7269 #if DECSUBSET
7270 /* ------------------------------------------------------------------ */
7271 /* decFinish -- finish processing a number                            */
7272 /*                                                                    */
7273 /*   dn is the number                                                 */
7274 /*   set is the context                                               */
7275 /*   residue is the rounding accumulator (as in decApplyRound)        */
7276 /*   status is the accumulator                                        */
7277 /*                                                                    */
7278 /* This finishes off the current number by:                           */
7279 /*    1. If not extended:                                             */
7280 /*       a. Converting a zero result to clean '0'                     */
7281 /*       b. Reducing positive exponents to 0, if would fit in digits  */
7282 /*    2. Checking for overflow and subnormals (always)                */
7283 /* Note this is just Finalize when no subset arithmetic.              */
7284 /* All fields are updated as required.                                */
7285 /* ------------------------------------------------------------------ */
7286 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7287                       uInt *status) {
7288   if (!set->extended) {
7289     if ISZERO(dn) {                /* value is zero  */
7290       dn->exponent=0;              /* clean exponent ..  */
7291       dn->bits=0;                  /* .. and sign  */
7292       return;                      /* no error possible  */
7293       }
7294     if (dn->exponent>=0) {         /* non-negative exponent  */
7295       /* >0; reduce to integer if possible  */
7296       if (set->digits >= (dn->exponent+dn->digits)) {
7297         dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7298         dn->exponent=0;
7299         }
7300       }
7301     } /* !extended  */
7302 
7303   decFinalize(dn, set, residue, status);
7304   } /* decFinish  */
7305 #endif
7306 
7307 /* ------------------------------------------------------------------ */
7308 /* decFinalize -- final check, clamp, and round of a number           */
7309 /*                                                                    */
7310 /*   dn is the number                                                 */
7311 /*   set is the context                                               */
7312 /*   residue is the rounding accumulator (as in decApplyRound)        */
7313 /*   status is the status accumulator                                 */
7314 /*                                                                    */
7315 /* This finishes off the current number by checking for subnormal     */
7316 /* results, applying any pending rounding, checking for overflow,     */
7317 /* and applying any clamping.                                         */
7318 /* Underflow and overflow conditions are raised as appropriate.       */
7319 /* All fields are updated as required.                                */
7320 /* ------------------------------------------------------------------ */
7321 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7322                         uInt *status) {
7323   Int shift;                            /* shift needed if clamping  */
7324   Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary  */
7325 
7326   /* Must be careful, here, when checking the exponent as the  */
7327   /* adjusted exponent could overflow 31 bits [because it may already  */
7328   /* be up to twice the expected].  */
7329 
7330   /* First test for subnormal.  This must be done before any final  */
7331   /* round as the result could be rounded to Nmin or 0.  */
7332   if (dn->exponent<=tinyexp) {          /* prefilter  */
7333     Int comp;
7334     decNumber nmin;
7335     /* A very nasty case here is dn == Nmin and residue<0  */
7336     if (dn->exponent<tinyexp) {
7337       /* Go handle subnormals; this will apply round if needed.  */
7338       decSetSubnormal(dn, set, residue, status);
7339       return;
7340       }
7341     /* Equals case: only subnormal if dn=Nmin and negative residue  */
7342     uprv_decNumberZero(&nmin);
7343     nmin.lsu[0]=1;
7344     nmin.exponent=set->emin;
7345     comp=decCompare(dn, &nmin, 1);                /* (signless compare)  */
7346     if (comp==BADINT) {                           /* oops  */
7347       *status|=DEC_Insufficient_storage;          /* abandon...  */
7348       return;
7349       }
7350     if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin  */
7351       decApplyRound(dn, set, *residue, status);   /* might force down  */
7352       decSetSubnormal(dn, set, residue, status);
7353       return;
7354       }
7355     }
7356 
7357   /* now apply any pending round (this could raise overflow).  */
7358   if (*residue!=0) decApplyRound(dn, set, *residue, status);
7359 
7360   /* Check for overflow [redundant in the 'rare' case] or clamp  */
7361   if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed  */
7362 
7363 
7364   /* here when might have an overflow or clamp to do  */
7365   if (dn->exponent>set->emax-dn->digits+1) {           /* too big  */
7366     decSetOverflow(dn, set, status);
7367     return;
7368     }
7369   /* here when the result is normal but in clamp range  */
7370   if (!set->clamp) return;
7371 
7372   /* here when need to apply the IEEE exponent clamp (fold-down)  */
7373   shift=dn->exponent-(set->emax-set->digits+1);
7374 
7375   /* shift coefficient (if non-zero)  */
7376   if (!ISZERO(dn)) {
7377     dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7378     }
7379   dn->exponent-=shift;   /* adjust the exponent to match  */
7380   *status|=DEC_Clamped;  /* and record the dirty deed  */
7381   return;
7382   } /* decFinalize  */
7383 
7384 /* ------------------------------------------------------------------ */
7385 /* decSetOverflow -- set number to proper overflow value              */
7386 /*                                                                    */
7387 /*   dn is the number (used for sign [only] and result)               */
7388 /*   set is the context [used for the rounding mode, etc.]            */
7389 /*   status contains the current status to be updated                 */
7390 /*                                                                    */
7391 /* This sets the sign of a number and sets its value to either        */
7392 /* Infinity or the maximum finite value, depending on the sign of     */
7393 /* dn and the rounding mode, following IEEE 754 rules.                */
7394 /* ------------------------------------------------------------------ */
7395 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7396   Flag needmax=0;                  /* result is maximum finite value  */
7397   uByte sign=dn->bits&DECNEG;      /* clean and save sign bit  */
7398 
7399   if (ISZERO(dn)) {                /* zero does not overflow magnitude  */
7400     Int emax=set->emax;                      /* limit value  */
7401     if (set->clamp) emax-=set->digits-1;     /* lower if clamping  */
7402     if (dn->exponent>emax) {                 /* clamp required  */
7403       dn->exponent=emax;
7404       *status|=DEC_Clamped;
7405       }
7406     return;
7407     }
7408 
7409   uprv_decNumberZero(dn);
7410   switch (set->round) {
7411     case DEC_ROUND_DOWN: {
7412       needmax=1;                   /* never Infinity  */
7413       break;} /* r-d  */
7414     case DEC_ROUND_05UP: {
7415       needmax=1;                   /* never Infinity  */
7416       break;} /* r-05  */
7417     case DEC_ROUND_CEILING: {
7418       if (sign) needmax=1;         /* Infinity if non-negative  */
7419       break;} /* r-c  */
7420     case DEC_ROUND_FLOOR: {
7421       if (!sign) needmax=1;        /* Infinity if negative  */
7422       break;} /* r-f  */
7423     default: break;                /* Infinity in all other cases  */
7424     }
7425   if (needmax) {
7426     decSetMaxValue(dn, set);
7427     dn->bits=sign;                 /* set sign  */
7428     }
7429    else dn->bits=sign|DECINF;      /* Value is +/-Infinity  */
7430   *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7431   } /* decSetOverflow  */
7432 
7433 /* ------------------------------------------------------------------ */
7434 /* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7435 /*                                                                    */
7436 /*   dn is the number to set                                          */
7437 /*   set is the context [used for digits and emax]                    */
7438 /*                                                                    */
7439 /* This sets the number to the maximum positive value.                */
7440 /* ------------------------------------------------------------------ */
7441 static void decSetMaxValue(decNumber *dn, decContext *set) {
7442   Unit *up;                        /* work  */
7443   Int count=set->digits;           /* nines to add  */
7444   dn->digits=count;
7445   /* fill in all nines to set maximum value  */
7446   for (up=dn->lsu; ; up++) {
7447     if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines  */
7448      else {                             /* this is the msu  */
7449       *up=(Unit)(powers[count]-1);
7450       break;
7451       }
7452     count-=DECDPUN;                /* filled those digits  */
7453     } /* up  */
7454   dn->bits=0;                      /* + sign  */
7455   dn->exponent=set->emax-set->digits+1;
7456   } /* decSetMaxValue  */
7457 
7458 /* ------------------------------------------------------------------ */
7459 /* decSetSubnormal -- process value whose exponent is <Emin           */
7460 /*                                                                    */
7461 /*   dn is the number (used as input as well as output; it may have   */
7462 /*         an allowed subnormal value, which may need to be rounded)  */
7463 /*   set is the context [used for the rounding mode]                  */
7464 /*   residue is any pending residue                                   */
7465 /*   status contains the current status to be updated                 */
7466 /*                                                                    */
7467 /* If subset mode, set result to zero and set Underflow flags.        */
7468 /*                                                                    */
7469 /* Value may be zero with a low exponent; this does not set Subnormal */
7470 /* but the exponent will be clamped to Etiny.                         */
7471 /*                                                                    */
7472 /* Otherwise ensure exponent is not out of range, and round as        */
7473 /* necessary.  Underflow is set if the result is Inexact.             */
7474 /* ------------------------------------------------------------------ */
7475 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7476                             uInt *status) {
7477   decContext workset;         /* work  */
7478   Int        etiny, adjust;   /* ..  */
7479 
7480   #if DECSUBSET
7481   /* simple set to zero and 'hard underflow' for subset  */
7482   if (!set->extended) {
7483     uprv_decNumberZero(dn);
7484     /* always full overflow  */
7485     *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7486     return;
7487     }
7488   #endif
7489 
7490   /* Full arithmetic -- allow subnormals, rounded to minimum exponent  */
7491   /* (Etiny) if needed  */
7492   etiny=set->emin-(set->digits-1);      /* smallest allowed exponent  */
7493 
7494   if ISZERO(dn) {                       /* value is zero  */
7495     /* residue can never be non-zero here  */
7496     #if DECCHECK
7497       if (*residue!=0) {
7498         printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7499         *status|=DEC_Invalid_operation;
7500         }
7501     #endif
7502     if (dn->exponent<etiny) {           /* clamp required  */
7503       dn->exponent=etiny;
7504       *status|=DEC_Clamped;
7505       }
7506     return;
7507     }
7508 
7509   *status|=DEC_Subnormal;               /* have a non-zero subnormal  */
7510   adjust=etiny-dn->exponent;            /* calculate digits to remove  */
7511   if (adjust<=0) {                      /* not out of range; unrounded  */
7512     /* residue can never be non-zero here, except in the Nmin-residue  */
7513     /* case (which is a subnormal result), so can take fast-path here  */
7514     /* it may already be inexact (from setting the coefficient)  */
7515     if (*status&DEC_Inexact) *status|=DEC_Underflow;
7516     return;
7517     }
7518 
7519   /* adjust>0, so need to rescale the result so exponent becomes Etiny  */
7520   /* [this code is similar to that in rescale]  */
7521   workset=*set;                         /* clone rounding, etc.  */
7522   workset.digits=dn->digits-adjust;     /* set requested length  */
7523   workset.emin-=adjust;                 /* and adjust emin to match  */
7524   /* [note that the latter can be <1, here, similar to Rescale case]  */
7525   decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7526   decApplyRound(dn, &workset, *residue, status);
7527 
7528   /* Use 754 default rule: Underflow is set iff Inexact  */
7529   /* [independent of whether trapped]  */
7530   if (*status&DEC_Inexact) *status|=DEC_Underflow;
7531 
7532   /* if rounded up a 999s case, exponent will be off by one; adjust  */
7533   /* back if so [it will fit, because it was shortened earlier]  */
7534   if (dn->exponent>etiny) {
7535     dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7536     dn->exponent--;                     /* (re)adjust the exponent.  */
7537     }
7538 
7539   /* if rounded to zero, it is by definition clamped...  */
7540   if (ISZERO(dn)) *status|=DEC_Clamped;
7541   } /* decSetSubnormal  */
7542 
7543 /* ------------------------------------------------------------------ */
7544 /* decCheckMath - check entry conditions for a math function          */
7545 /*                                                                    */
7546 /*   This checks the context and the operand                          */
7547 /*                                                                    */
7548 /*   rhs is the operand to check                                      */
7549 /*   set is the context to check                                      */
7550 /*   status is unchanged if both are good                             */
7551 /*                                                                    */
7552 /* returns non-zero if status is changed, 0 otherwise                 */
7553 /*                                                                    */
7554 /* Restrictions enforced:                                             */
7555 /*                                                                    */
7556 /*   digits, emax, and -emin in the context must be less than         */
7557 /*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7558 /*   non-zero.  Invalid_operation is set in the status if a           */
7559 /*   restriction is violated.                                         */
7560 /* ------------------------------------------------------------------ */
7561 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7562                          uInt *status) {
7563   uInt save=*status;                         /* record  */
7564   if (set->digits>DEC_MAX_MATH
7565    || set->emax>DEC_MAX_MATH
7566    || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7567    else if ((rhs->digits>DEC_MAX_MATH
7568      || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7569      || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7570      && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7571   return (*status!=save);
7572   } /* decCheckMath  */
7573 
7574 /* ------------------------------------------------------------------ */
7575 /* decGetInt -- get integer from a number                             */
7576 /*                                                                    */
7577 /*   dn is the number [which will not be altered]                     */
7578 /*                                                                    */
7579 /*   returns one of:                                                  */
7580 /*     BADINT if there is a non-zero fraction                         */
7581 /*     the converted integer                                          */
7582 /*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7583 /*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7584 /*                                                                    */
7585 /* This checks and gets a whole number from the input decNumber.      */
7586 /* The sign can be determined from dn by the caller when BIGEVEN or   */
7587 /* BIGODD is returned.                                                */
7588 /* ------------------------------------------------------------------ */
7589 static Int decGetInt(const decNumber *dn) {
7590   Int  theInt;                          /* result accumulator  */
7591   const Unit *up;                       /* work  */
7592   Int  got;                             /* digits (real or not) processed  */
7593   Int  ilength=dn->digits+dn->exponent; /* integral length  */
7594   Flag neg=decNumberIsNegative(dn);     /* 1 if -ve  */
7595 
7596   /* The number must be an integer that fits in 10 digits  */
7597   /* Assert, here, that 10 is enough for any rescale Etiny  */
7598   #if DEC_MAX_EMAX > 999999999
7599     #error GetInt may need updating [for Emax]
7600   #endif
7601   #if DEC_MIN_EMIN < -999999999
7602     #error GetInt may need updating [for Emin]
7603   #endif
7604   if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent  */
7605 
7606   up=dn->lsu;                           /* ready for lsu  */
7607   theInt=0;                             /* ready to accumulate  */
7608   if (dn->exponent>=0) {                /* relatively easy  */
7609     /* no fractional part [usual]; allow for positive exponent  */
7610     got=dn->exponent;
7611     }
7612    else { /* -ve exponent; some fractional part to check and discard  */
7613     Int count=-dn->exponent;            /* digits to discard  */
7614     /* spin up whole units until reach the Unit with the unit digit  */
7615     for (; count>=DECDPUN; up++) {
7616       if (*up!=0) return BADINT;        /* non-zero Unit to discard  */
7617       count-=DECDPUN;
7618       }
7619     if (count==0) got=0;                /* [a multiple of DECDPUN]  */
7620      else {                             /* [not multiple of DECDPUN]  */
7621       Int rem;                          /* work  */
7622       /* slice off fraction digits and check for non-zero  */
7623       #if DECDPUN<=4
7624         theInt=QUOT10(*up, count);
7625         rem=*up-theInt*powers[count];
7626       #else
7627         rem=*up%powers[count];          /* slice off discards  */
7628         theInt=*up/powers[count];
7629       #endif
7630       if (rem!=0) return BADINT;        /* non-zero fraction  */
7631       /* it looks good  */
7632       got=DECDPUN-count;                /* number of digits so far  */
7633       up++;                             /* ready for next  */
7634       }
7635     }
7636   /* now it's known there's no fractional part  */
7637 
7638   /* tricky code now, to accumulate up to 9.3 digits  */
7639   if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there  */
7640 
7641   if (ilength<11) {
7642     Int save=theInt;
7643     /* collect any remaining unit(s)  */
7644     for (; got<ilength; up++) {
7645       theInt+=*up*powers[got];
7646       got+=DECDPUN;
7647       }
7648     if (ilength==10) {                  /* need to check for wrap  */
7649       if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7650          /* [that test also disallows the BADINT result case]  */
7651        else if (neg && theInt>1999999997) ilength=11;
7652        else if (!neg && theInt>999999999) ilength=11;
7653       if (ilength==11) theInt=save;     /* restore correct low bit  */
7654       }
7655     }
7656 
7657   if (ilength>10) {                     /* too big  */
7658     if (theInt&1) return BIGODD;        /* bottom bit 1  */
7659     return BIGEVEN;                     /* bottom bit 0  */
7660     }
7661 
7662   if (neg) theInt=-theInt;              /* apply sign  */
7663   return theInt;
7664   } /* decGetInt  */
7665 
7666 /* ------------------------------------------------------------------ */
7667 /* decDecap -- decapitate the coefficient of a number                 */
7668 /*                                                                    */
7669 /*   dn   is the number to be decapitated                             */
7670 /*   drop is the number of digits to be removed from the left of dn;  */
7671 /*     this must be <= dn->digits (if equal, the coefficient is       */
7672 /*     set to 0)                                                      */
7673 /*                                                                    */
7674 /* Returns dn; dn->digits will be <= the initial digits less drop     */
7675 /* (after removing drop digits there may be leading zero digits       */
7676 /* which will also be removed).  Only dn->lsu and dn->digits change.  */
7677 /* ------------------------------------------------------------------ */
7678 static decNumber *decDecap(decNumber *dn, Int drop) {
7679   Unit *msu;                            /* -> target cut point  */
7680   Int cut;                              /* work  */
7681   if (drop>=dn->digits) {               /* losing the whole thing  */
7682     #if DECCHECK
7683     if (drop>dn->digits)
7684       printf("decDecap called with drop>digits [%ld>%ld]\n",
7685              (LI)drop, (LI)dn->digits);
7686     #endif
7687     dn->lsu[0]=0;
7688     dn->digits=1;
7689     return dn;
7690     }
7691   msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu  */
7692   cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu  */
7693   if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits  */
7694   /* that may have left leading zero digits, so do a proper count...  */
7695   dn->digits=decGetDigits(dn->lsu, static_cast<int32_t>(msu-dn->lsu+1));
7696   return dn;
7697   } /* decDecap  */
7698 
7699 /* ------------------------------------------------------------------ */
7700 /* decBiStr -- compare string with pairwise options                   */
7701 /*                                                                    */
7702 /*   targ is the string to compare                                    */
7703 /*   str1 is one of the strings to compare against (length may be 0)  */
7704 /*   str2 is the other; it must be the same length as str1            */
7705 /*                                                                    */
7706 /*   returns 1 if strings compare equal, (that is, it is the same     */
7707 /*   length as str1 and str2, and each character of targ is in either */
7708 /*   str1 or str2 in the corresponding position), or 0 otherwise      */
7709 /*                                                                    */
7710 /* This is used for generic caseless compare, including the awkward   */
7711 /* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7712 /*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7713 /* ------------------------------------------------------------------ */
7714 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7715   for (;;targ++, str1++, str2++) {
7716     if (*targ!=*str1 && *targ!=*str2) return 0;
7717     /* *targ has a match in one (or both, if terminator)  */
7718     if (*targ=='\0') break;
7719     } /* forever  */
7720   return 1;
7721   } /* decBiStr  */
7722 
7723 /* ------------------------------------------------------------------ */
7724 /* decNaNs -- handle NaN operand or operands                          */
7725 /*                                                                    */
7726 /*   res     is the result number                                     */
7727 /*   lhs     is the first operand                                     */
7728 /*   rhs     is the second operand, or NULL if none                   */
7729 /*   context is used to limit payload length                          */
7730 /*   status  contains the current status                              */
7731 /*   returns res in case convenient                                   */
7732 /*                                                                    */
7733 /* Called when one or both operands is a NaN, and propagates the      */
7734 /* appropriate result to res.  When an sNaN is found, it is changed   */
7735 /* to a qNaN and Invalid operation is set.                            */
7736 /* ------------------------------------------------------------------ */
7737 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7738                            const decNumber *rhs, decContext *set,
7739                            uInt *status) {
7740   /* This decision tree ends up with LHS being the source pointer,  */
7741   /* and status updated if need be  */
7742   if (lhs->bits & DECSNAN)
7743     *status|=DEC_Invalid_operation | DEC_sNaN;
7744    else if (rhs==NULL);
7745    else if (rhs->bits & DECSNAN) {
7746     lhs=rhs;
7747     *status|=DEC_Invalid_operation | DEC_sNaN;
7748     }
7749    else if (lhs->bits & DECNAN);
7750    else lhs=rhs;
7751 
7752   /* propagate the payload  */
7753   if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy  */
7754    else { /* too long  */
7755     const Unit *ul;
7756     Unit *ur, *uresp1;
7757     /* copy safe number of units, then decapitate  */
7758     res->bits=lhs->bits;                /* need sign etc.  */
7759     uresp1=res->lsu+D2U(set->digits);
7760     for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7761     res->digits=D2U(set->digits)*DECDPUN;
7762     /* maybe still too long  */
7763     if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7764     }
7765 
7766   res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while  */
7767   res->bits|=DECNAN;          /* .. preserving sign  */
7768   res->exponent=0;            /* clean exponent  */
7769                               /* [coefficient was copied/decapitated]  */
7770   return res;
7771   } /* decNaNs  */
7772 
7773 /* ------------------------------------------------------------------ */
7774 /* decStatus -- apply non-zero status                                 */
7775 /*                                                                    */
7776 /*   dn     is the number to set if error                             */
7777 /*   status contains the current status (not yet in context)          */
7778 /*   set    is the context                                            */
7779 /*                                                                    */
7780 /* If the status is an error status, the number is set to a NaN,      */
7781 /* unless the error was an overflow, divide-by-zero, or underflow,    */
7782 /* in which case the number will have already been set.               */
7783 /*                                                                    */
7784 /* The context status is then updated with the new status.  Note that */
7785 /* this may raise a signal, so control may never return from this     */
7786 /* routine (hence resources must be recovered before it is called).   */
7787 /* ------------------------------------------------------------------ */
7788 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7789   if (status & DEC_NaNs) {              /* error status -> NaN  */
7790     /* if cause was an sNaN, clear and propagate [NaN is already set up]  */
7791     if (status & DEC_sNaN) status&=~DEC_sNaN;
7792      else {
7793       uprv_decNumberZero(dn);                /* other error: clean throughout  */
7794       dn->bits=DECNAN;                  /* and make a quiet NaN  */
7795       }
7796     }
7797   uprv_decContextSetStatus(set, status);     /* [may not return]  */
7798   return;
7799   } /* decStatus  */
7800 
7801 /* ------------------------------------------------------------------ */
7802 /* decGetDigits -- count digits in a Units array                      */
7803 /*                                                                    */
7804 /*   uar is the Unit array holding the number (this is often an       */
7805 /*          accumulator of some sort)                                 */
7806 /*   len is the length of the array in units [>=1]                    */
7807 /*                                                                    */
7808 /*   returns the number of (significant) digits in the array          */
7809 /*                                                                    */
7810 /* All leading zeros are excluded, except the last if the array has   */
7811 /* only zero Units.                                                   */
7812 /* ------------------------------------------------------------------ */
7813 /* This may be called twice during some operations.  */
7814 static Int decGetDigits(Unit *uar, Int len) {
7815   Unit *up=uar+(len-1);            /* -> msu  */
7816   Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu  */
7817   #if DECDPUN>4
7818   uInt const *pow;                 /* work  */
7819   #endif
7820                                    /* (at least 1 in final msu)  */
7821   #if DECCHECK
7822   if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7823   #endif
7824 
7825   for (; up>=uar; up--) {
7826     if (*up==0) {                  /* unit is all 0s  */
7827       if (digits==1) break;        /* a zero has one digit  */
7828       digits-=DECDPUN;             /* adjust for 0 unit  */
7829       continue;}
7830     /* found the first (most significant) non-zero Unit  */
7831     #if DECDPUN>1                  /* not done yet  */
7832     if (*up<10) break;             /* is 1-9  */
7833     digits++;
7834     #if DECDPUN>2                  /* not done yet  */
7835     if (*up<100) break;            /* is 10-99  */
7836     digits++;
7837     #if DECDPUN>3                  /* not done yet  */
7838     if (*up<1000) break;           /* is 100-999  */
7839     digits++;
7840     #if DECDPUN>4                  /* count the rest ...  */
7841     for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7842     #endif
7843     #endif
7844     #endif
7845     #endif
7846     break;
7847     } /* up  */
7848   return digits;
7849   } /* decGetDigits  */
7850 
7851 #if DECTRACE | DECCHECK
7852 /* ------------------------------------------------------------------ */
7853 /* decNumberShow -- display a number [debug aid]                      */
7854 /*   dn is the number to show                                         */
7855 /*                                                                    */
7856 /* Shows: sign, exponent, coefficient (msu first), digits             */
7857 /*    or: sign, special-value                                         */
7858 /* ------------------------------------------------------------------ */
7859 /* this is public so other modules can use it  */
7860 void uprv_decNumberShow(const decNumber *dn) {
7861   const Unit *up;                  /* work  */
7862   uInt u, d;                       /* ..  */
7863   Int cut;                         /* ..  */
7864   char isign='+';                  /* main sign  */
7865   if (dn==NULL) {
7866     printf("NULL\n");
7867     return;}
7868   if (decNumberIsNegative(dn)) isign='-';
7869   printf(" >> %c ", isign);
7870   if (dn->bits&DECSPECIAL) {       /* Is a special value  */
7871     if (decNumberIsInfinite(dn)) printf("Infinity");
7872      else {                                  /* a NaN  */
7873       if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN  */
7874        else printf("NaN");
7875       }
7876     /* if coefficient and exponent are 0, no more to do  */
7877     if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7878       printf("\n");
7879       return;}
7880     /* drop through to report other information  */
7881     printf(" ");
7882     }
7883 
7884   /* now carefully display the coefficient  */
7885   up=dn->lsu+D2U(dn->digits)-1;         /* msu  */
7886   printf("%ld", (LI)*up);
7887   for (up=up-1; up>=dn->lsu; up--) {
7888     u=*up;
7889     printf(":");
7890     for (cut=DECDPUN-1; cut>=0; cut--) {
7891       d=u/powers[cut];
7892       u-=d*powers[cut];
7893       printf("%ld", (LI)d);
7894       } /* cut  */
7895     } /* up  */
7896   if (dn->exponent!=0) {
7897     char esign='+';
7898     if (dn->exponent<0) esign='-';
7899     printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7900     }
7901   printf(" [%ld]\n", (LI)dn->digits);
7902   } /* decNumberShow  */
7903 #endif
7904 
7905 #if DECTRACE || DECCHECK
7906 /* ------------------------------------------------------------------ */
7907 /* decDumpAr -- display a unit array [debug/check aid]                */
7908 /*   name is a single-character tag name                              */
7909 /*   ar   is the array to display                                     */
7910 /*   len  is the length of the array in Units                         */
7911 /* ------------------------------------------------------------------ */
7912 static void decDumpAr(char name, const Unit *ar, Int len) {
7913   Int i;
7914   const char *spec;
7915   #if DECDPUN==9
7916     spec="%09d ";
7917   #elif DECDPUN==8
7918     spec="%08d ";
7919   #elif DECDPUN==7
7920     spec="%07d ";
7921   #elif DECDPUN==6
7922     spec="%06d ";
7923   #elif DECDPUN==5
7924     spec="%05d ";
7925   #elif DECDPUN==4
7926     spec="%04d ";
7927   #elif DECDPUN==3
7928     spec="%03d ";
7929   #elif DECDPUN==2
7930     spec="%02d ";
7931   #else
7932     spec="%d ";
7933   #endif
7934   printf("  :%c: ", name);
7935   for (i=len-1; i>=0; i--) {
7936     if (i==len-1) printf("%ld ", (LI)ar[i]);
7937      else printf(spec, ar[i]);
7938     }
7939   printf("\n");
7940   return;}
7941 #endif
7942 
7943 #if DECCHECK
7944 /* ------------------------------------------------------------------ */
7945 /* decCheckOperands -- check operand(s) to a routine                  */
7946 /*   res is the result structure (not checked; it will be set to      */
7947 /*          quiet NaN if error found (and it is not NULL))            */
7948 /*   lhs is the first operand (may be DECUNRESU)                      */
7949 /*   rhs is the second (may be DECUNUSED)                             */
7950 /*   set is the context (may be DECUNCONT)                            */
7951 /*   returns 0 if both operands, and the context are clean, or 1      */
7952 /*     otherwise (in which case the context will show an error,       */
7953 /*     unless NULL).  Note that res is not cleaned; caller should     */
7954 /*     handle this so res=NULL case is safe.                          */
7955 /* The caller is expected to abandon immediately if 1 is returned.    */
7956 /* ------------------------------------------------------------------ */
7957 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7958                              const decNumber *rhs, decContext *set) {
7959   Flag bad=0;
7960   if (set==NULL) {                 /* oops; hopeless  */
7961     #if DECTRACE || DECVERB
7962     printf("Reference to context is NULL.\n");
7963     #endif
7964     bad=1;
7965     return 1;}
7966    else if (set!=DECUNCONT
7967      && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7968     bad=1;
7969     #if DECTRACE || DECVERB
7970     printf("Bad context [digits=%ld round=%ld].\n",
7971            (LI)set->digits, (LI)set->round);
7972     #endif
7973     }
7974    else {
7975     if (res==NULL) {
7976       bad=1;
7977       #if DECTRACE
7978       /* this one not DECVERB as standard tests include NULL  */
7979       printf("Reference to result is NULL.\n");
7980       #endif
7981       }
7982     if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7983     if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7984     }
7985   if (bad) {
7986     if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7987     if (res!=DECUNRESU && res!=NULL) {
7988       uprv_decNumberZero(res);
7989       res->bits=DECNAN;       /* qNaN  */
7990       }
7991     }
7992   return bad;
7993   } /* decCheckOperands  */
7994 
7995 /* ------------------------------------------------------------------ */
7996 /* decCheckNumber -- check a number                                   */
7997 /*   dn is the number to check                                        */
7998 /*   returns 0 if the number is clean, or 1 otherwise                 */
7999 /*                                                                    */
8000 /* The number is considered valid if it could be a result from some   */
8001 /* operation in some valid context.                                   */
8002 /* ------------------------------------------------------------------ */
8003 static Flag decCheckNumber(const decNumber *dn) {
8004   const Unit *up;             /* work  */
8005   uInt maxuint;               /* ..  */
8006   Int ae, d, digits;          /* ..  */
8007   Int emin, emax;             /* ..  */
8008 
8009   if (dn==NULL) {             /* hopeless  */
8010     #if DECTRACE
8011     /* this one not DECVERB as standard tests include NULL  */
8012     printf("Reference to decNumber is NULL.\n");
8013     #endif
8014     return 1;}
8015 
8016   /* check special values  */
8017   if (dn->bits & DECSPECIAL) {
8018     if (dn->exponent!=0) {
8019       #if DECTRACE || DECVERB
8020       printf("Exponent %ld (not 0) for a special value [%02x].\n",
8021              (LI)dn->exponent, dn->bits);
8022       #endif
8023       return 1;}
8024 
8025     /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only  */
8026     if (decNumberIsInfinite(dn)) {
8027       if (dn->digits!=1) {
8028         #if DECTRACE || DECVERB
8029         printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8030         #endif
8031         return 1;}
8032       if (*dn->lsu!=0) {
8033         #if DECTRACE || DECVERB
8034         printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8035         #endif
8036         decDumpAr('I', dn->lsu, D2U(dn->digits));
8037         return 1;}
8038       } /* Inf  */
8039     /* 2002.12.26: negative NaNs can now appear through proposed IEEE  */
8040     /*             concrete formats (decimal64, etc.).  */
8041     return 0;
8042     }
8043 
8044   /* check the coefficient  */
8045   if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8046     #if DECTRACE || DECVERB
8047     printf("Digits %ld in number.\n", (LI)dn->digits);
8048     #endif
8049     return 1;}
8050 
8051   d=dn->digits;
8052 
8053   for (up=dn->lsu; d>0; up++) {
8054     if (d>DECDPUN) maxuint=DECDPUNMAX;
8055      else {                   /* reached the msu  */
8056       maxuint=powers[d]-1;
8057       if (dn->digits>1 && *up<powers[d-1]) {
8058         #if DECTRACE || DECVERB
8059         printf("Leading 0 in number.\n");
8060         uprv_decNumberShow(dn);
8061         #endif
8062         return 1;}
8063       }
8064     if (*up>maxuint) {
8065       #if DECTRACE || DECVERB
8066       printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8067               (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8068       #endif
8069       return 1;}
8070     d-=DECDPUN;
8071     }
8072 
8073   /* check the exponent.  Note that input operands can have exponents  */
8074   /* which are out of the set->emin/set->emax and set->digits range  */
8075   /* (just as they can have more digits than set->digits).  */
8076   ae=dn->exponent+dn->digits-1;    /* adjusted exponent  */
8077   emax=DECNUMMAXE;
8078   emin=DECNUMMINE;
8079   digits=DECNUMMAXP;
8080   if (ae<emin-(digits-1)) {
8081     #if DECTRACE || DECVERB
8082     printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8083     uprv_decNumberShow(dn);
8084     #endif
8085     return 1;}
8086   if (ae>+emax) {
8087     #if DECTRACE || DECVERB
8088     printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8089     uprv_decNumberShow(dn);
8090     #endif
8091     return 1;}
8092 
8093   return 0;              /* it's OK  */
8094   } /* decCheckNumber  */
8095 
8096 /* ------------------------------------------------------------------ */
8097 /* decCheckInexact -- check a normal finite inexact result has digits */
8098 /*   dn is the number to check                                        */
8099 /*   set is the context (for status and precision)                    */
8100 /*   sets Invalid operation, etc., if some digits are missing         */
8101 /* [this check is not made for DECSUBSET compilation or when          */
8102 /* subnormal is not set]                                              */
8103 /* ------------------------------------------------------------------ */
8104 static void decCheckInexact(const decNumber *dn, decContext *set) {
8105   #if !DECSUBSET && DECEXTFLAG
8106     if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8107      && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8108       #if DECTRACE || DECVERB
8109       printf("Insufficient digits [%ld] on normal Inexact result.\n",
8110              (LI)dn->digits);
8111       uprv_decNumberShow(dn);
8112       #endif
8113       uprv_decContextSetStatus(set, DEC_Invalid_operation);
8114       }
8115   #else
8116     /* next is a noop for quiet compiler  */
8117     if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8118   #endif
8119   return;
8120   } /* decCheckInexact  */
8121 #endif
8122 
8123 #if DECALLOC
8124 #undef malloc
8125 #undef free
8126 /* ------------------------------------------------------------------ */
8127 /* decMalloc -- accountable allocation routine                        */
8128 /*   n is the number of bytes to allocate                             */
8129 /*                                                                    */
8130 /* Semantics is the same as the stdlib malloc routine, but bytes      */
8131 /* allocated are accounted for globally, and corruption fences are    */
8132 /* added before and after the 'actual' storage.                       */
8133 /* ------------------------------------------------------------------ */
8134 /* This routine allocates storage with an extra twelve bytes; 8 are   */
8135 /* at the start and hold:                                             */
8136 /*   0-3 the original length requested                                */
8137 /*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8138 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8139 /* ------------------------------------------------------------------ */
8140 static void *decMalloc(size_t n) {
8141   uInt  size=n+12;                 /* true size  */
8142   void  *alloc;                    /* -> allocated storage  */
8143   uByte *b, *b0;                   /* work  */
8144   uInt  uiwork;                    /* for macros  */
8145 
8146   alloc=malloc(size);              /* -> allocated storage  */
8147   if (alloc==NULL) return NULL;    /* out of strorage  */
8148   b0=(uByte *)alloc;               /* as bytes  */
8149   decAllocBytes+=n;                /* account for storage  */
8150   UBFROMUI(alloc, n);              /* save n  */
8151   /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);  */
8152   for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8153   for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8154   return b0+8;                     /* -> play area  */
8155   } /* decMalloc  */
8156 
8157 /* ------------------------------------------------------------------ */
8158 /* decFree -- accountable free routine                                */
8159 /*   alloc is the storage to free                                     */
8160 /*                                                                    */
8161 /* Semantics is the same as the stdlib malloc routine, except that    */
8162 /* the global storage accounting is updated and the fences are        */
8163 /* checked to ensure that no routine has written 'out of bounds'.     */
8164 /* ------------------------------------------------------------------ */
8165 /* This routine first checks that the fences have not been corrupted. */
8166 /* It then frees the storage using the 'truw' storage address (that   */
8167 /* is, offset by 8).                                                  */
8168 /* ------------------------------------------------------------------ */
8169 static void decFree(void *alloc) {
8170   uInt  n;                         /* original length  */
8171   uByte *b, *b0;                   /* work  */
8172   uInt  uiwork;                    /* for macros  */
8173 
8174   if (alloc==NULL) return;         /* allowed; it's a nop  */
8175   b0=(uByte *)alloc;               /* as bytes  */
8176   b0-=8;                           /* -> true start of storage  */
8177   n=UBTOUI(b0);                    /* lift length  */
8178   for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8179     printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8180            b-b0-8, (LI)b0);
8181   for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8182     printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8183            b-b0-8, (LI)b0, (LI)n);
8184   free(b0);                        /* drop the storage  */
8185   decAllocBytes-=n;                /* account for storage  */
8186   /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);  */
8187   } /* decFree  */
8188 #define malloc(a) decMalloc(a)
8189 #define free(a) decFree(a)
8190 #endif
8191