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