]> git.saurik.com Git - apple/icu.git/blame - icuSources/i18n/decNumber.c
ICU-491.11.1.tar.gz
[apple/icu.git] / icuSources / i18n / decNumber.c
CommitLineData
729e4ab9
A
1/* ------------------------------------------------------------------ */
2/* Decimal Number arithmetic module */
3/* ------------------------------------------------------------------ */
4388f060 4/* Copyright (c) IBM Corporation, 2000-2012. All rights reserved. */
729e4ab9
A
5/* */
6/* This software is made available under the terms of the */
7/* ICU License -- ICU 1.8.1 and later. */
8/* */
9/* The description and User's Guide ("The decNumber C Library") for */
10/* this software is called decNumber.pdf. This document is */
11/* available, together with arithmetic and format specifications, */
12/* testcases, and Web links, on the General Decimal Arithmetic page. */
13/* */
14/* Please send comments, suggestions, and corrections to the author: */
15/* mfc@uk.ibm.com */
16/* Mike Cowlishaw, IBM Fellow */
17/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
18/* ------------------------------------------------------------------ */
19
20/* Modified version, for use from within ICU.
21 * Renamed public functions, to avoid an unwanted export of the
22 * standard names from the ICU library.
23 *
24 * Use ICU's uprv_malloc() and uprv_free()
25 *
26 * Revert comment syntax to plain C
27 *
28 * Remove a few compiler warnings.
29 */
30
31/* This module comprises the routines for arbitrary-precision General */
32/* Decimal Arithmetic as defined in the specification which may be */
33/* found on the General Decimal Arithmetic pages. It implements both */
34/* the full ('extended') arithmetic and the simpler ('subset') */
35/* arithmetic. */
36/* */
37/* Usage notes: */
38/* */
39/* 1. This code is ANSI C89 except: */
40/* */
41/* a) C99 line comments (double forward slash) are used. (Most C */
42/* compilers accept these. If yours does not, a simple script */
43/* can be used to convert them to ANSI C comments.) */
44/* */
45/* b) Types from C99 stdint.h are used. If you do not have this */
46/* header file, see the User's Guide section of the decNumber */
47/* documentation; this lists the necessary definitions. */
48/* */
49/* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
50/* uint64_t types may be used. To avoid these, set DECUSE64=0 */
51/* and DECDPUN<=4 (see documentation). */
52/* */
53/* The code also conforms to C99 restrictions; in particular, */
54/* strict aliasing rules are observed. */
55/* */
56/* 2. The decNumber format which this library uses is optimized for */
57/* efficient processing of relatively short numbers; in particular */
58/* it allows the use of fixed sized structures and minimizes copy */
59/* and move operations. It does, however, support arbitrary */
60/* precision (up to 999,999,999 digits) and arbitrary exponent */
61/* range (Emax in the range 0 through 999,999,999 and Emin in the */
62/* range -999,999,999 through 0). Mathematical functions (for */
63/* example decNumberExp) as identified below are restricted more */
64/* tightly: digits, emax, and -emin in the context must be <= */
65/* DEC_MAX_MATH (999999), and their operand(s) must be within */
66/* these bounds. */
67/* */
68/* 3. Logical functions are further restricted; their operands must */
69/* be finite, positive, have an exponent of zero, and all digits */
70/* must be either 0 or 1. The result will only contain digits */
71/* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
72/* */
73/* 4. Operands to operator functions are never modified unless they */
74/* are also specified to be the result number (which is always */
75/* permitted). Other than that case, operands must not overlap. */
76/* */
77/* 5. Error handling: the type of the error is ORed into the status */
78/* flags in the current context (decContext structure). The */
79/* SIGFPE signal is then raised if the corresponding trap-enabler */
80/* flag in the decContext is set (is 1). */
81/* */
82/* It is the responsibility of the caller to clear the status */
83/* flags as required. */
84/* */
85/* The result of any routine which returns a number will always */
86/* be a valid number (which may be a special value, such as an */
87/* Infinity or NaN). */
88/* */
89/* 6. The decNumber format is not an exchangeable concrete */
90/* representation as it comprises fields which may be machine- */
91/* dependent (packed or unpacked, or special length, for example). */
92/* Canonical conversions to and from strings are provided; other */
93/* conversions are available in separate modules. */
94/* */
95/* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
96/* to 1 for extended operand checking (including NULL operands). */
97/* Results are undefined if a badly-formed structure (or a NULL */
98/* pointer to a structure) is provided, though with DECCHECK */
99/* enabled the operator routines are protected against exceptions. */
100/* (Except if the result pointer is NULL, which is unrecoverable.) */
101/* */
102/* However, the routines will never cause exceptions if they are */
103/* given well-formed operands, even if the value of the operands */
104/* is inappropriate for the operation and DECCHECK is not set. */
105/* (Except for SIGFPE, as and where documented.) */
106/* */
107/* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
108/* ------------------------------------------------------------------ */
109/* Implementation notes for maintenance of this module: */
110/* */
111/* 1. Storage leak protection: Routines which use malloc are not */
112/* permitted to use return for fastpath or error exits (i.e., */
113/* they follow strict structured programming conventions). */
114/* Instead they have a do{}while(0); construct surrounding the */
115/* code which is protected -- break may be used to exit this. */
116/* Other routines can safely use the return statement inline. */
117/* */
118/* Storage leak accounting can be enabled using DECALLOC. */
119/* */
120/* 2. All loops use the for(;;) construct. Any do construct does */
121/* not loop; it is for allocation protection as just described. */
122/* */
123/* 3. Setting status in the context must always be the very last */
124/* action in a routine, as non-0 status may raise a trap and hence */
125/* the call to set status may not return (if the handler uses long */
126/* jump). Therefore all cleanup must be done first. In general, */
127/* to achieve this status is accumulated and is only applied just */
128/* before return by calling decContextSetStatus (via decStatus). */
129/* */
130/* Routines which allocate storage cannot, in general, use the */
131/* 'top level' routines which could cause a non-returning */
132/* transfer of control. The decXxxxOp routines are safe (do not */
133/* call decStatus even if traps are set in the context) and should */
134/* be used instead (they are also a little faster). */
135/* */
136/* 4. Exponent checking is minimized by allowing the exponent to */
137/* grow outside its limits during calculations, provided that */
138/* the decFinalize function is called later. Multiplication and */
139/* division, and intermediate calculations in exponentiation, */
140/* require more careful checks because of the risk of 31-bit */
141/* overflow (the most negative valid exponent is -1999999997, for */
142/* a 999999999-digit number with adjusted exponent of -999999999). */
143/* */
144/* 5. Rounding is deferred until finalization of results, with any */
145/* 'off to the right' data being represented as a single digit */
146/* residue (in the range -1 through 9). This avoids any double- */
147/* rounding when more than one shortening takes place (for */
148/* example, when a result is subnormal). */
149/* */
150/* 6. The digits count is allowed to rise to a multiple of DECDPUN */
151/* during many operations, so whole Units are handled and exact */
152/* accounting of digits is not needed. The correct digits value */
153/* is found by decGetDigits, which accounts for leading zeros. */
154/* This must be called before any rounding if the number of digits */
155/* is not known exactly. */
156/* */
157/* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
158/* numbers up to four digits, using appropriate constants. This */
159/* is not useful for longer numbers because overflow of 32 bits */
160/* would lead to 4 multiplies, which is almost as expensive as */
161/* a divide (unless a floating-point or 64-bit multiply is */
162/* assumed to be available). */
163/* */
164/* 8. Unusual abbreviations that may be used in the commentary: */
165/* lhs -- left hand side (operand, of an operation) */
166/* lsd -- least significant digit (of coefficient) */
167/* lsu -- least significant Unit (of coefficient) */
168/* msd -- most significant digit (of coefficient) */
169/* msi -- most significant item (in an array) */
170/* msu -- most significant Unit (of coefficient) */
171/* rhs -- right hand side (operand, of an operation) */
172/* +ve -- positive */
173/* -ve -- negative */
174/* ** -- raise to the power */
175/* ------------------------------------------------------------------ */
176
177#include <stdlib.h> /* for malloc, free, etc. */
178/* #include <stdio.h> */ /* for printf [if needed] */
179#include <string.h> /* for strcpy */
180#include <ctype.h> /* for lower */
181#include "cmemory.h" /* for uprv_malloc, etc., in ICU */
182#include "decNumber.h" /* base number library */
183#include "decNumberLocal.h" /* decNumber local types, etc. */
4388f060 184#include "uassert.h"
729e4ab9
A
185
186/* Constants */
187/* Public lookup table used by the D2U macro */
188const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
189
190#define DECVERB 1 /* set to 1 for verbose DECCHECK */
191#define powers DECPOWERS /* old internal name */
192
193/* Local constants */
194#define DIVIDE 0x80 /* Divide operators */
195#define REMAINDER 0x40 /* .. */
196#define DIVIDEINT 0x20 /* .. */
197#define REMNEAR 0x10 /* .. */
198#define COMPARE 0x01 /* Compare operators */
199#define COMPMAX 0x02 /* .. */
200#define COMPMIN 0x03 /* .. */
201#define COMPTOTAL 0x04 /* .. */
202#define COMPNAN 0x05 /* .. [NaN processing] */
203#define COMPSIG 0x06 /* .. [signaling COMPARE] */
204#define COMPMAXMAG 0x07 /* .. */
205#define COMPMINMAG 0x08 /* .. */
206
207#define DEC_sNaN 0x40000000 /* local status: sNaN signal */
208#define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
209/* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
210#define BIGEVEN (Int)0x80000002
211#define BIGODD (Int)0x80000003
212
213static Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */
214
215/* Granularity-dependent code */
216#if DECDPUN<=4
217 #define eInt Int /* extended integer */
218 #define ueInt uInt /* unsigned extended integer */
219 /* Constant multipliers for divide-by-power-of five using reciprocal */
220 /* multiply, after removing powers of 2 by shifting, and final shift */
221 /* of 17 [we only need up to **4] */
222 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
223 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
224 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
225#else
226 /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
227 #if !DECUSE64
228 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
229 #endif
230 #define eInt Long /* extended integer */
231 #define ueInt uLong /* unsigned extended integer */
232#endif
233
234/* Local routines */
235static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
236 decContext *, uByte, uInt *);
237static Flag decBiStr(const char *, const char *, const char *);
238static uInt decCheckMath(const decNumber *, decContext *, uInt *);
239static void decApplyRound(decNumber *, decContext *, Int, uInt *);
240static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
241static decNumber * decCompareOp(decNumber *, const decNumber *,
242 const decNumber *, decContext *,
243 Flag, uInt *);
244static void decCopyFit(decNumber *, const decNumber *, decContext *,
245 Int *, uInt *);
246static decNumber * decDecap(decNumber *, Int);
247static decNumber * decDivideOp(decNumber *, const decNumber *,
248 const decNumber *, decContext *, Flag, uInt *);
249static decNumber * decExpOp(decNumber *, const decNumber *,
250 decContext *, uInt *);
251static void decFinalize(decNumber *, decContext *, Int *, uInt *);
252static Int decGetDigits(Unit *, Int);
253static Int decGetInt(const decNumber *);
254static decNumber * decLnOp(decNumber *, const decNumber *,
255 decContext *, uInt *);
256static decNumber * decMultiplyOp(decNumber *, const decNumber *,
257 const decNumber *, decContext *,
258 uInt *);
259static decNumber * decNaNs(decNumber *, const decNumber *,
260 const decNumber *, decContext *, uInt *);
261static decNumber * decQuantizeOp(decNumber *, const decNumber *,
262 const decNumber *, decContext *, Flag,
263 uInt *);
264static void decReverse(Unit *, Unit *);
265static void decSetCoeff(decNumber *, decContext *, const Unit *,
266 Int, Int *, uInt *);
267static void decSetMaxValue(decNumber *, decContext *);
268static void decSetOverflow(decNumber *, decContext *, uInt *);
269static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
270static Int decShiftToLeast(Unit *, Int, Int);
271static Int decShiftToMost(Unit *, Int, Int);
272static void decStatus(decNumber *, uInt, decContext *);
273static void decToString(const decNumber *, char[], Flag);
274static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
275static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
276 Unit *, Int);
277static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
278
279#if !DECSUBSET
280/* decFinish == decFinalize when no subset arithmetic needed */
281#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
282#else
283static void decFinish(decNumber *, decContext *, Int *, uInt *);
284static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
285#endif
286
287/* Local macros */
288/* masked special-values bits */
289#define SPECIALARG (rhs->bits & DECSPECIAL)
290#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
291
292/* For use in ICU */
293#define malloc(a) uprv_malloc(a)
294#define free(a) uprv_free(a)
295
296/* Diagnostic macros, etc. */
297#if DECALLOC
298/* Handle malloc/free accounting. If enabled, our accountable routines */
299/* are used; otherwise the code just goes straight to the system malloc */
300/* and free routines. */
301#define malloc(a) decMalloc(a)
302#define free(a) decFree(a)
303#define DECFENCE 0x5a /* corruption detector */
304/* 'Our' malloc and free: */
305static void *decMalloc(size_t);
306static void decFree(void *);
307uInt decAllocBytes=0; /* count of bytes allocated */
308/* Note that DECALLOC code only checks for storage buffer overflow. */
309/* To check for memory leaks, the decAllocBytes variable must be */
310/* checked to be 0 at appropriate times (e.g., after the test */
311/* harness completes a set of tests). This checking may be unreliable */
312/* if the testing is done in a multi-thread environment. */
313#endif
314
315#if DECCHECK
316/* Optional checking routines. Enabling these means that decNumber */
317/* and decContext operands to operator routines are checked for */
318/* correctness. This roughly doubles the execution time of the */
319/* fastest routines (and adds 600+ bytes), so should not normally be */
320/* used in 'production'. */
321/* decCheckInexact is used to check that inexact results have a full */
322/* complement of digits (where appropriate -- this is not the case */
323/* for Quantize, for example) */
324#define DECUNRESU ((decNumber *)(void *)0xffffffff)
325#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
326#define DECUNCONT ((decContext *)(void *)(0xffffffff))
327static Flag decCheckOperands(decNumber *, const decNumber *,
328 const decNumber *, decContext *);
329static Flag decCheckNumber(const decNumber *);
330static void decCheckInexact(const decNumber *, decContext *);
331#endif
332
333#if DECTRACE || DECCHECK
334/* Optional trace/debugging routines (may or may not be used) */
335void decNumberShow(const decNumber *); /* displays the components of a number */
336static void decDumpAr(char, const Unit *, Int);
337#endif
338
339/* ================================================================== */
340/* Conversions */
341/* ================================================================== */
342
343/* ------------------------------------------------------------------ */
344/* from-int32 -- conversion from Int or uInt */
345/* */
346/* dn is the decNumber to receive the integer */
347/* in or uin is the integer to be converted */
348/* returns dn */
349/* */
350/* No error is possible. */
351/* ------------------------------------------------------------------ */
352U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
353 uInt unsig;
354 if (in>=0) unsig=in;
355 else { /* negative (possibly BADINT) */
356 if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
357 else unsig=-in; /* invert */
358 }
359 /* in is now positive */
360 uprv_decNumberFromUInt32(dn, unsig);
361 if (in<0) dn->bits=DECNEG; /* sign needed */
362 return dn;
363 } /* decNumberFromInt32 */
364
365U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
366 Unit *up; /* work pointer */
367 uprv_decNumberZero(dn); /* clean */
368 if (uin==0) return dn; /* [or decGetDigits bad call] */
369 for (up=dn->lsu; uin>0; up++) {
370 *up=(Unit)(uin%(DECDPUNMAX+1));
371 uin=uin/(DECDPUNMAX+1);
372 }
373 dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
374 return dn;
375 } /* decNumberFromUInt32 */
376
377/* ------------------------------------------------------------------ */
378/* to-int32 -- conversion to Int or uInt */
379/* */
380/* dn is the decNumber to convert */
381/* set is the context for reporting errors */
382/* returns the converted decNumber, or 0 if Invalid is set */
383/* */
384/* Invalid is set if the decNumber does not have exponent==0 or if */
385/* it is a NaN, Infinite, or out-of-range. */
386/* ------------------------------------------------------------------ */
387U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
388 #if DECCHECK
389 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
390 #endif
391
392 /* special or too many digits, or bad exponent */
393 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
394 else { /* is a finite integer with 10 or fewer digits */
395 Int d; /* work */
396 const Unit *up; /* .. */
397 uInt hi=0, lo; /* .. */
398 up=dn->lsu; /* -> lsu */
399 lo=*up; /* get 1 to 9 digits */
400 #if DECDPUN>1 /* split to higher */
401 hi=lo/10;
402 lo=lo%10;
403 #endif
404 up++;
405 /* collect remaining Units, if any, into hi */
406 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
407 /* now low has the lsd, hi the remainder */
408 if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
409 /* most-negative is a reprieve */
410 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
411 /* bad -- drop through */
412 }
413 else { /* in-range always */
414 Int i=X10(hi)+lo;
415 if (dn->bits&DECNEG) return -i;
416 return i;
417 }
418 } /* integer */
419 uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
420 return 0;
421 } /* decNumberToInt32 */
422
423U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
424 #if DECCHECK
425 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
426 #endif
427 /* special or too many digits, or bad exponent, or negative (<0) */
428 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
429 || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
430 else { /* is a finite integer with 10 or fewer digits */
431 Int d; /* work */
432 const Unit *up; /* .. */
433 uInt hi=0, lo; /* .. */
434 up=dn->lsu; /* -> lsu */
435 lo=*up; /* get 1 to 9 digits */
436 #if DECDPUN>1 /* split to higher */
437 hi=lo/10;
438 lo=lo%10;
439 #endif
440 up++;
441 /* collect remaining Units, if any, into hi */
442 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
443
444 /* now low has the lsd, hi the remainder */
445 if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
446 else return X10(hi)+lo;
447 } /* integer */
448 uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
449 return 0;
450 } /* decNumberToUInt32 */
451
452/* ------------------------------------------------------------------ */
453/* to-scientific-string -- conversion to numeric string */
454/* to-engineering-string -- conversion to numeric string */
455/* */
456/* decNumberToString(dn, string); */
457/* decNumberToEngString(dn, string); */
458/* */
459/* dn is the decNumber to convert */
460/* string is the string where the result will be laid out */
461/* */
462/* string must be at least dn->digits+14 characters long */
463/* */
464/* No error is possible, and no status can be set. */
465/* ------------------------------------------------------------------ */
466U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
467 decToString(dn, string, 0);
468 return string;
469 } /* DecNumberToString */
470
471U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
472 decToString(dn, string, 1);
473 return string;
474 } /* DecNumberToEngString */
475
476/* ------------------------------------------------------------------ */
477/* to-number -- conversion from numeric string */
478/* */
479/* decNumberFromString -- convert string to decNumber */
480/* dn -- the number structure to fill */
481/* chars[] -- the string to convert ('\0' terminated) */
482/* set -- the context used for processing any error, */
483/* determining the maximum precision available */
484/* (set.digits), determining the maximum and minimum */
485/* exponent (set.emax and set.emin), determining if */
486/* extended values are allowed, and checking the */
487/* rounding mode if overflow occurs or rounding is */
488/* needed. */
489/* */
490/* The length of the coefficient and the size of the exponent are */
491/* checked by this routine, so the correct error (Underflow or */
492/* Overflow) can be reported or rounding applied, as necessary. */
493/* */
494/* If bad syntax is detected, the result will be a quiet NaN. */
495/* ------------------------------------------------------------------ */
496U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
497 decContext *set) {
498 Int exponent=0; /* working exponent [assume 0] */
499 uByte bits=0; /* working flags [assume +ve] */
500 Unit *res; /* where result will be built */
501 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
502 /* [+9 allows for ln() constants] */
503 Unit *allocres=NULL; /* -> allocated result, iff allocated */
504 Int d=0; /* count of digits found in decimal part */
505 const char *dotchar=NULL; /* where dot was found */
506 const char *cfirst=chars; /* -> first character of decimal part */
507 const char *last=NULL; /* -> last digit of decimal part */
508 const char *c; /* work */
509 Unit *up; /* .. */
510 #if DECDPUN>1
511 Int cut, out; /* .. */
512 #endif
513 Int residue; /* rounding residue */
514 uInt status=0; /* error code */
515
516 #if DECCHECK
517 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
518 return uprv_decNumberZero(dn);
519 #endif
520
521 do { /* status & malloc protection */
522 for (c=chars;; c++) { /* -> input character */
523 if (*c>='0' && *c<='9') { /* test for Arabic digit */
524 last=c;
525 d++; /* count of real digits */
526 continue; /* still in decimal part */
527 }
528 if (*c=='.' && dotchar==NULL) { /* first '.' */
529 dotchar=c; /* record offset into decimal part */
530 if (c==cfirst) cfirst++; /* first digit must follow */
531 continue;}
532 if (c==chars) { /* first in string... */
533 if (*c=='-') { /* valid - sign */
534 cfirst++;
535 bits=DECNEG;
536 continue;}
537 if (*c=='+') { /* valid + sign */
538 cfirst++;
539 continue;}
540 }
541 /* *c is not a digit, or a valid +, -, or '.' */
542 break;
543 } /* c */
544
545 if (last==NULL) { /* no digits yet */
546 status=DEC_Conversion_syntax;/* assume the worst */
547 if (*c=='\0') break; /* and no more to come... */
548 #if DECSUBSET
549 /* if subset then infinities and NaNs are not allowed */
550 if (!set->extended) break; /* hopeless */
551 #endif
552 /* Infinities and NaNs are possible, here */
553 if (dotchar!=NULL) break; /* .. unless had a dot */
554 uprv_decNumberZero(dn); /* be optimistic */
555 if (decBiStr(c, "infinity", "INFINITY")
556 || decBiStr(c, "inf", "INF")) {
557 dn->bits=bits | DECINF;
558 status=0; /* is OK */
559 break; /* all done */
560 }
561 /* a NaN expected */
562 /* 2003.09.10 NaNs are now permitted to have a sign */
563 dn->bits=bits | DECNAN; /* assume simple NaN */
564 if (*c=='s' || *c=='S') { /* looks like an sNaN */
565 c++;
566 dn->bits=bits | DECSNAN;
567 }
568 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
569 c++;
570 if (*c!='a' && *c!='A') break; /* .. */
571 c++;
572 if (*c!='n' && *c!='N') break; /* .. */
573 c++;
574 /* now either nothing, or nnnn payload, expected */
575 /* -> start of integer and skip leading 0s [including plain 0] */
576 for (cfirst=c; *cfirst=='0';) cfirst++;
577 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
578 status=0; /* it's good */
579 break; /* .. */
580 }
581 /* something other than 0s; setup last and d as usual [no dots] */
582 for (c=cfirst;; c++, d++) {
583 if (*c<'0' || *c>'9') break; /* test for Arabic digit */
584 last=c;
585 }
586 if (*c!='\0') break; /* not all digits */
587 if (d>set->digits-1) {
588 /* [NB: payload in a decNumber can be full length unless */
589 /* clamped, in which case can only be digits-1] */
590 if (set->clamp) break;
591 if (d>set->digits) break;
592 } /* too many digits? */
593 /* good; drop through to convert the integer to coefficient */
594 status=0; /* syntax is OK */
595 bits=dn->bits; /* for copy-back */
596 } /* last==NULL */
597
598 else if (*c!='\0') { /* more to process... */
599 /* had some digits; exponent is only valid sequence now */
600 Flag nege; /* 1=negative exponent */
601 const char *firstexp; /* -> first significant exponent digit */
602 status=DEC_Conversion_syntax;/* assume the worst */
603 if (*c!='e' && *c!='E') break;
604 /* Found 'e' or 'E' -- now process explicit exponent */
605 /* 1998.07.11: sign no longer required */
606 nege=0;
607 c++; /* to (possible) sign */
608 if (*c=='-') {nege=1; c++;}
609 else if (*c=='+') c++;
610 if (*c=='\0') break;
611
612 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
613 firstexp=c; /* save exponent digit place */
614 for (; ;c++) {
615 if (*c<'0' || *c>'9') break; /* not a digit */
616 exponent=X10(exponent)+(Int)*c-(Int)'0';
617 } /* c */
618 /* if not now on a '\0', *c must not be a digit */
619 if (*c!='\0') break;
620
621 /* (this next test must be after the syntax checks) */
622 /* if it was too long the exponent may have wrapped, so check */
623 /* carefully and set it to a certain overflow if wrap possible */
624 if (c>=firstexp+9+1) {
625 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
626 /* [up to 1999999999 is OK, for example 1E-1000000998] */
627 }
628 if (nege) exponent=-exponent; /* was negative */
629 status=0; /* is OK */
630 } /* stuff after digits */
631
632 /* Here when whole string has been inspected; syntax is good */
633 /* cfirst->first digit (never dot), last->last digit (ditto) */
634
635 /* strip leading zeros/dot [leave final 0 if all 0's] */
636 if (*cfirst=='0') { /* [cfirst has stepped over .] */
637 for (c=cfirst; c<last; c++, cfirst++) {
638 if (*c=='.') continue; /* ignore dots */
639 if (*c!='0') break; /* non-zero found */
640 d--; /* 0 stripped */
641 } /* c */
642 #if DECSUBSET
643 /* make a rapid exit for easy zeros if !extended */
644 if (*cfirst=='0' && !set->extended) {
645 uprv_decNumberZero(dn); /* clean result */
646 break; /* [could be return] */
647 }
648 #endif
649 } /* at least one leading 0 */
650
651 /* Handle decimal point... */
652 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */
653 exponent-=(last-dotchar); /* adjust exponent */
654 /* [we can now ignore the .] */
655
656 /* OK, the digits string is good. Assemble in the decNumber, or in */
657 /* a temporary units array if rounding is needed */
658 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
659 else { /* rounding needed */
660 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
661 res=resbuff; /* assume use local buffer */
662 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
663 allocres=(Unit *)malloc(needbytes);
664 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
665 res=allocres;
666 }
667 }
668 /* res now -> number lsu, buffer, or allocated storage for Unit array */
669
670 /* Place the coefficient into the selected Unit array */
671 /* [this is often 70% of the cost of this function when DECDPUN>1] */
672 #if DECDPUN>1
673 out=0; /* accumulator */
674 up=res+D2U(d)-1; /* -> msu */
675 cut=d-(up-res)*DECDPUN; /* digits in top unit */
676 for (c=cfirst;; c++) { /* along the digits */
677 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
678 out=X10(out)+(Int)*c-(Int)'0';
679 if (c==last) break; /* done [never get to trailing '.'] */
680 cut--;
681 if (cut>0) continue; /* more for this unit */
682 *up=(Unit)out; /* write unit */
683 up--; /* prepare for unit below.. */
684 cut=DECDPUN; /* .. */
685 out=0; /* .. */
686 } /* c */
687 *up=(Unit)out; /* write lsu */
688
689 #else
690 /* DECDPUN==1 */
691 up=res; /* -> lsu */
692 for (c=last; c>=cfirst; c--) { /* over each character, from least */
693 if (*c=='.') continue; /* ignore . [don't step up] */
694 *up=(Unit)((Int)*c-(Int)'0');
695 up++;
696 } /* c */
697 #endif
698
699 dn->bits=bits;
700 dn->exponent=exponent;
701 dn->digits=d;
702
703 /* if not in number (too long) shorten into the number */
704 if (d>set->digits) {
705 residue=0;
706 decSetCoeff(dn, set, res, d, &residue, &status);
707 /* always check for overflow or subnormal and round as needed */
708 decFinalize(dn, set, &residue, &status);
709 }
710 else { /* no rounding, but may still have overflow or subnormal */
711 /* [these tests are just for performance; finalize repeats them] */
712 if ((dn->exponent-1<set->emin-dn->digits)
713 || (dn->exponent-1>set->emax-set->digits)) {
714 residue=0;
715 decFinalize(dn, set, &residue, &status);
716 }
717 }
718 /* decNumberShow(dn); */
719 } while(0); /* [for break] */
720
721 if (allocres!=NULL) free(allocres); /* drop any storage used */
722 if (status!=0) decStatus(dn, status, set);
723 return dn;
724 } /* decNumberFromString */
725
726/* ================================================================== */
727/* Operators */
728/* ================================================================== */
729
730/* ------------------------------------------------------------------ */
731/* decNumberAbs -- absolute value operator */
732/* */
733/* This computes C = abs(A) */
734/* */
735/* res is C, the result. C may be A */
736/* rhs is A */
737/* set is the context */
738/* */
739/* See also decNumberCopyAbs for a quiet bitwise version of this. */
740/* C must have space for set->digits digits. */
741/* ------------------------------------------------------------------ */
742/* This has the same effect as decNumberPlus unless A is negative, */
743/* in which case it has the same effect as decNumberMinus. */
744/* ------------------------------------------------------------------ */
745U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
746 decContext *set) {
747 decNumber dzero; /* for 0 */
748 uInt status=0; /* accumulator */
749
750 #if DECCHECK
751 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
752 #endif
753
754 uprv_decNumberZero(&dzero); /* set 0 */
755 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
756 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
757 if (status!=0) decStatus(res, status, set);
758 #if DECCHECK
759 decCheckInexact(res, set);
760 #endif
761 return res;
762 } /* decNumberAbs */
763
764/* ------------------------------------------------------------------ */
765/* decNumberAdd -- add two Numbers */
766/* */
767/* This computes C = A + B */
768/* */
769/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
770/* lhs is A */
771/* rhs is B */
772/* set is the context */
773/* */
774/* C must have space for set->digits digits. */
775/* ------------------------------------------------------------------ */
776/* This just calls the routine shared with Subtract */
777U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
778 const decNumber *rhs, decContext *set) {
779 uInt status=0; /* accumulator */
780 decAddOp(res, lhs, rhs, set, 0, &status);
781 if (status!=0) decStatus(res, status, set);
782 #if DECCHECK
783 decCheckInexact(res, set);
784 #endif
785 return res;
786 } /* decNumberAdd */
787
788/* ------------------------------------------------------------------ */
789/* decNumberAnd -- AND two Numbers, digitwise */
790/* */
791/* This computes C = A & B */
792/* */
793/* res is C, the result. C may be A and/or B (e.g., X=X&X) */
794/* lhs is A */
795/* rhs is B */
796/* set is the context (used for result length and error report) */
797/* */
798/* C must have space for set->digits digits. */
799/* */
800/* Logical function restrictions apply (see above); a NaN is */
801/* returned with Invalid_operation if a restriction is violated. */
802/* ------------------------------------------------------------------ */
803U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
804 const decNumber *rhs, decContext *set) {
805 const Unit *ua, *ub; /* -> operands */
806 const Unit *msua, *msub; /* -> operand msus */
807 Unit *uc, *msuc; /* -> result and its msu */
808 Int msudigs; /* digits in res msu */
809 #if DECCHECK
810 if (decCheckOperands(res, lhs, rhs, set)) return res;
811 #endif
812
813 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
814 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
815 decStatus(res, DEC_Invalid_operation, set);
816 return res;
817 }
818
819 /* operands are valid */
820 ua=lhs->lsu; /* bottom-up */
821 ub=rhs->lsu; /* .. */
822 uc=res->lsu; /* .. */
823 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
824 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
825 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
826 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
827 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
828 Unit a, b; /* extract units */
829 if (ua>msua) a=0;
830 else a=*ua;
831 if (ub>msub) b=0;
832 else b=*ub;
833 *uc=0; /* can now write back */
834 if (a|b) { /* maybe 1 bits to examine */
835 Int i, j;
836 *uc=0; /* can now write back */
837 /* This loop could be unrolled and/or use BIN2BCD tables */
838 for (i=0; i<DECDPUN; i++) {
839 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
840 j=a%10;
841 a=a/10;
842 j|=b%10;
843 b=b/10;
844 if (j>1) {
845 decStatus(res, DEC_Invalid_operation, set);
846 return res;
847 }
848 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
849 } /* each digit */
850 } /* both OK */
851 } /* each unit */
852 /* [here uc-1 is the msu of the result] */
853 res->digits=decGetDigits(res->lsu, uc-res->lsu);
854 res->exponent=0; /* integer */
855 res->bits=0; /* sign=0 */
856 return res; /* [no status to set] */
857 } /* decNumberAnd */
858
859/* ------------------------------------------------------------------ */
860/* decNumberCompare -- compare two Numbers */
861/* */
862/* This computes C = A ? B */
863/* */
864/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
865/* lhs is A */
866/* rhs is B */
867/* set is the context */
868/* */
869/* C must have space for one digit (or NaN). */
870/* ------------------------------------------------------------------ */
871U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
872 const decNumber *rhs, decContext *set) {
873 uInt status=0; /* accumulator */
874 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
875 if (status!=0) decStatus(res, status, set);
876 return res;
877 } /* decNumberCompare */
878
879/* ------------------------------------------------------------------ */
880/* decNumberCompareSignal -- compare, signalling on all NaNs */
881/* */
882/* This computes C = A ? B */
883/* */
884/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
885/* lhs is A */
886/* rhs is B */
887/* set is the context */
888/* */
889/* C must have space for one digit (or NaN). */
890/* ------------------------------------------------------------------ */
891U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
892 const decNumber *rhs, decContext *set) {
893 uInt status=0; /* accumulator */
894 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
895 if (status!=0) decStatus(res, status, set);
896 return res;
897 } /* decNumberCompareSignal */
898
899/* ------------------------------------------------------------------ */
900/* decNumberCompareTotal -- compare two Numbers, using total ordering */
901/* */
902/* This computes C = A ? B, under total ordering */
903/* */
904/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
905/* lhs is A */
906/* rhs is B */
907/* set is the context */
908/* */
909/* C must have space for one digit; the result will always be one of */
910/* -1, 0, or 1. */
911/* ------------------------------------------------------------------ */
912U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
913 const decNumber *rhs, decContext *set) {
914 uInt status=0; /* accumulator */
915 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
916 if (status!=0) decStatus(res, status, set);
917 return res;
918 } /* decNumberCompareTotal */
919
920/* ------------------------------------------------------------------ */
921/* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
922/* */
923/* This computes C = |A| ? |B|, under total ordering */
924/* */
925/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
926/* lhs is A */
927/* rhs is B */
928/* set is the context */
929/* */
930/* C must have space for one digit; the result will always be one of */
931/* -1, 0, or 1. */
932/* ------------------------------------------------------------------ */
933U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
934 const decNumber *rhs, decContext *set) {
935 uInt status=0; /* accumulator */
936 uInt needbytes; /* for space calculations */
937 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
938 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
939 decNumber bufb[D2N(DECBUFFER+1)];
940 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
941 decNumber *a, *b; /* temporary pointers */
942
943 #if DECCHECK
944 if (decCheckOperands(res, lhs, rhs, set)) return res;
945 #endif
946
947 do { /* protect allocated storage */
948 /* if either is negative, take a copy and absolute */
949 if (decNumberIsNegative(lhs)) { /* lhs<0 */
950 a=bufa;
951 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
952 if (needbytes>sizeof(bufa)) { /* need malloc space */
953 allocbufa=(decNumber *)malloc(needbytes);
954 if (allocbufa==NULL) { /* hopeless -- abandon */
955 status|=DEC_Insufficient_storage;
956 break;}
957 a=allocbufa; /* use the allocated space */
958 }
959 uprv_decNumberCopy(a, lhs); /* copy content */
960 a->bits&=~DECNEG; /* .. and clear the sign */
961 lhs=a; /* use copy from here on */
962 }
963 if (decNumberIsNegative(rhs)) { /* rhs<0 */
964 b=bufb;
965 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
966 if (needbytes>sizeof(bufb)) { /* need malloc space */
967 allocbufb=(decNumber *)malloc(needbytes);
968 if (allocbufb==NULL) { /* hopeless -- abandon */
969 status|=DEC_Insufficient_storage;
970 break;}
971 b=allocbufb; /* use the allocated space */
972 }
973 uprv_decNumberCopy(b, rhs); /* copy content */
974 b->bits&=~DECNEG; /* .. and clear the sign */
975 rhs=b; /* use copy from here on */
976 }
977 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
978 } while(0); /* end protected */
979
980 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
981 if (allocbufb!=NULL) free(allocbufb); /* .. */
982 if (status!=0) decStatus(res, status, set);
983 return res;
984 } /* decNumberCompareTotalMag */
985
986/* ------------------------------------------------------------------ */
987/* decNumberDivide -- divide one number by another */
988/* */
989/* This computes C = A / B */
990/* */
991/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
992/* lhs is A */
993/* rhs is B */
994/* set is the context */
995/* */
996/* C must have space for set->digits digits. */
997/* ------------------------------------------------------------------ */
998U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
999 const decNumber *rhs, decContext *set) {
1000 uInt status=0; /* accumulator */
1001 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1002 if (status!=0) decStatus(res, status, set);
1003 #if DECCHECK
1004 decCheckInexact(res, set);
1005 #endif
1006 return res;
1007 } /* decNumberDivide */
1008
1009/* ------------------------------------------------------------------ */
1010/* decNumberDivideInteger -- divide and return integer quotient */
1011/* */
1012/* This computes C = A # B, where # is the integer divide operator */
1013/* */
1014/* res is C, the result. C may be A and/or B (e.g., X=X#X) */
1015/* lhs is A */
1016/* rhs is B */
1017/* set is the context */
1018/* */
1019/* C must have space for set->digits digits. */
1020/* ------------------------------------------------------------------ */
1021U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1022 const decNumber *rhs, decContext *set) {
1023 uInt status=0; /* accumulator */
1024 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1025 if (status!=0) decStatus(res, status, set);
1026 return res;
1027 } /* decNumberDivideInteger */
1028
1029/* ------------------------------------------------------------------ */
1030/* decNumberExp -- exponentiation */
1031/* */
1032/* This computes C = exp(A) */
1033/* */
1034/* res is C, the result. C may be A */
1035/* rhs is A */
1036/* set is the context; note that rounding mode has no effect */
1037/* */
1038/* C must have space for set->digits digits. */
1039/* */
1040/* Mathematical function restrictions apply (see above); a NaN is */
1041/* returned with Invalid_operation if a restriction is violated. */
1042/* */
1043/* Finite results will always be full precision and Inexact, except */
1044/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1045/* */
1046/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1047/* almost always be correctly rounded, but may be up to 1 ulp in */
1048/* error in rare cases. */
1049/* ------------------------------------------------------------------ */
1050/* This is a wrapper for decExpOp which can handle the slightly wider */
1051/* (double) range needed by Ln (which has to be able to calculate */
1052/* exp(-a) where a can be the tiniest number (Ntiny). */
1053/* ------------------------------------------------------------------ */
1054U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
1055 decContext *set) {
1056 uInt status=0; /* accumulator */
1057 #if DECSUBSET
1058 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1059 #endif
1060
1061 #if DECCHECK
1062 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1063 #endif
1064
1065 /* Check restrictions; these restrictions ensure that if h=8 (see */
1066 /* decExpOp) then the result will either overflow or underflow to 0. */
1067 /* Other math functions restrict the input range, too, for inverses. */
1068 /* If not violated then carry out the operation. */
1069 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1070 #if DECSUBSET
1071 if (!set->extended) {
1072 /* reduce operand and set lostDigits status, as needed */
1073 if (rhs->digits>set->digits) {
1074 allocrhs=decRoundOperand(rhs, set, &status);
1075 if (allocrhs==NULL) break;
1076 rhs=allocrhs;
1077 }
1078 }
1079 #endif
1080 decExpOp(res, rhs, set, &status);
1081 } while(0); /* end protected */
1082
1083 #if DECSUBSET
1084 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1085 #endif
1086 /* apply significant status */
1087 if (status!=0) decStatus(res, status, set);
1088 #if DECCHECK
1089 decCheckInexact(res, set);
1090 #endif
1091 return res;
1092 } /* decNumberExp */
1093
1094/* ------------------------------------------------------------------ */
1095/* decNumberFMA -- fused multiply add */
1096/* */
1097/* This computes D = (A * B) + C with only one rounding */
1098/* */
1099/* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1100/* lhs is A */
1101/* rhs is B */
1102/* fhs is C [far hand side] */
1103/* set is the context */
1104/* */
1105/* Mathematical function restrictions apply (see above); a NaN is */
1106/* returned with Invalid_operation if a restriction is violated. */
1107/* */
1108/* C must have space for set->digits digits. */
1109/* ------------------------------------------------------------------ */
1110U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
1111 const decNumber *rhs, const decNumber *fhs,
1112 decContext *set) {
1113 uInt status=0; /* accumulator */
1114 decContext dcmul; /* context for the multiplication */
1115 uInt needbytes; /* for space calculations */
1116 decNumber bufa[D2N(DECBUFFER*2+1)];
1117 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1118 decNumber *acc; /* accumulator pointer */
1119 decNumber dzero; /* work */
1120
1121 #if DECCHECK
1122 if (decCheckOperands(res, lhs, rhs, set)) return res;
1123 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1124 #endif
1125
1126 do { /* protect allocated storage */
1127 #if DECSUBSET
1128 if (!set->extended) { /* [undefined if subset] */
1129 status|=DEC_Invalid_operation;
1130 break;}
1131 #endif
1132 /* Check math restrictions [these ensure no overflow or underflow] */
1133 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1134 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1135 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1136 /* set up context for multiply */
1137 dcmul=*set;
1138 dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1139 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1140 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
1141 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
1142 /* set up decNumber space to receive the result of the multiply */
1143 acc=bufa; /* may fit */
1144 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1145 if (needbytes>sizeof(bufa)) { /* need malloc space */
1146 allocbufa=(decNumber *)malloc(needbytes);
1147 if (allocbufa==NULL) { /* hopeless -- abandon */
1148 status|=DEC_Insufficient_storage;
1149 break;}
1150 acc=allocbufa; /* use the allocated space */
1151 }
1152 /* multiply with extended range and necessary precision */
1153 /*printf("emin=%ld\n", dcmul.emin); */
1154 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1155 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1156 /* status; if either is seen than ignore fhs (in case it is */
1157 /* another sNaN) and set acc to NaN unless we had an sNaN */
1158 /* [decMultiplyOp leaves that to caller] */
1159 /* Note sNaN has to go through addOp to shorten payload if */
1160 /* necessary */
1161 if ((status&DEC_Invalid_operation)!=0) {
1162 if (!(status&DEC_sNaN)) { /* but be true invalid */
1163 uprv_decNumberZero(res); /* acc not yet set */
1164 res->bits=DECNAN;
1165 break;
1166 }
1167 uprv_decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
1168 fhs=&dzero; /* use that */
1169 }
1170 #if DECCHECK
1171 else { /* multiply was OK */
1172 if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1173 }
1174 #endif
1175 /* add the third operand and result -> res, and all is done */
1176 decAddOp(res, acc, fhs, set, 0, &status);
1177 } while(0); /* end protected */
1178
1179 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1180 if (status!=0) decStatus(res, status, set);
1181 #if DECCHECK
1182 decCheckInexact(res, set);
1183 #endif
1184 return res;
1185 } /* decNumberFMA */
1186
1187/* ------------------------------------------------------------------ */
1188/* decNumberInvert -- invert a Number, digitwise */
1189/* */
1190/* This computes C = ~A */
1191/* */
1192/* res is C, the result. C may be A (e.g., X=~X) */
1193/* rhs is A */
1194/* set is the context (used for result length and error report) */
1195/* */
1196/* C must have space for set->digits digits. */
1197/* */
1198/* Logical function restrictions apply (see above); a NaN is */
1199/* returned with Invalid_operation if a restriction is violated. */
1200/* ------------------------------------------------------------------ */
1201U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
1202 decContext *set) {
1203 const Unit *ua, *msua; /* -> operand and its msu */
1204 Unit *uc, *msuc; /* -> result and its msu */
1205 Int msudigs; /* digits in res msu */
1206 #if DECCHECK
1207 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1208 #endif
1209
1210 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1211 decStatus(res, DEC_Invalid_operation, set);
1212 return res;
1213 }
1214 /* operand is valid */
1215 ua=rhs->lsu; /* bottom-up */
1216 uc=res->lsu; /* .. */
1217 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
1218 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1219 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1220 for (; uc<=msuc; ua++, uc++) { /* Unit loop */
1221 Unit a; /* extract unit */
1222 Int i, j; /* work */
1223 if (ua>msua) a=0;
1224 else a=*ua;
1225 *uc=0; /* can now write back */
1226 /* always need to examine all bits in rhs */
1227 /* This loop could be unrolled and/or use BIN2BCD tables */
1228 for (i=0; i<DECDPUN; i++) {
1229 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
1230 j=a%10;
1231 a=a/10;
1232 if (j>1) {
1233 decStatus(res, DEC_Invalid_operation, set);
1234 return res;
1235 }
1236 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1237 } /* each digit */
1238 } /* each unit */
1239 /* [here uc-1 is the msu of the result] */
1240 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1241 res->exponent=0; /* integer */
1242 res->bits=0; /* sign=0 */
1243 return res; /* [no status to set] */
1244 } /* decNumberInvert */
1245
1246/* ------------------------------------------------------------------ */
1247/* decNumberLn -- natural logarithm */
1248/* */
1249/* This computes C = ln(A) */
1250/* */
1251/* res is C, the result. C may be A */
1252/* rhs is A */
1253/* set is the context; note that rounding mode has no effect */
1254/* */
1255/* C must have space for set->digits digits. */
1256/* */
1257/* Notable cases: */
1258/* A<0 -> Invalid */
1259/* A=0 -> -Infinity (Exact) */
1260/* A=+Infinity -> +Infinity (Exact) */
1261/* A=1 exactly -> 0 (Exact) */
1262/* */
1263/* Mathematical function restrictions apply (see above); a NaN is */
1264/* returned with Invalid_operation if a restriction is violated. */
1265/* */
1266/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1267/* almost always be correctly rounded, but may be up to 1 ulp in */
1268/* error in rare cases. */
1269/* ------------------------------------------------------------------ */
1270/* This is a wrapper for decLnOp which can handle the slightly wider */
1271/* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1272/* to calculate at p+e+2). */
1273/* ------------------------------------------------------------------ */
1274U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
1275 decContext *set) {
1276 uInt status=0; /* accumulator */
1277 #if DECSUBSET
1278 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1279 #endif
1280
1281 #if DECCHECK
1282 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1283 #endif
1284
1285 /* Check restrictions; this is a math function; if not violated */
1286 /* then carry out the operation. */
1287 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1288 #if DECSUBSET
1289 if (!set->extended) {
1290 /* reduce operand and set lostDigits status, as needed */
1291 if (rhs->digits>set->digits) {
1292 allocrhs=decRoundOperand(rhs, set, &status);
1293 if (allocrhs==NULL) break;
1294 rhs=allocrhs;
1295 }
1296 /* special check in subset for rhs=0 */
1297 if (ISZERO(rhs)) { /* +/- zeros -> error */
1298 status|=DEC_Invalid_operation;
1299 break;}
1300 } /* extended=0 */
1301 #endif
1302 decLnOp(res, rhs, set, &status);
1303 } while(0); /* end protected */
1304
1305 #if DECSUBSET
1306 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1307 #endif
1308 /* apply significant status */
1309 if (status!=0) decStatus(res, status, set);
1310 #if DECCHECK
1311 decCheckInexact(res, set);
1312 #endif
1313 return res;
1314 } /* decNumberLn */
1315
1316/* ------------------------------------------------------------------ */
1317/* decNumberLogB - get adjusted exponent, by 754 rules */
1318/* */
1319/* This computes C = adjustedexponent(A) */
1320/* */
1321/* res is C, the result. C may be A */
1322/* rhs is A */
1323/* set is the context, used only for digits and status */
1324/* */
1325/* C must have space for 10 digits (A might have 10**9 digits and */
1326/* an exponent of +999999999, or one digit and an exponent of */
1327/* -1999999999). */
1328/* */
1329/* This returns the adjusted exponent of A after (in theory) padding */
1330/* with zeros on the right to set->digits digits while keeping the */
1331/* same value. The exponent is not limited by emin/emax. */
1332/* */
1333/* Notable cases: */
1334/* A<0 -> Use |A| */
1335/* A=0 -> -Infinity (Division by zero) */
1336/* A=Infinite -> +Infinity (Exact) */
1337/* A=1 exactly -> 0 (Exact) */
1338/* NaNs are propagated as usual */
1339/* ------------------------------------------------------------------ */
1340U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
1341 decContext *set) {
1342 uInt status=0; /* accumulator */
1343
1344 #if DECCHECK
1345 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1346 #endif
1347
1348 /* NaNs as usual; Infinities return +Infinity; 0->oops */
1349 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1350 else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
1351 else if (decNumberIsZero(rhs)) {
1352 uprv_decNumberZero(res); /* prepare for Infinity */
1353 res->bits=DECNEG|DECINF; /* -Infinity */
1354 status|=DEC_Division_by_zero; /* as per 754 */
1355 }
1356 else { /* finite non-zero */
1357 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1358 uprv_decNumberFromInt32(res, ae); /* lay it out */
1359 }
1360
1361 if (status!=0) decStatus(res, status, set);
1362 return res;
1363 } /* decNumberLogB */
1364
1365/* ------------------------------------------------------------------ */
1366/* decNumberLog10 -- logarithm in base 10 */
1367/* */
1368/* This computes C = log10(A) */
1369/* */
1370/* res is C, the result. C may be A */
1371/* rhs is A */
1372/* set is the context; note that rounding mode has no effect */
1373/* */
1374/* C must have space for set->digits digits. */
1375/* */
1376/* Notable cases: */
1377/* A<0 -> Invalid */
1378/* A=0 -> -Infinity (Exact) */
1379/* A=+Infinity -> +Infinity (Exact) */
1380/* A=10**n (if n is an integer) -> n (Exact) */
1381/* */
1382/* Mathematical function restrictions apply (see above); a NaN is */
1383/* returned with Invalid_operation if a restriction is violated. */
1384/* */
1385/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1386/* almost always be correctly rounded, but may be up to 1 ulp in */
1387/* error in rare cases. */
1388/* ------------------------------------------------------------------ */
1389/* This calculates ln(A)/ln(10) using appropriate precision. For */
1390/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1391/* requested digits and t is the number of digits in the exponent */
1392/* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1393/* fastpath in decLnOp. The final division is done to the requested */
1394/* precision. */
1395/* ------------------------------------------------------------------ */
4388f060
A
1396#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
1397#pragma GCC diagnostic push
1398#pragma GCC diagnostic ignored "-Warray-bounds"
1399#endif
729e4ab9
A
1400U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1401 decContext *set) {
1402 uInt status=0, ignore=0; /* status accumulators */
1403 uInt needbytes; /* for space calculations */
1404 Int p; /* working precision */
1405 Int t; /* digits in exponent of A */
1406
1407 /* buffers for a and b working decimals */
1408 /* (adjustment calculator, same size) */
1409 decNumber bufa[D2N(DECBUFFER+2)];
1410 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1411 decNumber *a=bufa; /* temporary a */
1412 decNumber bufb[D2N(DECBUFFER+2)];
1413 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1414 decNumber *b=bufb; /* temporary b */
1415 decNumber bufw[D2N(10)]; /* working 2-10 digit number */
1416 decNumber *w=bufw; /* .. */
1417 #if DECSUBSET
1418 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1419 #endif
1420
1421 decContext aset; /* working context */
1422
1423 #if DECCHECK
1424 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1425 #endif
1426
1427 /* Check restrictions; this is a math function; if not violated */
1428 /* then carry out the operation. */
1429 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1430 #if DECSUBSET
1431 if (!set->extended) {
1432 /* reduce operand and set lostDigits status, as needed */
1433 if (rhs->digits>set->digits) {
1434 allocrhs=decRoundOperand(rhs, set, &status);
1435 if (allocrhs==NULL) break;
1436 rhs=allocrhs;
1437 }
1438 /* special check in subset for rhs=0 */
1439 if (ISZERO(rhs)) { /* +/- zeros -> error */
1440 status|=DEC_Invalid_operation;
1441 break;}
1442 } /* extended=0 */
1443 #endif
1444
1445 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1446
1447 /* handle exact powers of 10; only check if +ve finite */
1448 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1449 Int residue=0; /* (no residue) */
1450 uInt copystat=0; /* clean status */
1451
1452 /* round to a single digit... */
1453 aset.digits=1;
1454 decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1455 /* if exact and the digit is 1, rhs is a power of 10 */
1456 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1457 /* the exponent, conveniently, is the power of 10; making */
1458 /* this the result needs a little care as it might not fit, */
1459 /* so first convert it into the working number, and then move */
1460 /* to res */
1461 uprv_decNumberFromInt32(w, w->exponent);
1462 residue=0;
1463 decCopyFit(res, w, set, &residue, &status); /* copy & round */
1464 decFinish(res, set, &residue, &status); /* cleanup/set flags */
1465 break;
1466 } /* not a power of 10 */
1467 } /* not a candidate for exact */
1468
1469 /* simplify the information-content calculation to use 'total */
1470 /* number of digits in a, including exponent' as compared to the */
1471 /* requested digits, as increasing this will only rarely cost an */
1472 /* iteration in ln(a) anyway */
1473 t=6; /* it can never be >6 */
1474
1475 /* allocate space when needed... */
1476 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1477 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1478 if (needbytes>sizeof(bufa)) { /* need malloc space */
1479 allocbufa=(decNumber *)malloc(needbytes);
1480 if (allocbufa==NULL) { /* hopeless -- abandon */
1481 status|=DEC_Insufficient_storage;
1482 break;}
1483 a=allocbufa; /* use the allocated space */
1484 }
1485 aset.digits=p; /* as calculated */
1486 aset.emax=DEC_MAX_MATH; /* usual bounds */
1487 aset.emin=-DEC_MAX_MATH; /* .. */
1488 aset.clamp=0; /* and no concrete format */
1489 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
1490
1491 /* skip the division if the result so far is infinite, NaN, or */
1492 /* zero, or there was an error; note NaN from sNaN needs copy */
1493 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1494 if (a->bits&DECSPECIAL || ISZERO(a)) {
1495 uprv_decNumberCopy(res, a); /* [will fit] */
1496 break;}
1497
1498 /* for ln(10) an extra 3 digits of precision are needed */
1499 p=set->digits+3;
1500 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1501 if (needbytes>sizeof(bufb)) { /* need malloc space */
1502 allocbufb=(decNumber *)malloc(needbytes);
1503 if (allocbufb==NULL) { /* hopeless -- abandon */
1504 status|=DEC_Insufficient_storage;
1505 break;}
1506 b=allocbufb; /* use the allocated space */
1507 }
1508 uprv_decNumberZero(w); /* set up 10... */
1509 #if DECDPUN==1
1510 w->lsu[1]=1; w->lsu[0]=0; /* .. */
1511 #else
1512 w->lsu[0]=10; /* .. */
1513 #endif
1514 w->digits=2; /* .. */
1515
1516 aset.digits=p;
1517 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
1518
1519 aset.digits=set->digits; /* for final divide */
1520 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1521 } while(0); /* [for break] */
1522
1523 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1524 if (allocbufb!=NULL) free(allocbufb); /* .. */
1525 #if DECSUBSET
1526 if (allocrhs !=NULL) free(allocrhs); /* .. */
1527 #endif
1528 /* apply significant status */
1529 if (status!=0) decStatus(res, status, set);
1530 #if DECCHECK
1531 decCheckInexact(res, set);
1532 #endif
1533 return res;
1534 } /* decNumberLog10 */
4388f060
A
1535#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
1536#pragma GCC diagnostic pop
1537#endif
729e4ab9
A
1538
1539/* ------------------------------------------------------------------ */
1540/* decNumberMax -- compare two Numbers and return the maximum */
1541/* */
1542/* This computes C = A ? B, returning the maximum by 754 rules */
1543/* */
1544/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1545/* lhs is A */
1546/* rhs is B */
1547/* set is the context */
1548/* */
1549/* C must have space for set->digits digits. */
1550/* ------------------------------------------------------------------ */
1551U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1552 const decNumber *rhs, decContext *set) {
1553 uInt status=0; /* accumulator */
1554 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1555 if (status!=0) decStatus(res, status, set);
1556 #if DECCHECK
1557 decCheckInexact(res, set);
1558 #endif
1559 return res;
1560 } /* decNumberMax */
1561
1562/* ------------------------------------------------------------------ */
1563/* decNumberMaxMag -- compare and return the maximum by magnitude */
1564/* */
1565/* This computes C = A ? B, returning the maximum by 754 rules */
1566/* */
1567/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1568/* lhs is A */
1569/* rhs is B */
1570/* set is the context */
1571/* */
1572/* C must have space for set->digits digits. */
1573/* ------------------------------------------------------------------ */
1574U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1575 const decNumber *rhs, decContext *set) {
1576 uInt status=0; /* accumulator */
1577 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1578 if (status!=0) decStatus(res, status, set);
1579 #if DECCHECK
1580 decCheckInexact(res, set);
1581 #endif
1582 return res;
1583 } /* decNumberMaxMag */
1584
1585/* ------------------------------------------------------------------ */
1586/* decNumberMin -- compare two Numbers and return the minimum */
1587/* */
1588/* This computes C = A ? B, returning the minimum by 754 rules */
1589/* */
1590/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1591/* lhs is A */
1592/* rhs is B */
1593/* set is the context */
1594/* */
1595/* C must have space for set->digits digits. */
1596/* ------------------------------------------------------------------ */
1597U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1598 const decNumber *rhs, decContext *set) {
1599 uInt status=0; /* accumulator */
1600 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1601 if (status!=0) decStatus(res, status, set);
1602 #if DECCHECK
1603 decCheckInexact(res, set);
1604 #endif
1605 return res;
1606 } /* decNumberMin */
1607
1608/* ------------------------------------------------------------------ */
1609/* decNumberMinMag -- compare and return the minimum by magnitude */
1610/* */
1611/* This computes C = A ? B, returning the minimum by 754 rules */
1612/* */
1613/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1614/* lhs is A */
1615/* rhs is B */
1616/* set is the context */
1617/* */
1618/* C must have space for set->digits digits. */
1619/* ------------------------------------------------------------------ */
1620U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1621 const decNumber *rhs, decContext *set) {
1622 uInt status=0; /* accumulator */
1623 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1624 if (status!=0) decStatus(res, status, set);
1625 #if DECCHECK
1626 decCheckInexact(res, set);
1627 #endif
1628 return res;
1629 } /* decNumberMinMag */
1630
1631/* ------------------------------------------------------------------ */
1632/* decNumberMinus -- prefix minus operator */
1633/* */
1634/* This computes C = 0 - A */
1635/* */
1636/* res is C, the result. C may be A */
1637/* rhs is A */
1638/* set is the context */
1639/* */
1640/* See also decNumberCopyNegate for a quiet bitwise version of this. */
1641/* C must have space for set->digits digits. */
1642/* ------------------------------------------------------------------ */
1643/* Simply use AddOp for the subtract, which will do the necessary. */
1644/* ------------------------------------------------------------------ */
1645U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1646 decContext *set) {
1647 decNumber dzero;
1648 uInt status=0; /* accumulator */
1649
1650 #if DECCHECK
1651 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1652 #endif
1653
1654 uprv_decNumberZero(&dzero); /* make 0 */
1655 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1656 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1657 if (status!=0) decStatus(res, status, set);
1658 #if DECCHECK
1659 decCheckInexact(res, set);
1660 #endif
1661 return res;
1662 } /* decNumberMinus */
1663
1664/* ------------------------------------------------------------------ */
1665/* decNumberNextMinus -- next towards -Infinity */
1666/* */
1667/* This computes C = A - infinitesimal, rounded towards -Infinity */
1668/* */
1669/* res is C, the result. C may be A */
1670/* rhs is A */
1671/* set is the context */
1672/* */
1673/* This is a generalization of 754 NextDown. */
1674/* ------------------------------------------------------------------ */
1675U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1676 decContext *set) {
1677 decNumber dtiny; /* constant */
1678 decContext workset=*set; /* work */
1679 uInt status=0; /* accumulator */
1680 #if DECCHECK
1681 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1682 #endif
1683
1684 /* +Infinity is the special case */
1685 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1686 decSetMaxValue(res, set); /* is +ve */
1687 /* there is no status to set */
1688 return res;
1689 }
1690 uprv_decNumberZero(&dtiny); /* start with 0 */
1691 dtiny.lsu[0]=1; /* make number that is .. */
1692 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1693 workset.round=DEC_ROUND_FLOOR;
1694 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1695 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1696 if (status!=0) decStatus(res, status, set);
1697 return res;
1698 } /* decNumberNextMinus */
1699
1700/* ------------------------------------------------------------------ */
1701/* decNumberNextPlus -- next towards +Infinity */
1702/* */
1703/* This computes C = A + infinitesimal, rounded towards +Infinity */
1704/* */
1705/* res is C, the result. C may be A */
1706/* rhs is A */
1707/* set is the context */
1708/* */
1709/* This is a generalization of 754 NextUp. */
1710/* ------------------------------------------------------------------ */
1711U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1712 decContext *set) {
1713 decNumber dtiny; /* constant */
1714 decContext workset=*set; /* work */
1715 uInt status=0; /* accumulator */
1716 #if DECCHECK
1717 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1718 #endif
1719
1720 /* -Infinity is the special case */
1721 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1722 decSetMaxValue(res, set);
1723 res->bits=DECNEG; /* negative */
1724 /* there is no status to set */
1725 return res;
1726 }
1727 uprv_decNumberZero(&dtiny); /* start with 0 */
1728 dtiny.lsu[0]=1; /* make number that is .. */
1729 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1730 workset.round=DEC_ROUND_CEILING;
1731 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1732 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1733 if (status!=0) decStatus(res, status, set);
1734 return res;
1735 } /* decNumberNextPlus */
1736
1737/* ------------------------------------------------------------------ */
1738/* decNumberNextToward -- next towards rhs */
1739/* */
1740/* This computes C = A +/- infinitesimal, rounded towards */
1741/* +/-Infinity in the direction of B, as per 754-1985 nextafter */
1742/* modified during revision but dropped from 754-2008. */
1743/* */
1744/* res is C, the result. C may be A or B. */
1745/* lhs is A */
1746/* rhs is B */
1747/* set is the context */
1748/* */
1749/* This is a generalization of 754-1985 NextAfter. */
1750/* ------------------------------------------------------------------ */
1751U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1752 const decNumber *rhs, decContext *set) {
1753 decNumber dtiny; /* constant */
1754 decContext workset=*set; /* work */
1755 Int result; /* .. */
1756 uInt status=0; /* accumulator */
1757 #if DECCHECK
1758 if (decCheckOperands(res, lhs, rhs, set)) return res;
1759 #endif
1760
1761 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1762 decNaNs(res, lhs, rhs, set, &status);
1763 }
1764 else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1765 result=decCompare(lhs, rhs, 0); /* sign matters */
1766 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1767 else { /* valid compare */
1768 if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy */
1769 else { /* differ: need NextPlus or NextMinus */
1770 uByte sub; /* add or subtract */
1771 if (result<0) { /* lhs<rhs, do nextplus */
1772 /* -Infinity is the special case */
1773 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1774 decSetMaxValue(res, set);
1775 res->bits=DECNEG; /* negative */
1776 return res; /* there is no status to set */
1777 }
1778 workset.round=DEC_ROUND_CEILING;
1779 sub=0; /* add, please */
1780 } /* plus */
1781 else { /* lhs>rhs, do nextminus */
1782 /* +Infinity is the special case */
1783 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1784 decSetMaxValue(res, set);
1785 return res; /* there is no status to set */
1786 }
1787 workset.round=DEC_ROUND_FLOOR;
1788 sub=DECNEG; /* subtract, please */
1789 } /* minus */
1790 uprv_decNumberZero(&dtiny); /* start with 0 */
1791 dtiny.lsu[0]=1; /* make number that is .. */
1792 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1793 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1794 /* turn off exceptions if the result is a normal number */
1795 /* (including Nmin), otherwise let all status through */
1796 if (uprv_decNumberIsNormal(res, set)) status=0;
1797 } /* unequal */
1798 } /* compare OK */
1799 } /* numeric */
1800 if (status!=0) decStatus(res, status, set);
1801 return res;
1802 } /* decNumberNextToward */
1803
1804/* ------------------------------------------------------------------ */
1805/* decNumberOr -- OR two Numbers, digitwise */
1806/* */
1807/* This computes C = A | B */
1808/* */
1809/* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1810/* lhs is A */
1811/* rhs is B */
1812/* set is the context (used for result length and error report) */
1813/* */
1814/* C must have space for set->digits digits. */
1815/* */
1816/* Logical function restrictions apply (see above); a NaN is */
1817/* returned with Invalid_operation if a restriction is violated. */
1818/* ------------------------------------------------------------------ */
1819U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1820 const decNumber *rhs, decContext *set) {
1821 const Unit *ua, *ub; /* -> operands */
1822 const Unit *msua, *msub; /* -> operand msus */
1823 Unit *uc, *msuc; /* -> result and its msu */
1824 Int msudigs; /* digits in res msu */
1825 #if DECCHECK
1826 if (decCheckOperands(res, lhs, rhs, set)) return res;
1827 #endif
1828
1829 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1830 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1831 decStatus(res, DEC_Invalid_operation, set);
1832 return res;
1833 }
1834 /* operands are valid */
1835 ua=lhs->lsu; /* bottom-up */
1836 ub=rhs->lsu; /* .. */
1837 uc=res->lsu; /* .. */
1838 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
1839 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
1840 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1841 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1842 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
1843 Unit a, b; /* extract units */
1844 if (ua>msua) a=0;
1845 else a=*ua;
1846 if (ub>msub) b=0;
1847 else b=*ub;
1848 *uc=0; /* can now write back */
1849 if (a|b) { /* maybe 1 bits to examine */
1850 Int i, j;
1851 /* This loop could be unrolled and/or use BIN2BCD tables */
1852 for (i=0; i<DECDPUN; i++) {
1853 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
1854 j=a%10;
1855 a=a/10;
1856 j|=b%10;
1857 b=b/10;
1858 if (j>1) {
1859 decStatus(res, DEC_Invalid_operation, set);
1860 return res;
1861 }
1862 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1863 } /* each digit */
1864 } /* non-zero */
1865 } /* each unit */
1866 /* [here uc-1 is the msu of the result] */
1867 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1868 res->exponent=0; /* integer */
1869 res->bits=0; /* sign=0 */
1870 return res; /* [no status to set] */
1871 } /* decNumberOr */
1872
1873/* ------------------------------------------------------------------ */
1874/* decNumberPlus -- prefix plus operator */
1875/* */
1876/* This computes C = 0 + A */
1877/* */
1878/* res is C, the result. C may be A */
1879/* rhs is A */
1880/* set is the context */
1881/* */
1882/* See also decNumberCopy for a quiet bitwise version of this. */
1883/* C must have space for set->digits digits. */
1884/* ------------------------------------------------------------------ */
1885/* This simply uses AddOp; Add will take fast path after preparing A. */
1886/* Performance is a concern here, as this routine is often used to */
1887/* check operands and apply rounding and overflow/underflow testing. */
1888/* ------------------------------------------------------------------ */
1889U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1890 decContext *set) {
1891 decNumber dzero;
1892 uInt status=0; /* accumulator */
1893 #if DECCHECK
1894 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1895 #endif
1896
1897 uprv_decNumberZero(&dzero); /* make 0 */
1898 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1899 decAddOp(res, &dzero, rhs, set, 0, &status);
1900 if (status!=0) decStatus(res, status, set);
1901 #if DECCHECK
1902 decCheckInexact(res, set);
1903 #endif
1904 return res;
1905 } /* decNumberPlus */
1906
1907/* ------------------------------------------------------------------ */
1908/* decNumberMultiply -- multiply two Numbers */
1909/* */
1910/* This computes C = A x B */
1911/* */
1912/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1913/* lhs is A */
1914/* rhs is B */
1915/* set is the context */
1916/* */
1917/* C must have space for set->digits digits. */
1918/* ------------------------------------------------------------------ */
1919U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1920 const decNumber *rhs, decContext *set) {
1921 uInt status=0; /* accumulator */
1922 decMultiplyOp(res, lhs, rhs, set, &status);
1923 if (status!=0) decStatus(res, status, set);
1924 #if DECCHECK
1925 decCheckInexact(res, set);
1926 #endif
1927 return res;
1928 } /* decNumberMultiply */
1929
1930/* ------------------------------------------------------------------ */
1931/* decNumberPower -- raise a number to a power */
1932/* */
1933/* This computes C = A ** B */
1934/* */
1935/* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1936/* lhs is A */
1937/* rhs is B */
1938/* set is the context */
1939/* */
1940/* C must have space for set->digits digits. */
1941/* */
1942/* Mathematical function restrictions apply (see above); a NaN is */
1943/* returned with Invalid_operation if a restriction is violated. */
1944/* */
1945/* However, if 1999999997<=B<=999999999 and B is an integer then the */
1946/* restrictions on A and the context are relaxed to the usual bounds, */
1947/* for compatibility with the earlier (integer power only) version */
1948/* of this function. */
1949/* */
1950/* When B is an integer, the result may be exact, even if rounded. */
1951/* */
1952/* The final result is rounded according to the context; it will */
1953/* almost always be correctly rounded, but may be up to 1 ulp in */
1954/* error in rare cases. */
1955/* ------------------------------------------------------------------ */
1956U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1957 const decNumber *rhs, decContext *set) {
1958 #if DECSUBSET
1959 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
1960 decNumber *allocrhs=NULL; /* .., rhs */
1961 #endif
1962 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */
1963 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */
1964 Int reqdigits=set->digits; /* requested DIGITS */
1965 Int n; /* rhs in binary */
1966 Flag rhsint=0; /* 1 if rhs is an integer */
1967 Flag useint=0; /* 1 if can use integer calculation */
1968 Flag isoddint=0; /* 1 if rhs is an integer and odd */
1969 Int i; /* work */
1970 #if DECSUBSET
1971 Int dropped; /* .. */
1972 #endif
1973 uInt needbytes; /* buffer size needed */
1974 Flag seenbit; /* seen a bit while powering */
1975 Int residue=0; /* rounding residue */
1976 uInt status=0; /* accumulators */
1977 uByte bits=0; /* result sign if errors */
1978 decContext aset; /* working context */
1979 decNumber dnOne; /* work value 1... */
1980 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1981 decNumber dacbuff[D2N(DECBUFFER+9)];
1982 decNumber *dac=dacbuff; /* -> result accumulator */
1983 /* same again for possible 1/lhs calculation */
1984 decNumber invbuff[D2N(DECBUFFER+9)];
1985
1986 #if DECCHECK
1987 if (decCheckOperands(res, lhs, rhs, set)) return res;
1988 #endif
1989
1990 do { /* protect allocated storage */
1991 #if DECSUBSET
1992 if (!set->extended) { /* reduce operands and set status, as needed */
1993 if (lhs->digits>reqdigits) {
1994 alloclhs=decRoundOperand(lhs, set, &status);
1995 if (alloclhs==NULL) break;
1996 lhs=alloclhs;
1997 }
1998 if (rhs->digits>reqdigits) {
1999 allocrhs=decRoundOperand(rhs, set, &status);
2000 if (allocrhs==NULL) break;
2001 rhs=allocrhs;
2002 }
2003 }
2004 #endif
2005 /* [following code does not require input rounding] */
2006
2007 /* handle NaNs and rhs Infinity (lhs infinity is harder) */
2008 if (SPECIALARGS) {
2009 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
2010 decNaNs(res, lhs, rhs, set, &status);
2011 break;}
2012 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
2013 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
2014 if (decNumberIsNegative(lhs) /* lhs<0 */
2015 && !decNumberIsZero(lhs)) /* .. */
2016 status|=DEC_Invalid_operation;
2017 else { /* lhs >=0 */
2018 uprv_decNumberZero(&dnOne); /* set up 1 */
2019 dnOne.lsu[0]=1;
2020 uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2021 uprv_decNumberZero(res); /* prepare for 0/1/Infinity */
2022 if (decNumberIsNegative(dac)) { /* lhs<1 */
2023 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2024 }
2025 else if (dac->lsu[0]==0) { /* lhs=1 */
2026 /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2027 Int shift=set->digits-1;
2028 *res->lsu=1; /* was 0, make int 1 */
2029 res->digits=decShiftToMost(res->lsu, 1, shift);
2030 res->exponent=-shift; /* make 1.0000... */
2031 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2032 }
2033 else { /* lhs>1 */
2034 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2035 }
2036 } /* lhs>=0 */
2037 break;}
2038 /* [lhs infinity drops through] */
2039 } /* specials */
2040
2041 /* Original rhs may be an integer that fits and is in range */
2042 n=decGetInt(rhs);
2043 if (n!=BADINT) { /* it is an integer */
2044 rhsint=1; /* record the fact for 1**n */
2045 isoddint=(Flag)n&1; /* [works even if big] */
2046 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
2047 useint=1; /* looks good */
2048 }
2049
2050 if (decNumberIsNegative(lhs) /* -x .. */
2051 && isoddint) bits=DECNEG; /* .. to an odd power */
2052
2053 /* handle LHS infinity */
2054 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
2055 uByte rbits=rhs->bits; /* save */
2056 uprv_decNumberZero(res); /* prepare */
2057 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
2058 else {
2059 /* -Inf**nonint -> error */
2060 if (!rhsint && decNumberIsNegative(lhs)) {
2061 status|=DEC_Invalid_operation; /* -Inf**nonint is error */
2062 break;}
2063 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2064 /* [otherwise will be 0 or -0] */
2065 res->bits=bits;
2066 }
2067 break;}
2068
2069 /* similarly handle LHS zero */
2070 if (decNumberIsZero(lhs)) {
2071 if (n==0) { /* 0**0 => Error */
2072 #if DECSUBSET
2073 if (!set->extended) { /* [unless subset] */
2074 uprv_decNumberZero(res);
2075 *res->lsu=1; /* return 1 */
2076 break;}
2077 #endif
2078 status|=DEC_Invalid_operation;
2079 }
2080 else { /* 0**x */
2081 uByte rbits=rhs->bits; /* save */
2082 if (rbits & DECNEG) { /* was a 0**(-n) */
2083 #if DECSUBSET
2084 if (!set->extended) { /* [bad if subset] */
2085 status|=DEC_Invalid_operation;
2086 break;}
2087 #endif
2088 bits|=DECINF;
2089 }
2090 uprv_decNumberZero(res); /* prepare */
2091 /* [otherwise will be 0 or -0] */
2092 res->bits=bits;
2093 }
2094 break;}
2095
2096 /* here both lhs and rhs are finite; rhs==0 is handled in the */
2097 /* integer path. Next handle the non-integer cases */
2098 if (!useint) { /* non-integral rhs */
2099 /* any -ve lhs is bad, as is either operand or context out of */
2100 /* bounds */
2101 if (decNumberIsNegative(lhs)) {
2102 status|=DEC_Invalid_operation;
2103 break;}
2104 if (decCheckMath(lhs, set, &status)
2105 || decCheckMath(rhs, set, &status)) break; /* variable status */
2106
2107 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2108 aset.emax=DEC_MAX_MATH; /* usual bounds */
2109 aset.emin=-DEC_MAX_MATH; /* .. */
2110 aset.clamp=0; /* and no concrete format */
2111
2112 /* calculate the result using exp(ln(lhs)*rhs), which can */
2113 /* all be done into the accumulator, dac. The precision needed */
2114 /* is enough to contain the full information in the lhs (which */
2115 /* is the total digits, including exponent), or the requested */
2116 /* precision, if larger, + 4; 6 is used for the exponent */
2117 /* maximum length, and this is also used when it is shorter */
2118 /* than the requested digits as it greatly reduces the >0.5 ulp */
2119 /* cases at little cost (because Ln doubles digits each */
2120 /* iteration so a few extra digits rarely causes an extra */
2121 /* iteration) */
2122 aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2123 } /* non-integer rhs */
2124
2125 else { /* rhs is in-range integer */
2126 if (n==0) { /* x**0 = 1 */
2127 /* (0**0 was handled above) */
2128 uprv_decNumberZero(res); /* result=1 */
2129 *res->lsu=1; /* .. */
2130 break;}
2131 /* rhs is a non-zero integer */
2132 if (n<0) n=-n; /* use abs(n) */
2133
2134 aset=*set; /* clone the context */
2135 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
2136 /* calculate the working DIGITS */
2137 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2138 #if DECSUBSET
2139 if (!set->extended) aset.digits--; /* use classic precision */
2140 #endif
2141 /* it's an error if this is more than can be handled */
2142 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2143 } /* integer path */
2144
2145 /* aset.digits is the count of digits for the accumulator needed */
2146 /* if accumulator is too long for local storage, then allocate */
2147 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2148 /* [needbytes also used below if 1/lhs needed] */
2149 if (needbytes>sizeof(dacbuff)) {
2150 allocdac=(decNumber *)malloc(needbytes);
2151 if (allocdac==NULL) { /* hopeless -- abandon */
2152 status|=DEC_Insufficient_storage;
2153 break;}
2154 dac=allocdac; /* use the allocated space */
2155 }
2156 /* here, aset is set up and accumulator is ready for use */
2157
2158 if (!useint) { /* non-integral rhs */
2159 /* x ** y; special-case x=1 here as it will otherwise always */
2160 /* reduce to integer 1; decLnOp has a fastpath which detects */
2161 /* the case of x=1 */
2162 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
2163 /* [no error possible, as lhs 0 already handled] */
2164 if (ISZERO(dac)) { /* x==1, 1.0, etc. */
2165 /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2166 *dac->lsu=1; /* was 0, make int 1 */
2167 if (!rhsint) { /* add padding */
2168 Int shift=set->digits-1;
2169 dac->digits=decShiftToMost(dac->lsu, 1, shift);
2170 dac->exponent=-shift; /* make 1.0000... */
2171 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2172 }
2173 }
2174 else {
2175 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
2176 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
2177 }
2178 /* and drop through for final rounding */
2179 } /* non-integer rhs */
2180
2181 else { /* carry on with integer */
2182 uprv_decNumberZero(dac); /* acc=1 */
2183 *dac->lsu=1; /* .. */
2184
2185 /* if a negative power the constant 1 is needed, and if not subset */
2186 /* invert the lhs now rather than inverting the result later */
2187 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2188 decNumber *inv=invbuff; /* asssume use fixed buffer */
2189 uprv_decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
2190 #if DECSUBSET
2191 if (set->extended) { /* need to calculate 1/lhs */
2192 #endif
2193 /* divide lhs into 1, putting result in dac [dac=1/dac] */
2194 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2195 /* now locate or allocate space for the inverted lhs */
2196 if (needbytes>sizeof(invbuff)) {
2197 allocinv=(decNumber *)malloc(needbytes);
2198 if (allocinv==NULL) { /* hopeless -- abandon */
2199 status|=DEC_Insufficient_storage;
2200 break;}
2201 inv=allocinv; /* use the allocated space */
2202 }
2203 /* [inv now points to big-enough buffer or allocated storage] */
2204 uprv_decNumberCopy(inv, dac); /* copy the 1/lhs */
2205 uprv_decNumberCopy(dac, &dnOne); /* restore acc=1 */
2206 lhs=inv; /* .. and go forward with new lhs */
2207 #if DECSUBSET
2208 }
2209 #endif
2210 }
2211
2212 /* Raise-to-the-power loop... */
2213 seenbit=0; /* set once a 1-bit is encountered */
2214 for (i=1;;i++){ /* for each bit [top bit ignored] */
2215 /* abandon if had overflow or terminal underflow */
2216 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2217 if (status&DEC_Overflow || ISZERO(dac)) break;
2218 }
2219 /* [the following two lines revealed an optimizer bug in a C++ */
2220 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2221 n=n<<1; /* move next bit to testable position */
2222 if (n<0) { /* top bit is set */
2223 seenbit=1; /* OK, significant bit seen */
2224 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2225 }
2226 if (i==31) break; /* that was the last bit */
2227 if (!seenbit) continue; /* no need to square 1 */
2228 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2229 } /*i*/ /* 32 bits */
2230
2231 /* complete internal overflow or underflow processing */
2232 if (status & (DEC_Overflow|DEC_Underflow)) {
2233 #if DECSUBSET
2234 /* If subset, and power was negative, reverse the kind of -erflow */
2235 /* [1/x not yet done] */
2236 if (!set->extended && decNumberIsNegative(rhs)) {
2237 if (status & DEC_Overflow)
2238 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2239 else { /* trickier -- Underflow may or may not be set */
2240 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2241 status|=DEC_Overflow;
2242 }
2243 }
2244 #endif
2245 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2246 /* round subnormals [to set.digits rather than aset.digits] */
2247 /* or set overflow result similarly as required */
2248 decFinalize(dac, set, &residue, &status);
2249 uprv_decNumberCopy(res, dac); /* copy to result (is now OK length) */
2250 break;
2251 }
2252
2253 #if DECSUBSET
2254 if (!set->extended && /* subset math */
2255 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2256 /* so divide result into 1 [dac=1/dac] */
2257 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2258 }
2259 #endif
2260 } /* rhs integer path */
2261
2262 /* reduce result to the requested length and copy to result */
2263 decCopyFit(res, dac, set, &residue, &status);
2264 decFinish(res, set, &residue, &status); /* final cleanup */
2265 #if DECSUBSET
2266 if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros */
2267 #endif
2268 } while(0); /* end protected */
2269
2270 if (allocdac!=NULL) free(allocdac); /* drop any storage used */
2271 if (allocinv!=NULL) free(allocinv); /* .. */
2272 #if DECSUBSET
2273 if (alloclhs!=NULL) free(alloclhs); /* .. */
2274 if (allocrhs!=NULL) free(allocrhs); /* .. */
2275 #endif
2276 if (status!=0) decStatus(res, status, set);
2277 #if DECCHECK
2278 decCheckInexact(res, set);
2279 #endif
2280 return res;
2281 } /* decNumberPower */
2282
2283/* ------------------------------------------------------------------ */
2284/* decNumberQuantize -- force exponent to requested value */
2285/* */
2286/* This computes C = op(A, B), where op adjusts the coefficient */
2287/* of C (by rounding or shifting) such that the exponent (-scale) */
2288/* of C has exponent of B. The numerical value of C will equal A, */
2289/* except for the effects of any rounding that occurred. */
2290/* */
2291/* res is C, the result. C may be A or B */
2292/* lhs is A, the number to adjust */
2293/* rhs is B, the number with exponent to match */
2294/* set is the context */
2295/* */
2296/* C must have space for set->digits digits. */
2297/* */
2298/* Unless there is an error or the result is infinite, the exponent */
2299/* after the operation is guaranteed to be equal to that of B. */
2300/* ------------------------------------------------------------------ */
2301U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2302 const decNumber *rhs, decContext *set) {
2303 uInt status=0; /* accumulator */
2304 decQuantizeOp(res, lhs, rhs, set, 1, &status);
2305 if (status!=0) decStatus(res, status, set);
2306 return res;
2307 } /* decNumberQuantize */
2308
2309/* ------------------------------------------------------------------ */
2310/* decNumberReduce -- remove trailing zeros */
2311/* */
2312/* This computes C = 0 + A, and normalizes the result */
2313/* */
2314/* res is C, the result. C may be A */
2315/* rhs is A */
2316/* set is the context */
2317/* */
2318/* C must have space for set->digits digits. */
2319/* ------------------------------------------------------------------ */
2320/* Previously known as Normalize */
2321U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2322 decContext *set) {
2323 return uprv_decNumberReduce(res, rhs, set);
2324 } /* decNumberNormalize */
2325
2326U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2327 decContext *set) {
2328 #if DECSUBSET
2329 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2330 #endif
2331 uInt status=0; /* as usual */
2332 Int residue=0; /* as usual */
2333 Int dropped; /* work */
2334
2335 #if DECCHECK
2336 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2337 #endif
2338
2339 do { /* protect allocated storage */
2340 #if DECSUBSET
2341 if (!set->extended) {
2342 /* reduce operand and set lostDigits status, as needed */
2343 if (rhs->digits>set->digits) {
2344 allocrhs=decRoundOperand(rhs, set, &status);
2345 if (allocrhs==NULL) break;
2346 rhs=allocrhs;
2347 }
2348 }
2349 #endif
2350 /* [following code does not require input rounding] */
2351
2352 /* Infinities copy through; NaNs need usual treatment */
2353 if (decNumberIsNaN(rhs)) {
2354 decNaNs(res, rhs, NULL, set, &status);
2355 break;
2356 }
2357
2358 /* reduce result to the requested length and copy to result */
2359 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2360 decFinish(res, set, &residue, &status); /* cleanup/set flags */
2361 decTrim(res, set, 1, 0, &dropped); /* normalize in place */
2362 /* [may clamp] */
2363 } while(0); /* end protected */
2364
2365 #if DECSUBSET
2366 if (allocrhs !=NULL) free(allocrhs); /* .. */
2367 #endif
2368 if (status!=0) decStatus(res, status, set);/* then report status */
2369 return res;
2370 } /* decNumberReduce */
2371
2372/* ------------------------------------------------------------------ */
2373/* decNumberRescale -- force exponent to requested value */
2374/* */
2375/* This computes C = op(A, B), where op adjusts the coefficient */
2376/* of C (by rounding or shifting) such that the exponent (-scale) */
2377/* of C has the value B. The numerical value of C will equal A, */
2378/* except for the effects of any rounding that occurred. */
2379/* */
2380/* res is C, the result. C may be A or B */
2381/* lhs is A, the number to adjust */
2382/* rhs is B, the requested exponent */
2383/* set is the context */
2384/* */
2385/* C must have space for set->digits digits. */
2386/* */
2387/* Unless there is an error or the result is infinite, the exponent */
2388/* after the operation is guaranteed to be equal to B. */
2389/* ------------------------------------------------------------------ */
2390U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2391 const decNumber *rhs, decContext *set) {
2392 uInt status=0; /* accumulator */
2393 decQuantizeOp(res, lhs, rhs, set, 0, &status);
2394 if (status!=0) decStatus(res, status, set);
2395 return res;
2396 } /* decNumberRescale */
2397
2398/* ------------------------------------------------------------------ */
2399/* decNumberRemainder -- divide and return remainder */
2400/* */
2401/* This computes C = A % B */
2402/* */
2403/* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2404/* lhs is A */
2405/* rhs is B */
2406/* set is the context */
2407/* */
2408/* C must have space for set->digits digits. */
2409/* ------------------------------------------------------------------ */
2410U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2411 const decNumber *rhs, decContext *set) {
2412 uInt status=0; /* accumulator */
2413 decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2414 if (status!=0) decStatus(res, status, set);
2415 #if DECCHECK
2416 decCheckInexact(res, set);
2417 #endif
2418 return res;
2419 } /* decNumberRemainder */
2420
2421/* ------------------------------------------------------------------ */
2422/* decNumberRemainderNear -- divide and return remainder from nearest */
2423/* */
2424/* This computes C = A % B, where % is the IEEE remainder operator */
2425/* */
2426/* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2427/* lhs is A */
2428/* rhs is B */
2429/* set is the context */
2430/* */
2431/* C must have space for set->digits digits. */
2432/* ------------------------------------------------------------------ */
2433U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2434 const decNumber *rhs, decContext *set) {
2435 uInt status=0; /* accumulator */
2436 decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2437 if (status!=0) decStatus(res, status, set);
2438 #if DECCHECK
2439 decCheckInexact(res, set);
2440 #endif
2441 return res;
2442 } /* decNumberRemainderNear */
2443
2444/* ------------------------------------------------------------------ */
2445/* decNumberRotate -- rotate the coefficient of a Number left/right */
2446/* */
2447/* This computes C = A rot B (in base ten and rotating set->digits */
2448/* digits). */
2449/* */
2450/* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
2451/* lhs is A */
2452/* rhs is B, the number of digits to rotate (-ve to right) */
2453/* set is the context */
2454/* */
2455/* The digits of the coefficient of A are rotated to the left (if B */
2456/* is positive) or to the right (if B is negative) without adjusting */
2457/* the exponent or the sign of A. If lhs->digits is less than */
2458/* set->digits the coefficient is padded with zeros on the left */
2459/* before the rotate. Any leading zeros in the result are removed */
2460/* as usual. */
2461/* */
2462/* B must be an integer (q=0) and in the range -set->digits through */
2463/* +set->digits. */
2464/* C must have space for set->digits digits. */
2465/* NaNs are propagated as usual. Infinities are unaffected (but */
2466/* B must be valid). No status is set unless B is invalid or an */
2467/* operand is an sNaN. */
2468/* ------------------------------------------------------------------ */
2469U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2470 const decNumber *rhs, decContext *set) {
2471 uInt status=0; /* accumulator */
2472 Int rotate; /* rhs as an Int */
2473
2474 #if DECCHECK
2475 if (decCheckOperands(res, lhs, rhs, set)) return res;
2476 #endif
2477
2478 /* NaNs propagate as normal */
2479 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2480 decNaNs(res, lhs, rhs, set, &status);
2481 /* rhs must be an integer */
2482 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2483 status=DEC_Invalid_operation;
2484 else { /* both numeric, rhs is an integer */
2485 rotate=decGetInt(rhs); /* [cannot fail] */
2486 if (rotate==BADINT /* something bad .. */
2487 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
2488 || abs(rotate)>set->digits) /* .. or out of range */
2489 status=DEC_Invalid_operation;
2490 else { /* rhs is OK */
2491 uprv_decNumberCopy(res, lhs);
2492 /* convert -ve rotate to equivalent positive rotation */
2493 if (rotate<0) rotate=set->digits+rotate;
2494 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
2495 && !decNumberIsInfinite(res)) { /* lhs was infinite */
2496 /* left-rotate to do; 0 < rotate < set->digits */
2497 uInt units, shift; /* work */
2498 uInt msudigits; /* digits in result msu */
2499 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
2500 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2501 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
2502 res->digits=set->digits; /* now full-length */
2503 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
2504
2505 /* rotation here is done in-place, in three steps */
2506 /* 1. shift all to least up to one unit to unit-align final */
2507 /* lsd [any digits shifted out are rotated to the left, */
2508 /* abutted to the original msd (which may require split)] */
2509 /* */
2510 /* [if there are no whole units left to rotate, the */
2511 /* rotation is now complete] */
2512 /* */
2513 /* 2. shift to least, from below the split point only, so that */
2514 /* the final msd is in the right place in its Unit [any */
2515 /* digits shifted out will fit exactly in the current msu, */
2516 /* left aligned, no split required] */
2517 /* */
2518 /* 3. rotate all the units by reversing left part, right */
2519 /* part, and then whole */
2520 /* */
2521 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2522 /* */
2523 /* start: 00a bcd efg hij klm npq */
2524 /* */
2525 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
2526 /* 1b 00p qab cde fgh|ijk lmn */
2527 /* */
2528 /* 2a 00p qab cde fgh|00i jkl [mn saved] */
2529 /* 2b mnp qab cde fgh|00i jkl */
2530 /* */
2531 /* 3a fgh cde qab mnp|00i jkl */
2532 /* 3b fgh cde qab mnp|jkl 00i */
2533 /* 3c 00i jkl mnp qab cde fgh */
2534
2535 /* Step 1: amount to shift is the partial right-rotate count */
2536 rotate=set->digits-rotate; /* make it right-rotate */
2537 units=rotate/DECDPUN; /* whole units to rotate */
2538 shift=rotate%DECDPUN; /* left-over digits count */
2539 if (shift>0) { /* not an exact number of units */
2540 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2541 decShiftToLeast(res->lsu, D2U(res->digits), shift);
2542 if (shift>msudigits) { /* msumax-1 needs >0 digits */
2543 uInt rem=save%powers[shift-msudigits];/* split save */
2544 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2545 *(msumax-1)=*(msumax-1)
2546 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2547 }
2548 else { /* all fits in msumax */
2549 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2550 }
2551 } /* digits shift needed */
2552
2553 /* If whole units to rotate... */
2554 if (units>0) { /* some to do */
2555 /* Step 2: the units to touch are the whole ones in rotate, */
2556 /* if any, and the shift is DECDPUN-msudigits (which may be */
2557 /* 0, again) */
2558 shift=DECDPUN-msudigits;
2559 if (shift>0) { /* not an exact number of units */
2560 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2561 decShiftToLeast(res->lsu, units, shift);
2562 *msumax=*msumax+(Unit)(save*powers[msudigits]);
2563 } /* partial shift needed */
2564
2565 /* Step 3: rotate the units array using triple reverse */
2566 /* (reversing is easy and fast) */
2567 decReverse(res->lsu+units, msumax); /* left part */
2568 decReverse(res->lsu, res->lsu+units-1); /* right part */
2569 decReverse(res->lsu, msumax); /* whole */
2570 } /* whole units to rotate */
2571 /* the rotation may have left an undetermined number of zeros */
2572 /* on the left, so true length needs to be calculated */
2573 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2574 } /* rotate needed */
2575 } /* rhs OK */
2576 } /* numerics */
2577 if (status!=0) decStatus(res, status, set);
2578 return res;
2579 } /* decNumberRotate */
2580
2581/* ------------------------------------------------------------------ */
2582/* decNumberSameQuantum -- test for equal exponents */
2583/* */
2584/* res is the result number, which will contain either 0 or 1 */
2585/* lhs is a number to test */
2586/* rhs is the second (usually a pattern) */
2587/* */
2588/* No errors are possible and no context is needed. */
2589/* ------------------------------------------------------------------ */
2590U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2591 const decNumber *rhs) {
2592 Unit ret=0; /* return value */
2593
2594 #if DECCHECK
2595 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2596 #endif
2597
2598 if (SPECIALARGS) {
2599 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2600 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2601 /* [anything else with a special gives 0] */
2602 }
2603 else if (lhs->exponent==rhs->exponent) ret=1;
2604
2605 uprv_decNumberZero(res); /* OK to overwrite an operand now */
2606 *res->lsu=ret;
2607 return res;
2608 } /* decNumberSameQuantum */
2609
2610/* ------------------------------------------------------------------ */
2611/* decNumberScaleB -- multiply by a power of 10 */
2612/* */
2613/* This computes C = A x 10**B where B is an integer (q=0) with */
2614/* maximum magnitude 2*(emax+digits) */
2615/* */
2616/* res is C, the result. C may be A or B */
2617/* lhs is A, the number to adjust */
2618/* rhs is B, the requested power of ten to use */
2619/* set is the context */
2620/* */
2621/* C must have space for set->digits digits. */
2622/* */
2623/* The result may underflow or overflow. */
2624/* ------------------------------------------------------------------ */
2625U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2626 const decNumber *rhs, decContext *set) {
2627 Int reqexp; /* requested exponent change [B] */
2628 uInt status=0; /* accumulator */
2629 Int residue; /* work */
2630
2631 #if DECCHECK
2632 if (decCheckOperands(res, lhs, rhs, set)) return res;
2633 #endif
2634
2635 /* Handle special values except lhs infinite */
2636 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2637 decNaNs(res, lhs, rhs, set, &status);
2638 /* rhs must be an integer */
2639 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2640 status=DEC_Invalid_operation;
2641 else {
2642 /* lhs is a number; rhs is a finite with q==0 */
2643 reqexp=decGetInt(rhs); /* [cannot fail] */
2644 if (reqexp==BADINT /* something bad .. */
2645 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
2646 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2647 status=DEC_Invalid_operation;
2648 else { /* rhs is OK */
2649 uprv_decNumberCopy(res, lhs); /* all done if infinite lhs */
2650 if (!decNumberIsInfinite(res)) { /* prepare to scale */
2651 res->exponent+=reqexp; /* adjust the exponent */
2652 residue=0;
2653 decFinalize(res, set, &residue, &status); /* .. and check */
2654 } /* finite LHS */
2655 } /* rhs OK */
2656 } /* rhs finite */
2657 if (status!=0) decStatus(res, status, set);
2658 return res;
2659 } /* decNumberScaleB */
2660
2661/* ------------------------------------------------------------------ */
2662/* decNumberShift -- shift the coefficient of a Number left or right */
2663/* */
2664/* This computes C = A << B or C = A >> -B (in base ten). */
2665/* */
2666/* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
2667/* lhs is A */
2668/* rhs is B, the number of digits to shift (-ve to right) */
2669/* set is the context */
2670/* */
2671/* The digits of the coefficient of A are shifted to the left (if B */
2672/* is positive) or to the right (if B is negative) without adjusting */
2673/* the exponent or the sign of A. */
2674/* */
2675/* B must be an integer (q=0) and in the range -set->digits through */
2676/* +set->digits. */
2677/* C must have space for set->digits digits. */
2678/* NaNs are propagated as usual. Infinities are unaffected (but */
2679/* B must be valid). No status is set unless B is invalid or an */
2680/* operand is an sNaN. */
2681/* ------------------------------------------------------------------ */
2682U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2683 const decNumber *rhs, decContext *set) {
2684 uInt status=0; /* accumulator */
2685 Int shift; /* rhs as an Int */
2686
2687 #if DECCHECK
2688 if (decCheckOperands(res, lhs, rhs, set)) return res;
2689 #endif
2690
2691 /* NaNs propagate as normal */
2692 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2693 decNaNs(res, lhs, rhs, set, &status);
2694 /* rhs must be an integer */
2695 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2696 status=DEC_Invalid_operation;
2697 else { /* both numeric, rhs is an integer */
2698 shift=decGetInt(rhs); /* [cannot fail] */
2699 if (shift==BADINT /* something bad .. */
2700 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
2701 || abs(shift)>set->digits) /* .. or out of range */
2702 status=DEC_Invalid_operation;
2703 else { /* rhs is OK */
2704 uprv_decNumberCopy(res, lhs);
2705 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2706 if (shift>0) { /* to left */
2707 if (shift==set->digits) { /* removing all */
2708 *res->lsu=0; /* so place 0 */
2709 res->digits=1; /* .. */
2710 }
2711 else { /* */
2712 /* first remove leading digits if necessary */
2713 if (res->digits+shift>set->digits) {
2714 decDecap(res, res->digits+shift-set->digits);
2715 /* that updated res->digits; may have gone to 1 (for a */
2716 /* single digit or for zero */
2717 }
2718 if (res->digits>1 || *res->lsu) /* if non-zero.. */
2719 res->digits=decShiftToMost(res->lsu, res->digits, shift);
2720 } /* partial left */
2721 } /* left */
2722 else { /* to right */
2723 if (-shift>=res->digits) { /* discarding all */
2724 *res->lsu=0; /* so place 0 */
2725 res->digits=1; /* .. */
2726 }
2727 else {
2728 decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2729 res->digits-=(-shift);
2730 }
2731 } /* to right */
2732 } /* non-0 non-Inf shift */
2733 } /* rhs OK */
2734 } /* numerics */
2735 if (status!=0) decStatus(res, status, set);
2736 return res;
2737 } /* decNumberShift */
2738
2739/* ------------------------------------------------------------------ */
2740/* decNumberSquareRoot -- square root operator */
2741/* */
2742/* This computes C = squareroot(A) */
2743/* */
2744/* res is C, the result. C may be A */
2745/* rhs is A */
2746/* set is the context; note that rounding mode has no effect */
2747/* */
2748/* C must have space for set->digits digits. */
2749/* ------------------------------------------------------------------ */
2750/* This uses the following varying-precision algorithm in: */
2751/* */
2752/* Properly Rounded Variable Precision Square Root, T. E. Hull and */
2753/* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2754/* pp229-237, ACM, September 1985. */
2755/* */
2756/* The square-root is calculated using Newton's method, after which */
2757/* a check is made to ensure the result is correctly rounded. */
2758/* */
2759/* % [Reformatted original Numerical Turing source code follows.] */
2760/* function sqrt(x : real) : real */
2761/* % sqrt(x) returns the properly rounded approximation to the square */
2762/* % root of x, in the precision of the calling environment, or it */
2763/* % fails if x < 0. */
2764/* % t e hull and a abrham, august, 1984 */
2765/* if x <= 0 then */
2766/* if x < 0 then */
2767/* assert false */
2768/* else */
2769/* result 0 */
2770/* end if */
2771/* end if */
2772/* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
2773/* var e := getexp(x) % exponent part of x */
2774/* var approx : real */
2775/* if e mod 2 = 0 then */
2776/* approx := .259 + .819 * f % approx to root of f */
2777/* else */
2778/* f := f/l0 % adjustments */
2779/* e := e + 1 % for odd */
2780/* approx := .0819 + 2.59 * f % exponent */
2781/* end if */
2782/* */
2783/* var p:= 3 */
2784/* const maxp := currentprecision + 2 */
2785/* loop */
2786/* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
2787/* precision p */
2788/* approx := .5 * (approx + f/approx) */
2789/* exit when p = maxp */
2790/* end loop */
2791/* */
2792/* % approx is now within 1 ulp of the properly rounded square root */
2793/* % of f; to ensure proper rounding, compare squares of (approx - */
2794/* % l/2 ulp) and (approx + l/2 ulp) with f. */
2795/* p := currentprecision */
2796/* begin */
2797/* precision p + 2 */
2798/* const approxsubhalf := approx - setexp(.5, -p) */
2799/* if mulru(approxsubhalf, approxsubhalf) > f then */
2800/* approx := approx - setexp(.l, -p + 1) */
2801/* else */
2802/* const approxaddhalf := approx + setexp(.5, -p) */
2803/* if mulrd(approxaddhalf, approxaddhalf) < f then */
2804/* approx := approx + setexp(.l, -p + 1) */
2805/* end if */
2806/* end if */
2807/* end */
2808/* result setexp(approx, e div 2) % fix exponent */
2809/* end sqrt */
2810/* ------------------------------------------------------------------ */
4388f060
A
2811#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
2812#pragma GCC diagnostic push
2813#pragma GCC diagnostic ignored "-Warray-bounds"
2814#endif
729e4ab9
A
2815U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2816 decContext *set) {
2817 decContext workset, approxset; /* work contexts */
2818 decNumber dzero; /* used for constant zero */
2819 Int maxp; /* largest working precision */
2820 Int workp; /* working precision */
2821 Int residue=0; /* rounding residue */
2822 uInt status=0, ignore=0; /* status accumulators */
2823 uInt rstatus; /* .. */
2824 Int exp; /* working exponent */
2825 Int ideal; /* ideal (preferred) exponent */
2826 Int needbytes; /* work */
2827 Int dropped; /* .. */
2828
2829 #if DECSUBSET
2830 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2831 #endif
2832 /* buffer for f [needs +1 in case DECBUFFER 0] */
2833 decNumber buff[D2N(DECBUFFER+1)];
2834 /* buffer for a [needs +2 to match likely maxp] */
2835 decNumber bufa[D2N(DECBUFFER+2)];
2836 /* buffer for temporary, b [must be same size as a] */
2837 decNumber bufb[D2N(DECBUFFER+2)];
2838 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */
2839 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
2840 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
2841 decNumber *f=buff; /* reduced fraction */
2842 decNumber *a=bufa; /* approximation to result */
2843 decNumber *b=bufb; /* intermediate result */
2844 /* buffer for temporary variable, up to 3 digits */
2845 decNumber buft[D2N(3)];
2846 decNumber *t=buft; /* up-to-3-digit constant or work */
2847
2848 #if DECCHECK
2849 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2850 #endif
2851
2852 do { /* protect allocated storage */
2853 #if DECSUBSET
2854 if (!set->extended) {
2855 /* reduce operand and set lostDigits status, as needed */
2856 if (rhs->digits>set->digits) {
2857 allocrhs=decRoundOperand(rhs, set, &status);
2858 if (allocrhs==NULL) break;
2859 /* [Note: 'f' allocation below could reuse this buffer if */
2860 /* used, but as this is rare they are kept separate for clarity.] */
2861 rhs=allocrhs;
2862 }
2863 }
2864 #endif
2865 /* [following code does not require input rounding] */
2866
2867 /* handle infinities and NaNs */
2868 if (SPECIALARG) {
2869 if (decNumberIsInfinite(rhs)) { /* an infinity */
2870 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2871 else uprv_decNumberCopy(res, rhs); /* +Infinity */
2872 }
2873 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2874 break;
2875 }
2876
2877 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2878 /* [It would be nicer to write: ideal=rhs->exponent>>1, but this */
2879 /* generates a compiler warning. Generated code is the same.] */
2880 ideal=(rhs->exponent&~1)/2; /* target */
2881
2882 /* handle zeros */
2883 if (ISZERO(rhs)) {
2884 uprv_decNumberCopy(res, rhs); /* could be 0 or -0 */
2885 res->exponent=ideal; /* use the ideal [safe] */
2886 /* use decFinish to clamp any out-of-range exponent, etc. */
2887 decFinish(res, set, &residue, &status);
2888 break;
2889 }
2890
2891 /* any other -x is an oops */
2892 if (decNumberIsNegative(rhs)) {
2893 status|=DEC_Invalid_operation;
2894 break;
2895 }
2896
2897 /* space is needed for three working variables */
2898 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
2899 /* a -- Hull's approximation -- precision, when assigned, is */
2900 /* currentprecision+1 or the input argument precision, */
2901 /* whichever is larger (+2 for use as temporary) */
2902 /* b -- intermediate temporary result (same size as a) */
2903 /* if any is too long for local storage, then allocate */
2904 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
2905 workp=MAXI(workp, 7); /* at least 7 for low cases */
2906 maxp=workp+2; /* largest working precision */
2907
2908 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2909 if (needbytes>(Int)sizeof(buff)) {
2910 allocbuff=(decNumber *)malloc(needbytes);
2911 if (allocbuff==NULL) { /* hopeless -- abandon */
2912 status|=DEC_Insufficient_storage;
2913 break;}
2914 f=allocbuff; /* use the allocated space */
2915 }
2916 /* a and b both need to be able to hold a maxp-length number */
2917 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2918 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
2919 allocbufa=(decNumber *)malloc(needbytes);
2920 allocbufb=(decNumber *)malloc(needbytes);
2921 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */
2922 status|=DEC_Insufficient_storage;
2923 break;}
2924 a=allocbufa; /* use the allocated spaces */
2925 b=allocbufb; /* .. */
2926 }
2927
2928 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2929 uprv_decNumberCopy(f, rhs);
2930 exp=f->exponent+f->digits; /* adjusted to Hull rules */
2931 f->exponent=-(f->digits); /* to range */
2932
2933 /* set up working context */
2934 uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2935 workset.emax=DEC_MAX_EMAX;
2936 workset.emin=DEC_MIN_EMIN;
2937
2938 /* [Until further notice, no error is possible and status bits */
2939 /* (Rounded, etc.) should be ignored, not accumulated.] */
2940
2941 /* Calculate initial approximation, and allow for odd exponent */
2942 workset.digits=workp; /* p for initial calculation */
2943 t->bits=0; t->digits=3;
2944 a->bits=0; a->digits=3;
2945 if ((exp & 1)==0) { /* even exponent */
2946 /* Set t=0.259, a=0.819 */
2947 t->exponent=-3;
2948 a->exponent=-3;
2949 #if DECDPUN>=3
2950 t->lsu[0]=259;
2951 a->lsu[0]=819;
2952 #elif DECDPUN==2
2953 t->lsu[0]=59; t->lsu[1]=2;
2954 a->lsu[0]=19; a->lsu[1]=8;
2955 #else
2956 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2957 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2958 #endif
2959 }
2960 else { /* odd exponent */
2961 /* Set t=0.0819, a=2.59 */
2962 f->exponent--; /* f=f/10 */
2963 exp++; /* e=e+1 */
2964 t->exponent=-4;
2965 a->exponent=-2;
2966 #if DECDPUN>=3
2967 t->lsu[0]=819;
2968 a->lsu[0]=259;
2969 #elif DECDPUN==2
2970 t->lsu[0]=19; t->lsu[1]=8;
2971 a->lsu[0]=59; a->lsu[1]=2;
2972 #else
2973 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2974 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2975 #endif
2976 }
2977
2978 decMultiplyOp(a, a, f, &workset, &ignore); /* a=a*f */
2979 decAddOp(a, a, t, &workset, 0, &ignore); /* ..+t */
2980 /* [a is now the initial approximation for sqrt(f), calculated with */
2981 /* currentprecision, which is also a's precision.] */
2982
2983 /* the main calculation loop */
2984 uprv_decNumberZero(&dzero); /* make 0 */
2985 uprv_decNumberZero(t); /* set t = 0.5 */
2986 t->lsu[0]=5; /* .. */
2987 t->exponent=-1; /* .. */
2988 workset.digits=3; /* initial p */
2989 for (; workset.digits<maxp;) {
2990 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
2991 workset.digits=MINI(workset.digits*2-2, maxp);
2992 /* a = 0.5 * (a + f/a) */
2993 /* [calculated at p then rounded to currentprecision] */
2994 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
2995 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
2996 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
2997 } /* loop */
2998
2999 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
3000 /* now reduce to length, etc.; this needs to be done with a */
3001 /* having the correct exponent so as to handle subnormals */
3002 /* correctly */
3003 approxset=*set; /* get emin, emax, etc. */
3004 approxset.round=DEC_ROUND_HALF_EVEN;
3005 a->exponent+=exp/2; /* set correct exponent */
3006 rstatus=0; /* clear status */
3007 residue=0; /* .. and accumulator */
3008 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
3009 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
3010
3011 /* Overflow was possible if the input exponent was out-of-range, */
3012 /* in which case quit */
3013 if (rstatus&DEC_Overflow) {
3014 status=rstatus; /* use the status as-is */
3015 uprv_decNumberCopy(res, a); /* copy to result */
3016 break;
3017 }
3018
3019 /* Preserve status except Inexact/Rounded */
3020 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3021
3022 /* Carry out the Hull correction */
3023 a->exponent-=exp/2; /* back to 0.1->1 */
3024
3025 /* a is now at final precision and within 1 ulp of the properly */
3026 /* rounded square root of f; to ensure proper rounding, compare */
3027 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3028 /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3029 /* the ulp */
3030 workset.digits--; /* maxp-1 is OK now */
3031 t->exponent=-a->digits-1; /* make 0.5 ulp */
3032 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3033 workset.round=DEC_ROUND_UP;
3034 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
3035 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3036 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
3037 /* this is the more common adjustment, though both are rare */
3038 t->exponent++; /* make 1.0 ulp */
3039 t->lsu[0]=1; /* .. */
3040 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3041 /* assign to approx [round to length] */
3042 approxset.emin-=exp/2; /* adjust to match a */
3043 approxset.emax-=exp/2;
3044 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3045 }
3046 else {
3047 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
3048 workset.round=DEC_ROUND_DOWN;
3049 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
3050 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
3051 if (decNumberIsNegative(b)) { /* b < f */
3052 t->exponent++; /* make 1.0 ulp */
3053 t->lsu[0]=1; /* .. */
3054 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
3055 /* assign to approx [round to length] */
3056 approxset.emin-=exp/2; /* adjust to match a */
3057 approxset.emax-=exp/2;
3058 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3059 }
3060 }
3061 /* [no errors are possible in the above, and rounding/inexact during */
3062 /* estimation are irrelevant, so status was not accumulated] */
3063
3064 /* Here, 0.1 <= a < 1 (still), so adjust back */
3065 a->exponent+=exp/2; /* set correct exponent */
3066
3067 /* count droppable zeros [after any subnormal rounding] by */
3068 /* trimming a copy */
3069 uprv_decNumberCopy(b, a);
3070 decTrim(b, set, 1, 1, &dropped); /* [drops trailing zeros] */
3071
3072 /* Set Inexact and Rounded. The answer can only be exact if */
3073 /* it is short enough so that squaring it could fit in workp */
3074 /* digits, so this is the only (relatively rare) condition that */
3075 /* a careful check is needed */
3076 if (b->digits*2-1 > workp) { /* cannot fit */
3077 status|=DEC_Inexact|DEC_Rounded;
3078 }
3079 else { /* could be exact/unrounded */
3080 uInt mstatus=0; /* local status */
3081 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3082 if (mstatus&DEC_Overflow) { /* result just won't fit */
3083 status|=DEC_Inexact|DEC_Rounded;
3084 }
3085 else { /* plausible */
3086 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3087 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3088 else { /* is Exact */
3089 /* here, dropped is the count of trailing zeros in 'a' */
3090 /* use closest exponent to ideal... */
3091 Int todrop=ideal-a->exponent; /* most that can be dropped */
3092 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3093 else { /* unrounded */
3094 /* there are some to drop, but emax may not allow all */
3095 Int maxexp=set->emax-set->digits+1;
3096 Int maxdrop=maxexp-a->exponent;
3097 if (todrop>maxdrop && set->clamp) { /* apply clamping */
3098 todrop=maxdrop;
3099 status|=DEC_Clamped;
3100 }
3101 if (dropped<todrop) { /* clamp to those available */
3102 todrop=dropped;
3103 status|=DEC_Clamped;
3104 }
3105 if (todrop>0) { /* have some to drop */
3106 decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3107 a->exponent+=todrop; /* maintain numerical value */
3108 a->digits-=todrop; /* new length */
3109 }
3110 }
3111 }
3112 }
3113 }
3114
3115 /* double-check Underflow, as perhaps the result could not have */
3116 /* been subnormal (initial argument too big), or it is now Exact */
3117 if (status&DEC_Underflow) {
3118 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
3119 /* check if truly subnormal */
3120 #if DECEXTFLAG /* DEC_Subnormal too */
3121 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3122 #else
3123 if (ae>=set->emin*2) status&=~DEC_Underflow;
3124 #endif
3125 /* check if truly inexact */
3126 if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3127 }
3128
3129 uprv_decNumberCopy(res, a); /* a is now the result */
3130 } while(0); /* end protected */
3131
3132 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */
3133 if (allocbufa!=NULL) free(allocbufa); /* .. */
3134 if (allocbufb!=NULL) free(allocbufb); /* .. */
3135 #if DECSUBSET
3136 if (allocrhs !=NULL) free(allocrhs); /* .. */
3137 #endif
3138 if (status!=0) decStatus(res, status, set);/* then report status */
3139 #if DECCHECK
3140 decCheckInexact(res, set);
3141 #endif
3142 return res;
3143 } /* decNumberSquareRoot */
4388f060
A
3144#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
3145#pragma GCC diagnostic pop
3146#endif
729e4ab9
A
3147
3148/* ------------------------------------------------------------------ */
3149/* decNumberSubtract -- subtract two Numbers */
3150/* */
3151/* This computes C = A - B */
3152/* */
3153/* res is C, the result. C may be A and/or B (e.g., X=X-X) */
3154/* lhs is A */
3155/* rhs is B */
3156/* set is the context */
3157/* */
3158/* C must have space for set->digits digits. */
3159/* ------------------------------------------------------------------ */
3160U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3161 const decNumber *rhs, decContext *set) {
3162 uInt status=0; /* accumulator */
3163
3164 decAddOp(res, lhs, rhs, set, DECNEG, &status);
3165 if (status!=0) decStatus(res, status, set);
3166 #if DECCHECK
3167 decCheckInexact(res, set);
3168 #endif
3169 return res;
3170 } /* decNumberSubtract */
3171
3172/* ------------------------------------------------------------------ */
3173/* decNumberToIntegralExact -- round-to-integral-value with InExact */
3174/* decNumberToIntegralValue -- round-to-integral-value */
3175/* */
3176/* res is the result */
3177/* rhs is input number */
3178/* set is the context */
3179/* */
3180/* res must have space for any value of rhs. */
3181/* */
3182/* This implements the IEEE special operators and therefore treats */
3183/* special values as valid. For finite numbers it returns */
3184/* rescale(rhs, 0) if rhs->exponent is <0. */
3185/* Otherwise the result is rhs (so no error is possible, except for */
3186/* sNaN). */
3187/* */
3188/* The context is used for rounding mode and status after sNaN, but */
3189/* the digits setting is ignored. The Exact version will signal */
3190/* Inexact if the result differs numerically from rhs; the other */
3191/* never signals Inexact. */
3192/* ------------------------------------------------------------------ */
3193U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3194 decContext *set) {
3195 decNumber dn;
3196 decContext workset; /* working context */
3197 uInt status=0; /* accumulator */
3198
3199 #if DECCHECK
3200 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3201 #endif
3202
3203 /* handle infinities and NaNs */
3204 if (SPECIALARG) {
3205 if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity */
3206 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3207 }
3208 else { /* finite */
3209 /* have a finite number; no error possible (res must be big enough) */
3210 if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3211 /* that was easy, but if negative exponent there is work to do... */
3212 workset=*set; /* clone rounding, etc. */
3213 workset.digits=rhs->digits; /* no length rounding */
3214 workset.traps=0; /* no traps */
3215 uprv_decNumberZero(&dn); /* make a number with exponent 0 */
3216 uprv_decNumberQuantize(res, rhs, &dn, &workset);
3217 status|=workset.status;
3218 }
3219 if (status!=0) decStatus(res, status, set);
3220 return res;
3221 } /* decNumberToIntegralExact */
3222
3223U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3224 decContext *set) {
3225 decContext workset=*set; /* working context */
3226 workset.traps=0; /* no traps */
3227 uprv_decNumberToIntegralExact(res, rhs, &workset);
3228 /* this never affects set, except for sNaNs; NaN will have been set */
3229 /* or propagated already, so no need to call decStatus */
3230 set->status|=workset.status&DEC_Invalid_operation;
3231 return res;
3232 } /* decNumberToIntegralValue */
3233
3234/* ------------------------------------------------------------------ */
3235/* decNumberXor -- XOR two Numbers, digitwise */
3236/* */
3237/* This computes C = A ^ B */
3238/* */
3239/* res is C, the result. C may be A and/or B (e.g., X=X^X) */
3240/* lhs is A */
3241/* rhs is B */
3242/* set is the context (used for result length and error report) */
3243/* */
3244/* C must have space for set->digits digits. */
3245/* */
3246/* Logical function restrictions apply (see above); a NaN is */
3247/* returned with Invalid_operation if a restriction is violated. */
3248/* ------------------------------------------------------------------ */
3249U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3250 const decNumber *rhs, decContext *set) {
3251 const Unit *ua, *ub; /* -> operands */
3252 const Unit *msua, *msub; /* -> operand msus */
3253 Unit *uc, *msuc; /* -> result and its msu */
3254 Int msudigs; /* digits in res msu */
3255 #if DECCHECK
3256 if (decCheckOperands(res, lhs, rhs, set)) return res;
3257 #endif
3258
3259 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3260 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3261 decStatus(res, DEC_Invalid_operation, set);
3262 return res;
3263 }
3264 /* operands are valid */
3265 ua=lhs->lsu; /* bottom-up */
3266 ub=rhs->lsu; /* .. */
3267 uc=res->lsu; /* .. */
3268 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
3269 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
3270 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
3271 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
3272 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
3273 Unit a, b; /* extract units */
3274 if (ua>msua) a=0;
3275 else a=*ua;
3276 if (ub>msub) b=0;
3277 else b=*ub;
3278 *uc=0; /* can now write back */
3279 if (a|b) { /* maybe 1 bits to examine */
3280 Int i, j;
3281 /* This loop could be unrolled and/or use BIN2BCD tables */
3282 for (i=0; i<DECDPUN; i++) {
3283 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
3284 j=a%10;
3285 a=a/10;
3286 j|=b%10;
3287 b=b/10;
3288 if (j>1) {
3289 decStatus(res, DEC_Invalid_operation, set);
3290 return res;
3291 }
3292 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
3293 } /* each digit */
3294 } /* non-zero */
3295 } /* each unit */
3296 /* [here uc-1 is the msu of the result] */
3297 res->digits=decGetDigits(res->lsu, uc-res->lsu);
3298 res->exponent=0; /* integer */
3299 res->bits=0; /* sign=0 */
3300 return res; /* [no status to set] */
3301 } /* decNumberXor */
3302
3303
3304/* ================================================================== */
3305/* Utility routines */
3306/* ================================================================== */
3307
3308/* ------------------------------------------------------------------ */
3309/* decNumberClass -- return the decClass of a decNumber */
3310/* dn -- the decNumber to test */
3311/* set -- the context to use for Emin */
3312/* returns the decClass enum */
3313/* ------------------------------------------------------------------ */
3314enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3315 if (decNumberIsSpecial(dn)) {
3316 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3317 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3318 /* must be an infinity */
3319 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3320 return DEC_CLASS_POS_INF;
3321 }
3322 /* is finite */
3323 if (uprv_decNumberIsNormal(dn, set)) { /* most common */
3324 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3325 return DEC_CLASS_POS_NORMAL;
3326 }
3327 /* is subnormal or zero */
3328 if (decNumberIsZero(dn)) { /* most common */
3329 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3330 return DEC_CLASS_POS_ZERO;
3331 }
3332 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3333 return DEC_CLASS_POS_SUBNORMAL;
3334 } /* decNumberClass */
3335
3336/* ------------------------------------------------------------------ */
3337/* decNumberClassToString -- convert decClass to a string */
3338/* */
3339/* eclass is a valid decClass */
3340/* returns a constant string describing the class (max 13+1 chars) */
3341/* ------------------------------------------------------------------ */
3342const char *uprv_decNumberClassToString(enum decClass eclass) {
3343 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
3344 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
3345 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
3346 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
3347 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3348 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3349 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
3350 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
3351 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
3352 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
3353 return DEC_ClassString_UN; /* Unknown */
3354 } /* decNumberClassToString */
3355
3356/* ------------------------------------------------------------------ */
3357/* decNumberCopy -- copy a number */
3358/* */
3359/* dest is the target decNumber */
3360/* src is the source decNumber */
3361/* returns dest */
3362/* */
3363/* (dest==src is allowed and is a no-op) */
3364/* All fields are updated as required. This is a utility operation, */
3365/* so special values are unchanged and no error is possible. */
3366/* ------------------------------------------------------------------ */
3367U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3368
3369 #if DECCHECK
3370 if (src==NULL) return uprv_decNumberZero(dest);
3371 #endif
3372
3373 if (dest==src) return dest; /* no copy required */
3374
3375 /* Use explicit assignments here as structure assignment could copy */
3376 /* more than just the lsu (for small DECDPUN). This would not affect */
3377 /* the value of the results, but could disturb test harness spill */
3378 /* checking. */
3379 dest->bits=src->bits;
3380 dest->exponent=src->exponent;
3381 dest->digits=src->digits;
3382 dest->lsu[0]=src->lsu[0];
3383 if (src->digits>DECDPUN) { /* more Units to come */
3384 const Unit *smsup, *s; /* work */
3385 Unit *d; /* .. */
3386 /* memcpy for the remaining Units would be safe as they cannot */
3387 /* overlap. However, this explicit loop is faster in short cases. */
3388 d=dest->lsu+1; /* -> first destination */
3389 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
3390 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3391 }
3392 return dest;
3393 } /* decNumberCopy */
3394
3395/* ------------------------------------------------------------------ */
3396/* decNumberCopyAbs -- quiet absolute value operator */
3397/* */
3398/* This sets C = abs(A) */
3399/* */
3400/* res is C, the result. C may be A */
3401/* rhs is A */
3402/* */
3403/* C must have space for set->digits digits. */
3404/* No exception or error can occur; this is a quiet bitwise operation.*/
3405/* See also decNumberAbs for a checking version of this. */
3406/* ------------------------------------------------------------------ */
3407U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3408 #if DECCHECK
3409 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3410 #endif
3411 uprv_decNumberCopy(res, rhs);
3412 res->bits&=~DECNEG; /* turn off sign */
3413 return res;
3414 } /* decNumberCopyAbs */
3415
3416/* ------------------------------------------------------------------ */
3417/* decNumberCopyNegate -- quiet negate value operator */
3418/* */
3419/* This sets C = negate(A) */
3420/* */
3421/* res is C, the result. C may be A */
3422/* rhs is A */
3423/* */
3424/* C must have space for set->digits digits. */
3425/* No exception or error can occur; this is a quiet bitwise operation.*/
3426/* See also decNumberMinus for a checking version of this. */
3427/* ------------------------------------------------------------------ */
3428U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3429 #if DECCHECK
3430 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3431 #endif
3432 uprv_decNumberCopy(res, rhs);
3433 res->bits^=DECNEG; /* invert the sign */
3434 return res;
3435 } /* decNumberCopyNegate */
3436
3437/* ------------------------------------------------------------------ */
3438/* decNumberCopySign -- quiet copy and set sign operator */
3439/* */
3440/* This sets C = A with the sign of B */
3441/* */
3442/* res is C, the result. C may be A */
3443/* lhs is A */
3444/* rhs is B */
3445/* */
3446/* C must have space for set->digits digits. */
3447/* No exception or error can occur; this is a quiet bitwise operation.*/
3448/* ------------------------------------------------------------------ */
3449U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3450 const decNumber *rhs) {
3451 uByte sign; /* rhs sign */
3452 #if DECCHECK
3453 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3454 #endif
3455 sign=rhs->bits & DECNEG; /* save sign bit */
3456 uprv_decNumberCopy(res, lhs);
3457 res->bits&=~DECNEG; /* clear the sign */
3458 res->bits|=sign; /* set from rhs */
3459 return res;
3460 } /* decNumberCopySign */
3461
3462/* ------------------------------------------------------------------ */
3463/* decNumberGetBCD -- get the coefficient in BCD8 */
3464/* dn is the source decNumber */
3465/* bcd is the uInt array that will receive dn->digits BCD bytes, */
3466/* most-significant at offset 0 */
3467/* returns bcd */
3468/* */
3469/* bcd must have at least dn->digits bytes. No error is possible; if */
3470/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
3471/* ------------------------------------------------------------------ */
3472U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3473 uByte *ub=bcd+dn->digits-1; /* -> lsd */
3474 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
3475
3476 #if DECDPUN==1 /* trivial simple copy */
3477 for (; ub>=bcd; ub--, up++) *ub=*up;
3478 #else /* chopping needed */
3479 uInt u=*up; /* work */
3480 uInt cut=DECDPUN; /* downcounter through unit */
3481 for (; ub>=bcd; ub--) {
3482 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
3483 u=u/10;
3484 cut--;
3485 if (cut>0) continue; /* more in this unit */
3486 up++;
3487 u=*up;
3488 cut=DECDPUN;
3489 }
3490 #endif
3491 return bcd;
3492 } /* decNumberGetBCD */
3493
3494/* ------------------------------------------------------------------ */
3495/* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
3496/* dn is the target decNumber */
3497/* bcd is the uInt array that will source n BCD bytes, most- */
3498/* significant at offset 0 */
3499/* n is the number of digits in the source BCD array (bcd) */
3500/* returns dn */
3501/* */
3502/* dn must have space for at least n digits. No error is possible; */
3503/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
3504/* and bcd[0] zero. */
3505/* ------------------------------------------------------------------ */
3506U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3507 Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */
3508 const uByte *ub=bcd; /* -> source msd */
3509
3510 #if DECDPUN==1 /* trivial simple copy */
3511 for (; ub<bcd+n; ub++, up--) *up=*ub;
3512 #else /* some assembly needed */
3513 /* calculate how many digits in msu, and hence first cut */
3514 Int cut=MSUDIGITS(n); /* [faster than remainder] */
3515 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3516 *up=0; /* will take <=DECDPUN digits */
3517 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3518 cut=DECDPUN; /* next Unit has all digits */
3519 }
3520 #endif
3521 dn->digits=n; /* set digit count */
3522 return dn;
3523 } /* decNumberSetBCD */
3524
3525/* ------------------------------------------------------------------ */
3526/* decNumberIsNormal -- test normality of a decNumber */
3527/* dn is the decNumber to test */
3528/* set is the context to use for Emin */
3529/* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
3530/* ------------------------------------------------------------------ */
3531Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3532 Int ae; /* adjusted exponent */
3533 #if DECCHECK
3534 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3535 #endif
3536
3537 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3538 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3539
3540 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3541 if (ae<set->emin) return 0; /* is subnormal */
3542 return 1;
3543 } /* decNumberIsNormal */
3544
3545/* ------------------------------------------------------------------ */
3546/* decNumberIsSubnormal -- test subnormality of a decNumber */
3547/* dn is the decNumber to test */
3548/* set is the context to use for Emin */
3549/* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
3550/* ------------------------------------------------------------------ */
3551Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3552 Int ae; /* adjusted exponent */
3553 #if DECCHECK
3554 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3555 #endif
3556
3557 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3558 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3559
3560 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3561 if (ae<set->emin) return 1; /* is subnormal */
3562 return 0;
3563 } /* decNumberIsSubnormal */
3564
3565/* ------------------------------------------------------------------ */
3566/* decNumberTrim -- remove insignificant zeros */
3567/* */
3568/* dn is the number to trim */
3569/* returns dn */
3570/* */
3571/* All fields are updated as required. This is a utility operation, */
3572/* so special values are unchanged and no error is possible. The */
3573/* zeros are removed unconditionally. */
3574/* ------------------------------------------------------------------ */
3575U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3576 Int dropped; /* work */
3577 decContext set; /* .. */
3578 #if DECCHECK
3579 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3580 #endif
3581 uprv_decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
3582 return decTrim(dn, &set, 0, 1, &dropped);
3583 } /* decNumberTrim */
3584
3585/* ------------------------------------------------------------------ */
3586/* decNumberVersion -- return the name and version of this module */
3587/* */
3588/* No error is possible. */
3589/* ------------------------------------------------------------------ */
3590const char * uprv_decNumberVersion(void) {
3591 return DECVERSION;
3592 } /* decNumberVersion */
3593
3594/* ------------------------------------------------------------------ */
3595/* decNumberZero -- set a number to 0 */
3596/* */
3597/* dn is the number to set, with space for one digit */
3598/* returns dn */
3599/* */
3600/* No error is possible. */
3601/* ------------------------------------------------------------------ */
3602/* Memset is not used as it is much slower in some environments. */
3603U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3604
3605 #if DECCHECK
3606 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3607 #endif
3608
3609 dn->bits=0;
3610 dn->exponent=0;
3611 dn->digits=1;
3612 dn->lsu[0]=0;
3613 return dn;
3614 } /* decNumberZero */
3615
3616/* ================================================================== */
3617/* Local routines */
3618/* ================================================================== */
3619
3620/* ------------------------------------------------------------------ */
3621/* decToString -- lay out a number into a string */
3622/* */
3623/* dn is the number to lay out */
3624/* string is where to lay out the number */
3625/* eng is 1 if Engineering, 0 if Scientific */
3626/* */
3627/* string must be at least dn->digits+14 characters long */
3628/* No error is possible. */
3629/* */
3630/* Note that this routine can generate a -0 or 0.000. These are */
3631/* never generated in subset to-number or arithmetic, but can occur */
3632/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
3633/* ------------------------------------------------------------------ */
3634/* If DECCHECK is enabled the string "?" is returned if a number is */
3635/* invalid. */
3636static void decToString(const decNumber *dn, char *string, Flag eng) {
3637 Int exp=dn->exponent; /* local copy */
3638 Int e; /* E-part value */
3639 Int pre; /* digits before the '.' */
3640 Int cut; /* for counting digits in a Unit */
3641 char *c=string; /* work [output pointer] */
3642 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3643 uInt u, pow; /* work */
3644
3645 #if DECCHECK
3646 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3647 strcpy(string, "?");
3648 return;}
3649 #endif
3650
3651 if (decNumberIsNegative(dn)) { /* Negatives get a minus */
3652 *c='-';
3653 c++;
3654 }
3655 if (dn->bits&DECSPECIAL) { /* Is a special value */
3656 if (decNumberIsInfinite(dn)) {
3657 strcpy(c, "Inf");
3658 strcpy(c+3, "inity");
3659 return;}
3660 /* a NaN */
3661 if (dn->bits&DECSNAN) { /* signalling NaN */
3662 *c='s';
3663 c++;
3664 }
3665 strcpy(c, "NaN");
3666 c+=3; /* step past */
3667 /* if not a clean non-zero coefficient, that's all there is in a */
3668 /* NaN string */
3669 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3670 /* [drop through to add integer] */
3671 }
3672
3673 /* calculate how many digits in msu, and hence first cut */
3674 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
3675 cut--; /* power of ten for digit */
3676
3677 if (exp==0) { /* simple integer [common fastpath] */
3678 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3679 u=*up; /* contains DECDPUN digits to lay out */
3680 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3681 cut=DECDPUN-1; /* next Unit has all digits */
3682 }
3683 *c='\0'; /* terminate the string */
3684 return;}
3685
3686 /* non-0 exponent -- assume plain form */
3687 pre=dn->digits+exp; /* digits before '.' */
3688 e=0; /* no E */
3689 if ((exp>0) || (pre<-5)) { /* need exponential form */
3690 e=exp+dn->digits-1; /* calculate E value */
3691 pre=1; /* assume one digit before '.' */
3692 if (eng && (e!=0)) { /* engineering: may need to adjust */
3693 Int adj; /* adjustment */
3694 /* The C remainder operator is undefined for negative numbers, so */
3695 /* a positive remainder calculation must be used here */
3696 if (e<0) {
3697 adj=(-e)%3;
3698 if (adj!=0) adj=3-adj;
3699 }
3700 else { /* e>0 */
3701 adj=e%3;
3702 }
3703 e=e-adj;
3704 /* if dealing with zero still produce an exponent which is a */
3705 /* multiple of three, as expected, but there will only be the */
3706 /* one zero before the E, still. Otherwise note the padding. */
3707 if (!ISZERO(dn)) pre+=adj;
3708 else { /* is zero */
3709 if (adj!=0) { /* 0.00Esnn needed */
3710 e=e+3;
3711 pre=-(2-adj);
3712 }
3713 } /* zero */
3714 } /* eng */
3715 } /* need exponent */
3716
3717 /* lay out the digits of the coefficient, adding 0s and . as needed */
3718 u=*up;
3719 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
3720 Int n=pre;
3721 for (; pre>0; pre--, c++, cut--) {
3722 if (cut<0) { /* need new Unit */
3723 if (up==dn->lsu) break; /* out of input digits (pre>digits) */
3724 up--;
3725 cut=DECDPUN-1;
3726 u=*up;
3727 }
3728 TODIGIT(u, cut, c, pow);
3729 }
3730 if (n<dn->digits) { /* more to come, after '.' */
3731 *c='.'; c++;
3732 for (;; c++, cut--) {
3733 if (cut<0) { /* need new Unit */
3734 if (up==dn->lsu) break; /* out of input digits */
3735 up--;
3736 cut=DECDPUN-1;
3737 u=*up;
3738 }
3739 TODIGIT(u, cut, c, pow);
3740 }
3741 }
3742 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3743 }
3744 else { /* 0.xxx or 0.000xxx form */
3745 *c='0'; c++;
3746 *c='.'; c++;
3747 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
3748 for (; ; c++, cut--) {
3749 if (cut<0) { /* need new Unit */
3750 if (up==dn->lsu) break; /* out of input digits */
3751 up--;
3752 cut=DECDPUN-1;
3753 u=*up;
3754 }
3755 TODIGIT(u, cut, c, pow);
3756 }
3757 }
3758
3759 /* Finally add the E-part, if needed. It will never be 0, has a
3760 base maximum and minimum of +999999999 through -999999999, but
3761 could range down to -1999999998 for anormal numbers */
3762 if (e!=0) {
3763 Flag had=0; /* 1=had non-zero */
3764 *c='E'; c++;
3765 *c='+'; c++; /* assume positive */
3766 u=e; /* .. */
3767 if (e<0) {
3768 *(c-1)='-'; /* oops, need - */
3769 u=-e; /* uInt, please */
3770 }
3771 /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3772 for (cut=9; cut>=0; cut--) {
3773 TODIGIT(u, cut, c, pow);
3774 if (*c=='0' && !had) continue; /* skip leading zeros */
3775 had=1; /* had non-0 */
3776 c++; /* step for next */
3777 } /* cut */
3778 }
3779 *c='\0'; /* terminate the string (all paths) */
3780 return;
3781 } /* decToString */
3782
3783/* ------------------------------------------------------------------ */
3784/* decAddOp -- add/subtract operation */
3785/* */
3786/* This computes C = A + B */
3787/* */
3788/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
3789/* lhs is A */
3790/* rhs is B */
3791/* set is the context */
3792/* negate is DECNEG if rhs should be negated, or 0 otherwise */
3793/* status accumulates status for the caller */
3794/* */
3795/* C must have space for set->digits digits. */
3796/* Inexact in status must be 0 for correct Exact zero sign in result */
3797/* ------------------------------------------------------------------ */
3798/* If possible, the coefficient is calculated directly into C. */
3799/* However, if: */
3800/* -- a digits+1 calculation is needed because the numbers are */
3801/* unaligned and span more than set->digits digits */
3802/* -- a carry to digits+1 digits looks possible */
3803/* -- C is the same as A or B, and the result would destructively */
3804/* overlap the A or B coefficient */
3805/* then the result must be calculated into a temporary buffer. In */
3806/* this case a local (stack) buffer is used if possible, and only if */
3807/* too long for that does malloc become the final resort. */
3808/* */
3809/* Misalignment is handled as follows: */
3810/* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
3811/* BPad: Apply the padding by a combination of shifting (whole */
3812/* units) and multiplication (part units). */
3813/* */
3814/* Addition, especially x=x+1, is speed-critical. */
3815/* The static buffer is larger than might be expected to allow for */
3816/* calls from higher-level funtions (notable exp). */
3817/* ------------------------------------------------------------------ */
3818static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3819 const decNumber *rhs, decContext *set,
3820 uByte negate, uInt *status) {
3821 #if DECSUBSET
3822 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
3823 decNumber *allocrhs=NULL; /* .., rhs */
3824 #endif
3825 Int rhsshift; /* working shift (in Units) */
3826 Int maxdigits; /* longest logical length */
3827 Int mult; /* multiplier */
3828 Int residue; /* rounding accumulator */
3829 uByte bits; /* result bits */
3830 Flag diffsign; /* non-0 if arguments have different sign */
3831 Unit *acc; /* accumulator for result */
3832 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3833 /* allocations when called from */
3834 /* other operations, notable exp] */
3835 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
3836 Int reqdigits=set->digits; /* local copy; requested DIGITS */
3837 Int padding; /* work */
3838
3839 #if DECCHECK
3840 if (decCheckOperands(res, lhs, rhs, set)) return res;
3841 #endif
3842
3843 do { /* protect allocated storage */
3844 #if DECSUBSET
3845 if (!set->extended) {
3846 /* reduce operands and set lostDigits status, as needed */
3847 if (lhs->digits>reqdigits) {
3848 alloclhs=decRoundOperand(lhs, set, status);
3849 if (alloclhs==NULL) break;
3850 lhs=alloclhs;
3851 }
3852 if (rhs->digits>reqdigits) {
3853 allocrhs=decRoundOperand(rhs, set, status);
3854 if (allocrhs==NULL) break;
3855 rhs=allocrhs;
3856 }
3857 }
3858 #endif
3859 /* [following code does not require input rounding] */
3860
3861 /* note whether signs differ [used all paths] */
3862 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3863
3864 /* handle infinities and NaNs */
3865 if (SPECIALARGS) { /* a special bit set */
3866 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
3867 decNaNs(res, lhs, rhs, set, status);
3868 else { /* one or two infinities */
3869 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3870 /* two infinities with different signs is invalid */
3871 if (decNumberIsInfinite(rhs) && diffsign) {
3872 *status|=DEC_Invalid_operation;
3873 break;
3874 }
3875 bits=lhs->bits & DECNEG; /* get sign from LHS */
3876 }
3877 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3878 bits|=DECINF;
3879 uprv_decNumberZero(res);
3880 res->bits=bits; /* set +/- infinity */
3881 } /* an infinity */
3882 break;
3883 }
3884
3885 /* Quick exit for add 0s; return the non-0, modified as need be */
3886 if (ISZERO(lhs)) {
3887 Int adjust; /* work */
3888 Int lexp=lhs->exponent; /* save in case LHS==RES */
3889 bits=lhs->bits; /* .. */
3890 residue=0; /* clear accumulator */
3891 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3892 res->bits^=negate; /* flip if rhs was negated */
3893 #if DECSUBSET
3894 if (set->extended) { /* exponents on zeros count */
3895 #endif
3896 /* exponent will be the lower of the two */
3897 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
3898 if (ISZERO(res)) { /* both 0: special IEEE 754 rules */
3899 if (adjust<0) res->exponent=lexp; /* set exponent */
3900 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3901 if (diffsign) {
3902 if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3903 else res->bits=DECNEG; /* preserve 0 sign */
3904 }
3905 }
3906 else { /* non-0 res */
3907 if (adjust<0) { /* 0-padding needed */
3908 if ((res->digits-adjust)>set->digits) {
3909 adjust=res->digits-set->digits; /* to fit exactly */
3910 *status|=DEC_Rounded; /* [but exact] */
3911 }
3912 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3913 res->exponent+=adjust; /* set the exponent. */
3914 }
3915 } /* non-0 res */
3916 #if DECSUBSET
3917 } /* extended */
3918 #endif
3919 decFinish(res, set, &residue, status); /* clean and finalize */
3920 break;}
3921
3922 if (ISZERO(rhs)) { /* [lhs is non-zero] */
3923 Int adjust; /* work */
3924 Int rexp=rhs->exponent; /* save in case RHS==RES */
3925 bits=rhs->bits; /* be clean */
3926 residue=0; /* clear accumulator */
3927 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3928 #if DECSUBSET
3929 if (set->extended) { /* exponents on zeros count */
3930 #endif
3931 /* exponent will be the lower of the two */
3932 /* [0-0 case handled above] */
3933 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
3934 if (adjust<0) { /* 0-padding needed */
3935 if ((res->digits-adjust)>set->digits) {
3936 adjust=res->digits-set->digits; /* to fit exactly */
3937 *status|=DEC_Rounded; /* [but exact] */
3938 }
3939 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3940 res->exponent+=adjust; /* set the exponent. */
3941 }
3942 #if DECSUBSET
3943 } /* extended */
3944 #endif
3945 decFinish(res, set, &residue, status); /* clean and finalize */
3946 break;}
3947
3948 /* [NB: both fastpath and mainpath code below assume these cases */
3949 /* (notably 0-0) have already been handled] */
3950
3951 /* calculate the padding needed to align the operands */
3952 padding=rhs->exponent-lhs->exponent;
3953
3954 /* Fastpath cases where the numbers are aligned and normal, the RHS */
3955 /* is all in one unit, no operand rounding is needed, and no carry, */
3956 /* lengthening, or borrow is needed */
3957 if (padding==0
3958 && rhs->digits<=DECDPUN
3959 && rhs->exponent>=set->emin /* [some normals drop through] */
3960 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3961 && rhs->digits<=reqdigits
3962 && lhs->digits<=reqdigits) {
3963 Int partial=*lhs->lsu;
3964 if (!diffsign) { /* adding */
3965 partial+=*rhs->lsu;
3966 if ((partial<=DECDPUNMAX) /* result fits in unit */
3967 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
3968 partial<(Int)powers[lhs->digits])) { /* .. */
3969 if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
3970 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
3971 break;
3972 }
3973 /* else drop out for careful add */
3974 }
3975 else { /* signs differ */
3976 partial-=*rhs->lsu;
3977 if (partial>0) { /* no borrow needed, and non-0 result */
3978 if (res!=lhs) uprv_decNumberCopy(res, lhs); /* not in place */
3979 *res->lsu=(Unit)partial;
3980 /* this could have reduced digits [but result>0] */
3981 res->digits=decGetDigits(res->lsu, D2U(res->digits));
3982 break;
3983 }
3984 /* else drop out for careful subtract */
3985 }
3986 }
3987
3988 /* Now align (pad) the lhs or rhs so they can be added or */
3989 /* subtracted, as necessary. If one number is much larger than */
3990 /* the other (that is, if in plain form there is a least one */
3991 /* digit between the lowest digit of one and the highest of the */
3992 /* other) padding with up to DIGITS-1 trailing zeros may be */
3993 /* needed; then apply rounding (as exotic rounding modes may be */
3994 /* affected by the residue). */
3995 rhsshift=0; /* rhs shift to left (padding) in Units */
3996 bits=lhs->bits; /* assume sign is that of LHS */
3997 mult=1; /* likely multiplier */
3998
3999 /* [if padding==0 the operands are aligned; no padding is needed] */
4000 if (padding!=0) {
4001 /* some padding needed; always pad the RHS, as any required */
4002 /* padding can then be effected by a simple combination of */
4003 /* shifts and a multiply */
4004 Flag swapped=0;
4005 if (padding<0) { /* LHS needs the padding */
4006 const decNumber *t;
4007 padding=-padding; /* will be +ve */
4008 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
4009 t=lhs; lhs=rhs; rhs=t;
4010 swapped=1;
4011 }
4012
4013 /* If, after pad, rhs would be longer than lhs by digits+1 or */
4014 /* more then lhs cannot affect the answer, except as a residue, */
4015 /* so only need to pad up to a length of DIGITS+1. */
4016 if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4017 /* The RHS is sufficient */
4018 /* for residue use the relative sign indication... */
4019 Int shift=reqdigits-rhs->digits; /* left shift needed */
4020 residue=1; /* residue for rounding */
4021 if (diffsign) residue=-residue; /* signs differ */
4022 /* copy, shortening if necessary */
4023 decCopyFit(res, rhs, set, &residue, status);
4024 /* if it was already shorter, then need to pad with zeros */
4025 if (shift>0) {
4026 res->digits=decShiftToMost(res->lsu, res->digits, shift);
4027 res->exponent-=shift; /* adjust the exponent. */
4028 }
4029 /* flip the result sign if unswapped and rhs was negated */
4030 if (!swapped) res->bits^=negate;
4031 decFinish(res, set, &residue, status); /* done */
4032 break;}
4033
4034 /* LHS digits may affect result */
4035 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
4036 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
4037 } /* padding needed */
4038
4039 if (diffsign) mult=-mult; /* signs differ */
4040
4041 /* determine the longer operand */
4042 maxdigits=rhs->digits+padding; /* virtual length of RHS */
4043 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4044
4045 /* Decide on the result buffer to use; if possible place directly */
4046 /* into result. */
4047 acc=res->lsu; /* assume add direct to result */
4048 /* If destructive overlap, or the number is too long, or a carry or */
4049 /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4050 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4051 if ((maxdigits>=reqdigits) /* is, or could be, too large */
4052 || (res==rhs && rhsshift>0)) { /* destructive overlap */
4053 /* buffer needed, choose it; units for maxdigits digits will be */
4054 /* needed, +1 Unit for carry or borrow */
4055 Int need=D2U(maxdigits)+1;
4056 acc=accbuff; /* assume use local buffer */
4057 if (need*sizeof(Unit)>sizeof(accbuff)) {
4058 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4059 allocacc=(Unit *)malloc(need*sizeof(Unit));
4060 if (allocacc==NULL) { /* hopeless -- abandon */
4061 *status|=DEC_Insufficient_storage;
4062 break;}
4063 acc=allocacc;
4064 }
4065 }
4066
4067 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
4068 res->exponent=lhs->exponent; /* .. operands (even if aliased) */
4069
4070 #if DECTRACE
4071 decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4072 decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4073 printf(" :h: %ld %ld\n", rhsshift, mult);
4074 #endif
4075
4076 /* add [A+B*m] or subtract [A+B*(-m)] */
4388f060
A
4077 U_ASSERT(rhs->digits > 0);
4078 U_ASSERT(lhs->digits > 0);
729e4ab9
A
4079 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4080 rhs->lsu, D2U(rhs->digits),
4081 rhsshift, acc, mult)
4082 *DECDPUN; /* [units -> digits] */
4083 if (res->digits<0) { /* borrowed... */
4084 res->digits=-res->digits;
4085 res->bits^=DECNEG; /* flip the sign */
4086 }
4087 #if DECTRACE
4088 decDumpAr('+', acc, D2U(res->digits));
4089 #endif
4090
4091 /* If a buffer was used the result must be copied back, possibly */
4092 /* shortening. (If no buffer was used then the result must have */
4093 /* fit, so can't need rounding and residue must be 0.) */
4094 residue=0; /* clear accumulator */
4095 if (acc!=res->lsu) {
4096 #if DECSUBSET
4097 if (set->extended) { /* round from first significant digit */
4098 #endif
4099 /* remove leading zeros that were added due to rounding up to */
4100 /* integral Units -- before the test for rounding. */
4101 if (res->digits>reqdigits)
4102 res->digits=decGetDigits(acc, D2U(res->digits));
4103 decSetCoeff(res, set, acc, res->digits, &residue, status);
4104 #if DECSUBSET
4105 }
4106 else { /* subset arithmetic rounds from original significant digit */
4107 /* May have an underestimate. This only occurs when both */
4108 /* numbers fit in DECDPUN digits and are padding with a */
4109 /* negative multiple (-10, -100...) and the top digit(s) become */
4110 /* 0. (This only matters when using X3.274 rules where the */
4111 /* leading zero could be included in the rounding.) */
4112 if (res->digits<maxdigits) {
4113 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4114 res->digits=maxdigits;
4115 }
4116 else {
4117 /* remove leading zeros that added due to rounding up to */
4118 /* integral Units (but only those in excess of the original */
4119 /* maxdigits length, unless extended) before test for rounding. */
4120 if (res->digits>reqdigits) {
4121 res->digits=decGetDigits(acc, D2U(res->digits));
4122 if (res->digits<maxdigits) res->digits=maxdigits;
4123 }
4124 }
4125 decSetCoeff(res, set, acc, res->digits, &residue, status);
4126 /* Now apply rounding if needed before removing leading zeros. */
4127 /* This is safe because subnormals are not a possibility */
4128 if (residue!=0) {
4129 decApplyRound(res, set, residue, status);
4130 residue=0; /* did what needed to be done */
4131 }
4132 } /* subset */
4133 #endif
4134 } /* used buffer */
4135
4136 /* strip leading zeros [these were left on in case of subset subtract] */
4137 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4138
4139 /* apply checks and rounding */
4140 decFinish(res, set, &residue, status);
4141
4142 /* "When the sum of two operands with opposite signs is exactly */
4143 /* zero, the sign of that sum shall be '+' in all rounding modes */
4144 /* except round toward -Infinity, in which mode that sign shall be */
4145 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
4146 if (ISZERO(res) && diffsign
4147 #if DECSUBSET
4148 && set->extended
4149 #endif
4150 && (*status&DEC_Inexact)==0) {
4151 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
4152 else res->bits&=~DECNEG; /* sign + */
4153 }
4154 } while(0); /* end protected */
4155
4156 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
4157 #if DECSUBSET
4158 if (allocrhs!=NULL) free(allocrhs); /* .. */
4159 if (alloclhs!=NULL) free(alloclhs); /* .. */
4160 #endif
4161 return res;
4162 } /* decAddOp */
4163
4164/* ------------------------------------------------------------------ */
4165/* decDivideOp -- division operation */
4166/* */
4167/* This routine performs the calculations for all four division */
4168/* operators (divide, divideInteger, remainder, remainderNear). */
4169/* */
4170/* C=A op B */
4171/* */
4172/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
4173/* lhs is A */
4174/* rhs is B */
4175/* set is the context */
4176/* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
4177/* status is the usual accumulator */
4178/* */
4179/* C must have space for set->digits digits. */
4180/* */
4181/* ------------------------------------------------------------------ */
4182/* The underlying algorithm of this routine is the same as in the */
4183/* 1981 S/370 implementation, that is, non-restoring long division */
4184/* with bi-unit (rather than bi-digit) estimation for each unit */
4185/* multiplier. In this pseudocode overview, complications for the */
4186/* Remainder operators and division residues for exact rounding are */
4187/* omitted for clarity. */
4188/* */
4189/* Prepare operands and handle special values */
4190/* Test for x/0 and then 0/x */
4191/* Exp =Exp1 - Exp2 */
4192/* Exp =Exp +len(var1) -len(var2) */
4193/* Sign=Sign1 * Sign2 */
4194/* Pad accumulator (Var1) to double-length with 0's (pad1) */
4195/* Pad Var2 to same length as Var1 */
4196/* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
4197/* have=0 */
4198/* Do until (have=digits+1 OR residue=0) */
4199/* if exp<0 then if integer divide/residue then leave */
4200/* this_unit=0 */
4201/* Do forever */
4202/* compare numbers */
4203/* if <0 then leave inner_loop */
4204/* if =0 then (* quick exit without subtract *) do */
4205/* this_unit=this_unit+1; output this_unit */
4206/* leave outer_loop; end */
4207/* Compare lengths of numbers (mantissae): */
4208/* If same then tops2=msu2pair -- {units 1&2 of var2} */
4209/* else tops2=msu2plus -- {0, unit 1 of var2} */
4210/* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4211/* mult=tops1/tops2 -- Good and safe guess at divisor */
4212/* if mult=0 then mult=1 */
4213/* this_unit=this_unit+mult */
4214/* subtract */
4215/* end inner_loop */
4216/* if have\=0 | this_unit\=0 then do */
4217/* output this_unit */
4218/* have=have+1; end */
4219/* var2=var2/10 */
4220/* exp=exp-1 */
4221/* end outer_loop */
4222/* exp=exp+1 -- set the proper exponent */
4223/* if have=0 then generate answer=0 */
4224/* Return (Result is defined by Var1) */
4225/* */
4226/* ------------------------------------------------------------------ */
4227/* Two working buffers are needed during the division; one (digits+ */
4228/* 1) to accumulate the result, and the other (up to 2*digits+1) for */
4229/* long subtractions. These are acc and var1 respectively. */
4230/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4231/* The static buffers may be larger than might be expected to allow */
4232/* for calls from higher-level funtions (notable exp). */
4233/* ------------------------------------------------------------------ */
4234static decNumber * decDivideOp(decNumber *res,
4235 const decNumber *lhs, const decNumber *rhs,
4236 decContext *set, Flag op, uInt *status) {
4237 #if DECSUBSET
4238 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
4239 decNumber *allocrhs=NULL; /* .., rhs */
4240 #endif
4241 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4242 Unit *acc=accbuff; /* -> accumulator array for result */
4243 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */
4244 Unit *accnext; /* -> where next digit will go */
4245 Int acclength; /* length of acc needed [Units] */
4246 Int accunits; /* count of units accumulated */
4247 Int accdigits; /* count of digits accumulated */
4248
4249 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; /* buffer for var1 */
4250 Unit *var1=varbuff; /* -> var1 array for long subtraction */
4251 Unit *varalloc=NULL; /* -> allocated buffer, iff used */
4252 Unit *msu1; /* -> msu of var1 */
4253
4254 const Unit *var2; /* -> var2 array */
4255 const Unit *msu2; /* -> msu of var2 */
4256 Int msu2plus; /* msu2 plus one [does not vary] */
4257 eInt msu2pair; /* msu2 pair plus one [does not vary] */
4258
4259 Int var1units, var2units; /* actual lengths */
4260 Int var2ulen; /* logical length (units) */
4261 Int var1initpad=0; /* var1 initial padding (digits) */
4262 Int maxdigits; /* longest LHS or required acc length */
4263 Int mult; /* multiplier for subtraction */
4264 Unit thisunit; /* current unit being accumulated */
4265 Int residue; /* for rounding */
4266 Int reqdigits=set->digits; /* requested DIGITS */
4267 Int exponent; /* working exponent */
4268 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
4269 uByte bits; /* working sign */
4270 Unit *target; /* work */
4271 const Unit *source; /* .. */
4272 uInt const *pow; /* .. */
4273 Int shift, cut; /* .. */
4274 #if DECSUBSET
4275 Int dropped; /* work */
4276 #endif
4277
4278 #if DECCHECK
4279 if (decCheckOperands(res, lhs, rhs, set)) return res;
4280 #endif
4281
4282 do { /* protect allocated storage */
4283 #if DECSUBSET
4284 if (!set->extended) {
4285 /* reduce operands and set lostDigits status, as needed */
4286 if (lhs->digits>reqdigits) {
4287 alloclhs=decRoundOperand(lhs, set, status);
4288 if (alloclhs==NULL) break;
4289 lhs=alloclhs;
4290 }
4291 if (rhs->digits>reqdigits) {
4292 allocrhs=decRoundOperand(rhs, set, status);
4293 if (allocrhs==NULL) break;
4294 rhs=allocrhs;
4295 }
4296 }
4297 #endif
4298 /* [following code does not require input rounding] */
4299
4300 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
4301
4302 /* handle infinities and NaNs */
4303 if (SPECIALARGS) { /* a special bit set */
4304 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4305 decNaNs(res, lhs, rhs, set, status);
4306 break;
4307 }
4308 /* one or two infinities */
4309 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
4310 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4311 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4312 *status|=DEC_Invalid_operation;
4313 break;
4314 }
4315 /* [Note that infinity/0 raises no exceptions] */
4316 uprv_decNumberZero(res);
4317 res->bits=bits|DECINF; /* set +/- infinity */
4318 break;
4319 }
4320 else { /* RHS (divisor) is infinite */
4321 residue=0;
4322 if (op&(REMAINDER|REMNEAR)) {
4323 /* result is [finished clone of] lhs */
4324 decCopyFit(res, lhs, set, &residue, status);
4325 }
4326 else { /* a division */
4327 uprv_decNumberZero(res);
4328 res->bits=bits; /* set +/- zero */
4329 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
4330 /* is a 0 with infinitely negative exponent, clamped to minimum */
4331 if (op&DIVIDE) {
4332 res->exponent=set->emin-set->digits+1;
4333 *status|=DEC_Clamped;
4334 }
4335 }
4336 decFinish(res, set, &residue, status);
4337 break;
4338 }
4339 }
4340
4341 /* handle 0 rhs (x/0) */
4342 if (ISZERO(rhs)) { /* x/0 is always exceptional */
4343 if (ISZERO(lhs)) {
4344 uprv_decNumberZero(res); /* [after lhs test] */
4345 *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4346 }
4347 else {
4348 uprv_decNumberZero(res);
4349 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4350 else {
4351 *status|=DEC_Division_by_zero; /* x/0 */
4352 res->bits=bits|DECINF; /* .. is +/- Infinity */
4353 }
4354 }
4355 break;}
4356
4357 /* handle 0 lhs (0/x) */
4358 if (ISZERO(lhs)) { /* 0/x [x!=0] */
4359 #if DECSUBSET
4360 if (!set->extended) uprv_decNumberZero(res);
4361 else {
4362 #endif
4363 if (op&DIVIDE) {
4364 residue=0;
4365 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4366 uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
4367 res->bits=bits; /* sign as computed */
4368 res->exponent=exponent; /* exponent, too */
4369 decFinalize(res, set, &residue, status); /* check exponent */
4370 }
4371 else if (op&DIVIDEINT) {
4372 uprv_decNumberZero(res); /* integer 0 */
4373 res->bits=bits; /* sign as computed */
4374 }
4375 else { /* a remainder */
4376 exponent=rhs->exponent; /* [save in case overwrite] */
4377 uprv_decNumberCopy(res, lhs); /* [zeros always fit] */
4378 if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4379 }
4380 #if DECSUBSET
4381 }
4382 #endif
4383 break;}
4384
4385 /* Precalculate exponent. This starts off adjusted (and hence fits */
4386 /* in 31 bits) and becomes the usual unadjusted exponent as the */
4387 /* division proceeds. The order of evaluation is important, here, */
4388 /* to avoid wrap. */
4389 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4390
4391 /* If the working exponent is -ve, then some quick exits are */
4392 /* possible because the quotient is known to be <1 */
4393 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4394 if (exponent<0 && !(op==DIVIDE)) {
4395 if (op&DIVIDEINT) {
4396 uprv_decNumberZero(res); /* integer part is 0 */
4397 #if DECSUBSET
4398 if (set->extended)
4399 #endif
4400 res->bits=bits; /* set +/- zero */
4401 break;}
4402 /* fastpath remainders so long as the lhs has the smaller */
4403 /* (or equal) exponent */
4404 if (lhs->exponent<=rhs->exponent) {
4405 if (op&REMAINDER || exponent<-1) {
4406 /* It is REMAINDER or safe REMNEAR; result is [finished */
4407 /* clone of] lhs (r = x - 0*y) */
4408 residue=0;
4409 decCopyFit(res, lhs, set, &residue, status);
4410 decFinish(res, set, &residue, status);
4411 break;
4412 }
4413 /* [unsafe REMNEAR drops through] */
4414 }
4415 } /* fastpaths */
4416
4417 /* Long (slow) division is needed; roll up the sleeves... */
4418
4419 /* The accumulator will hold the quotient of the division. */
4420 /* If it needs to be too long for stack storage, then allocate. */
4421 acclength=D2U(reqdigits+DECDPUN); /* in Units */
4422 if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4423 /* printf("malloc dvacc %ld units\n", acclength); */
4424 allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4425 if (allocacc==NULL) { /* hopeless -- abandon */
4426 *status|=DEC_Insufficient_storage;
4427 break;}
4428 acc=allocacc; /* use the allocated space */
4429 }
4430
4431 /* var1 is the padded LHS ready for subtractions. */
4432 /* If it needs to be too long for stack storage, then allocate. */
4433 /* The maximum units needed for var1 (long subtraction) is: */
4434 /* Enough for */
4435 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
4436 /* or (lhs->digits) -- to allow for long lhs */
4437 /* whichever is larger */
4438 /* +1 -- for rounding of slide to right */
4439 /* +1 -- for leading 0s */
4440 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
4441 /* [Note: unused units do not participate in decUnitAddSub data] */
4442 maxdigits=rhs->digits+reqdigits-1;
4443 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4444 var1units=D2U(maxdigits)+2;
4445 /* allocate a guard unit above msu1 for REMAINDERNEAR */
4446 if (!(op&DIVIDE)) var1units++;
4447 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4448 /* printf("malloc dvvar %ld units\n", var1units+1); */
4449 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4450 if (varalloc==NULL) { /* hopeless -- abandon */
4451 *status|=DEC_Insufficient_storage;
4452 break;}
4453 var1=varalloc; /* use the allocated space */
4454 }
4455
4456 /* Extend the lhs and rhs to full long subtraction length. The lhs */
4457 /* is truly extended into the var1 buffer, with 0 padding, so a */
4458 /* subtract in place is always possible. The rhs (var2) has */
4459 /* virtual padding (implemented by decUnitAddSub). */
4460 /* One guard unit was allocated above msu1 for rem=rem+rem in */
4461 /* REMAINDERNEAR. */
4462 msu1=var1+var1units-1; /* msu of var1 */
4463 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4464 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4465 for (; target>=var1; target--) *target=0;
4466
4467 /* rhs (var2) is left-aligned with var1 at the start */
4468 var2ulen=var1units; /* rhs logical length (units) */
4469 var2units=D2U(rhs->digits); /* rhs actual length (units) */
4470 var2=rhs->lsu; /* -> rhs array */
4471 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
4472 /* now set up the variables which will be used for estimating the */
4473 /* multiplication factor. If these variables are not exact, add */
4474 /* 1 to make sure that the multiplier is never overestimated. */
4475 msu2plus=*msu2; /* it's value .. */
4476 if (var2units>1) msu2plus++; /* .. +1 if any more */
4477 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4478 if (var2units>1) { /* .. [else treat 2nd as 0] */
4479 msu2pair+=*(msu2-1); /* .. */
4480 if (var2units>2) msu2pair++; /* .. +1 if any more */
4481 }
4482
4483 /* The calculation is working in units, which may have leading zeros, */
4484 /* but the exponent was calculated on the assumption that they are */
4485 /* both left-aligned. Adjust the exponent to compensate: add the */
4486 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4487 /* [This is actually done by counting the digits and negating, as */
4488 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4489 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4490 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4491
4492 /* Now, if doing an integer divide or remainder, ensure that */
4493 /* the result will be Unit-aligned. To do this, shift the var1 */
4494 /* accumulator towards least if need be. (It's much easier to */
4495 /* do this now than to reassemble the residue afterwards, if */
4496 /* doing a remainder.) Also ensure the exponent is not negative. */
4497 if (!(op&DIVIDE)) {
4498 Unit *u; /* work */
4499 /* save the initial 'false' padding of var1, in digits */
4500 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4501 /* Determine the shift to do. */
4502 if (exponent<0) cut=-exponent;
4503 else cut=DECDPUN-exponent%DECDPUN;
4504 decShiftToLeast(var1, var1units, cut);
4505 exponent+=cut; /* maintain numerical value */
4506 var1initpad-=cut; /* .. and reduce padding */
4507 /* clean any most-significant units which were just emptied */
4508 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4509 } /* align */
4510 else { /* is DIVIDE */
4511 maxexponent=lhs->exponent-rhs->exponent; /* save */
4512 /* optimization: if the first iteration will just produce 0, */
4513 /* preadjust to skip it [valid for DIVIDE only] */
4514 if (*msu1<*msu2) {
4515 var2ulen--; /* shift down */
4516 exponent-=DECDPUN; /* update the exponent */
4517 }
4518 }
4519
4520 /* ---- start the long-division loops ------------------------------ */
4521 accunits=0; /* no units accumulated yet */
4522 accdigits=0; /* .. or digits */
4523 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
4524 for (;;) { /* outer forever loop */
4525 thisunit=0; /* current unit assumed 0 */
4526 /* find the next unit */
4527 for (;;) { /* inner forever loop */
4528 /* strip leading zero units [from either pre-adjust or from */
4529 /* subtract last time around]. Leave at least one unit. */
4530 for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4531
4532 if (var1units<var2ulen) break; /* var1 too low for subtract */
4533 if (var1units==var2ulen) { /* unit-by-unit compare needed */
4534 /* compare the two numbers, from msu */
4535 const Unit *pv1, *pv2;
4536 Unit v2; /* units to compare */
4537 pv2=msu2; /* -> msu */
4538 for (pv1=msu1; ; pv1--, pv2--) {
4539 /* v1=*pv1 -- always OK */
4540 v2=0; /* assume in padding */
4541 if (pv2>=var2) v2=*pv2; /* in range */
4542 if (*pv1!=v2) break; /* no longer the same */
4543 if (pv1==var1) break; /* done; leave pv1 as is */
4544 }
4545 /* here when all inspected or a difference seen */
4546 if (*pv1<v2) break; /* var1 too low to subtract */
4547 if (*pv1==v2) { /* var1 == var2 */
4548 /* reach here if var1 and var2 are identical; subtraction */
4549 /* would increase digit by one, and the residue will be 0 so */
4550 /* the calculation is done; leave the loop with residue=0. */
4551 thisunit++; /* as though subtracted */
4552 *var1=0; /* set var1 to 0 */
4553 var1units=1; /* .. */
4554 break; /* from inner */
4555 } /* var1 == var2 */
4556 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
4557 /* Estimate the multiplier (there's always a msu1-1)... */
4558 /* Bring in two units of var2 to provide a good estimate. */
4559 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4560 } /* lengths the same */
4561 else { /* var1units > var2ulen, so subtraction is safe */
4562 /* The var2 msu is one unit towards the lsu of the var1 msu, */
4563 /* so only one unit for var2 can be used. */
4564 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4565 }
4566 if (mult==0) mult=1; /* must always be at least 1 */
4567 /* subtraction needed; var1 is > var2 */
4568 thisunit=(Unit)(thisunit+mult); /* accumulate */
4569 /* subtract var1-var2, into var1; only the overlap needs */
4570 /* processing, as this is an in-place calculation */
4571 shift=var2ulen-var2units;
4572 #if DECTRACE
4573 decDumpAr('1', &var1[shift], var1units-shift);
4574 decDumpAr('2', var2, var2units);
4575 printf("m=%ld\n", -mult);
4576 #endif
4577 decUnitAddSub(&var1[shift], var1units-shift,
4578 var2, var2units, 0,
4579 &var1[shift], -mult);
4580 #if DECTRACE
4581 decDumpAr('#', &var1[shift], var1units-shift);
4582 #endif
4583 /* var1 now probably has leading zeros; these are removed at the */
4584 /* top of the inner loop. */
4585 } /* inner loop */
4586
4587 /* The next unit has been calculated in full; unless it's a */
4588 /* leading zero, add to acc */
4589 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
4590 *accnext=thisunit; /* store in accumulator */
4591 /* account exactly for the new digits */
4592 if (accunits==0) {
4593 accdigits++; /* at least one */
4594 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4595 }
4596 else accdigits+=DECDPUN;
4597 accunits++; /* update count */
4598 accnext--; /* ready for next */
4599 if (accdigits>reqdigits) break; /* have enough digits */
4600 }
4601
4602 /* if the residue is zero, the operation is done (unless divide */
4603 /* or divideInteger and still not enough digits yet) */
4604 if (*var1==0 && var1units==1) { /* residue is 0 */
4605 if (op&(REMAINDER|REMNEAR)) break;
4606 if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4607 /* [drop through if divideInteger] */
4608 }
4609 /* also done enough if calculating remainder or integer */
4610 /* divide and just did the last ('units') unit */
4611 if (exponent==0 && !(op&DIVIDE)) break;
4612
4613 /* to get here, var1 is less than var2, so divide var2 by the per- */
4614 /* Unit power of ten and go for the next digit */
4615 var2ulen--; /* shift down */
4616 exponent-=DECDPUN; /* update the exponent */
4617 } /* outer loop */
4618
4619 /* ---- division is complete --------------------------------------- */
4620 /* here: acc has at least reqdigits+1 of good results (or fewer */
4621 /* if early stop), starting at accnext+1 (its lsu) */
4622 /* var1 has any residue at the stopping point */
4623 /* accunits is the number of digits collected in acc */
4624 if (accunits==0) { /* acc is 0 */
4625 accunits=1; /* show have a unit .. */
4626 accdigits=1; /* .. */
4627 *accnext=0; /* .. whose value is 0 */
4628 }
4629 else accnext++; /* back to last placed */
4630 /* accnext now -> lowest unit of result */
4631
4632 residue=0; /* assume no residue */
4633 if (op&DIVIDE) {
4634 /* record the presence of any residue, for rounding */
4635 if (*var1!=0 || var1units>1) residue=1;
4636 else { /* no residue */
4637 /* Had an exact division; clean up spurious trailing 0s. */
4638 /* There will be at most DECDPUN-1, from the final multiply, */
4639 /* and then only if the result is non-0 (and even) and the */
4640 /* exponent is 'loose'. */
4641 #if DECDPUN>1
4642 Unit lsu=*accnext;
4643 if (!(lsu&0x01) && (lsu!=0)) {
4644 /* count the trailing zeros */
4645 Int drop=0;
4646 for (;; drop++) { /* [will terminate because lsu!=0] */
4647 if (exponent>=maxexponent) break; /* don't chop real 0s */
4648 #if DECDPUN<=4
4649 if ((lsu-QUOT10(lsu, drop+1)
4650 *powers[drop+1])!=0) break; /* found non-0 digit */
4651 #else
4652 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
4653 #endif
4654 exponent++;
4655 }
4656 if (drop>0) {
4657 accunits=decShiftToLeast(accnext, accunits, drop);
4658 accdigits=decGetDigits(accnext, accunits);
4659 accunits=D2U(accdigits);
4660 /* [exponent was adjusted in the loop] */
4661 }
4662 } /* neither odd nor 0 */
4663 #endif
4664 } /* exact divide */
4665 } /* divide */
4666 else /* op!=DIVIDE */ {
4667 /* check for coefficient overflow */
4668 if (accdigits+exponent>reqdigits) {
4669 *status|=DEC_Division_impossible;
4670 break;
4671 }
4672 if (op & (REMAINDER|REMNEAR)) {
4673 /* [Here, the exponent will be 0, because var1 was adjusted */
4674 /* appropriately.] */
4675 Int postshift; /* work */
4676 Flag wasodd=0; /* integer was odd */
4677 Unit *quotlsu; /* for save */
4678 Int quotdigits; /* .. */
4679
4680 bits=lhs->bits; /* remainder sign is always as lhs */
4681
4682 /* Fastpath when residue is truly 0 is worthwhile [and */
4683 /* simplifies the code below] */
4684 if (*var1==0 && var1units==1) { /* residue is 0 */
4685 Int exp=lhs->exponent; /* save min(exponents) */
4686 if (rhs->exponent<exp) exp=rhs->exponent;
4687 uprv_decNumberZero(res); /* 0 coefficient */
4688 #if DECSUBSET
4689 if (set->extended)
4690 #endif
4691 res->exponent=exp; /* .. with proper exponent */
4692 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4693 decFinish(res, set, &residue, status); /* might clamp */
4694 break;
4695 }
4696 /* note if the quotient was odd */
4697 if (*accnext & 0x01) wasodd=1; /* acc is odd */
4698 quotlsu=accnext; /* save in case need to reinspect */
4699 quotdigits=accdigits; /* .. */
4700
4701 /* treat the residue, in var1, as the value to return, via acc */
4702 /* calculate the unused zero digits. This is the smaller of: */
4703 /* var1 initial padding (saved above) */
4704 /* var2 residual padding, which happens to be given by: */
4705 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4706 /* [the 'exponent' term accounts for the shifts during divide] */
4707 if (var1initpad<postshift) postshift=var1initpad;
4708
4709 /* shift var1 the requested amount, and adjust its digits */
4710 var1units=decShiftToLeast(var1, var1units, postshift);
4711 accnext=var1;
4712 accdigits=decGetDigits(var1, var1units);
4713 accunits=D2U(accdigits);
4714
4715 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
4716 if (rhs->exponent<exponent) exponent=rhs->exponent;
4717
4718 /* Now correct the result if doing remainderNear; if it */
4719 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4720 /* the integer was odd then the result should be rem-rhs. */
4721 if (op&REMNEAR) {
4722 Int compare, tarunits; /* work */
4723 Unit *up; /* .. */
4724 /* calculate remainder*2 into the var1 buffer (which has */
4725 /* 'headroom' of an extra unit and hence enough space) */
4726 /* [a dedicated 'double' loop would be faster, here] */
4727 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4728 0, accnext, 1);
4729 /* decDumpAr('r', accnext, tarunits); */
4730
4731 /* Here, accnext (var1) holds tarunits Units with twice the */
4732 /* remainder's coefficient, which must now be compared to the */
4733 /* RHS. The remainder's exponent may be smaller than the RHS's. */
4734 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4735 rhs->exponent-exponent);
4736 if (compare==BADINT) { /* deep trouble */
4737 *status|=DEC_Insufficient_storage;
4738 break;}
4739
4740 /* now restore the remainder by dividing by two; the lsu */
4741 /* is known to be even. */
4742 for (up=accnext; up<accnext+tarunits; up++) {
4743 Int half; /* half to add to lower unit */
4744 half=*up & 0x01;
4745 *up/=2; /* [shift] */
4746 if (!half) continue;
4747 *(up-1)+=(DECDPUNMAX+1)/2;
4748 }
4749 /* [accunits still describes the original remainder length] */
4750
4751 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4752 Int exp, expunits, exprem; /* work */
4753 /* This is effectively causing round-up of the quotient, */
4754 /* so if it was the rare case where it was full and all */
4755 /* nines, it would overflow and hence division-impossible */
4756 /* should be raised */
4757 Flag allnines=0; /* 1 if quotient all nines */
4758 if (quotdigits==reqdigits) { /* could be borderline */
4759 for (up=quotlsu; ; up++) {
4760 if (quotdigits>DECDPUN) {
4761 if (*up!=DECDPUNMAX) break;/* non-nines */
4762 }
4763 else { /* this is the last Unit */
4764 if (*up==powers[quotdigits]-1) allnines=1;
4765 break;
4766 }
4767 quotdigits-=DECDPUN; /* checked those digits */
4768 } /* up */
4769 } /* borderline check */
4770 if (allnines) {
4771 *status|=DEC_Division_impossible;
4772 break;}
4773
4774 /* rem-rhs is needed; the sign will invert. Again, var1 */
4775 /* can safely be used for the working Units array. */
4776 exp=rhs->exponent-exponent; /* RHS padding needed */
4777 /* Calculate units and remainder from exponent. */
4778 expunits=exp/DECDPUN;
4779 exprem=exp%DECDPUN;
4780 /* subtract [A+B*(-m)]; the result will always be negative */
4781 accunits=-decUnitAddSub(accnext, accunits,
4782 rhs->lsu, D2U(rhs->digits),
4783 expunits, accnext, -(Int)powers[exprem]);
4784 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4785 accunits=D2U(accdigits); /* and recalculate the units for copy */
4786 /* [exponent is as for original remainder] */
4787 bits^=DECNEG; /* flip the sign */
4788 }
4789 } /* REMNEAR */
4790 } /* REMAINDER or REMNEAR */
4791 } /* not DIVIDE */
4792
4793 /* Set exponent and bits */
4794 res->exponent=exponent;
4795 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4796
4797 /* Now the coefficient. */
4798 decSetCoeff(res, set, accnext, accdigits, &residue, status);
4799
4800 decFinish(res, set, &residue, status); /* final cleanup */
4801
4802 #if DECSUBSET
4803 /* If a divide then strip trailing zeros if subset [after round] */
4804 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4805 #endif
4806 } while(0); /* end protected */
4807
4808 if (varalloc!=NULL) free(varalloc); /* drop any storage used */
4809 if (allocacc!=NULL) free(allocacc); /* .. */
4810 #if DECSUBSET
4811 if (allocrhs!=NULL) free(allocrhs); /* .. */
4812 if (alloclhs!=NULL) free(alloclhs); /* .. */
4813 #endif
4814 return res;
4815 } /* decDivideOp */
4816
4817/* ------------------------------------------------------------------ */
4818/* decMultiplyOp -- multiplication operation */
4819/* */
4820/* This routine performs the multiplication C=A x B. */
4821/* */
4822/* res is C, the result. C may be A and/or B (e.g., X=X*X) */
4823/* lhs is A */
4824/* rhs is B */
4825/* set is the context */
4826/* status is the usual accumulator */
4827/* */
4828/* C must have space for set->digits digits. */
4829/* */
4830/* ------------------------------------------------------------------ */
4831/* 'Classic' multiplication is used rather than Karatsuba, as the */
4832/* latter would give only a minor improvement for the short numbers */
4833/* expected to be handled most (and uses much more memory). */
4834/* */
4835/* There are two major paths here: the general-purpose ('old code') */
4836/* path which handles all DECDPUN values, and a fastpath version */
4837/* which is used if 64-bit ints are available, DECDPUN<=4, and more */
4838/* than two calls to decUnitAddSub would be made. */
4839/* */
4840/* The fastpath version lumps units together into 8-digit or 9-digit */
4841/* chunks, and also uses a lazy carry strategy to minimise expensive */
4842/* 64-bit divisions. The chunks are then broken apart again into */
4843/* units for continuing processing. Despite this overhead, the */
4844/* fastpath can speed up some 16-digit operations by 10x (and much */
4845/* more for higher-precision calculations). */
4846/* */
4847/* A buffer always has to be used for the accumulator; in the */
4848/* fastpath, buffers are also always needed for the chunked copies of */
4849/* of the operand coefficients. */
4850/* Static buffers are larger than needed just for multiply, to allow */
4851/* for calls from other operations (notably exp). */
4852/* ------------------------------------------------------------------ */
4853#define FASTMUL (DECUSE64 && DECDPUN<5)
4854static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4855 const decNumber *rhs, decContext *set,
4856 uInt *status) {
4857 Int accunits; /* Units of accumulator in use */
4858 Int exponent; /* work */
4859 Int residue=0; /* rounding residue */
4860 uByte bits; /* result sign */
4861 Unit *acc; /* -> accumulator Unit array */
4862 Int needbytes; /* size calculator */
4863 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */
4864 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4865 /* *4 for calls from other operations) */
4866 const Unit *mer, *mermsup; /* work */
4867 Int madlength; /* Units in multiplicand */
4868 Int shift; /* Units to shift multiplicand by */
4869
4870 #if FASTMUL
4871 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4872 /* (DECDPUN is 2 or 4) then work in base 10**8 */
4873 #if DECDPUN & 1 /* odd */
4874 #define FASTBASE 1000000000 /* base */
4875 #define FASTDIGS 9 /* digits in base */
4876 #define FASTLAZY 18 /* carry resolution point [1->18] */
4877 #else
4878 #define FASTBASE 100000000
4879 #define FASTDIGS 8
4880 #define FASTLAZY 1844 /* carry resolution point [1->1844] */
4881 #endif
4882 /* three buffers are used, two for chunked copies of the operands */
4883 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4884 /* lazy carry evaluation */
4885 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4886 uInt *zlhi=zlhibuff; /* -> lhs array */
4887 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */
4888 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4889 uInt *zrhi=zrhibuff; /* -> rhs array */
4890 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */
4891 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4892 /* [allocacc is shared for both paths, as only one will run] */
4893 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
4894 #if DECDPUN==1
4895 Int zoff; /* accumulator offset */
4896 #endif
4897 uInt *lip, *rip; /* item pointers */
4898 uInt *lmsi, *rmsi; /* most significant items */
4899 Int ilhs, irhs, iacc; /* item counts in the arrays */
4900 Int lazy; /* lazy carry counter */
4901 uLong lcarry; /* uLong carry */
4902 uInt carry; /* carry (NB not uLong) */
4903 Int count; /* work */
4904 const Unit *cup; /* .. */
4905 Unit *up; /* .. */
4906 uLong *lp; /* .. */
4907 Int p; /* .. */
4908 #endif
4909
4910 #if DECSUBSET
4911 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */
4912 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */
4913 #endif
4914
4915 #if DECCHECK
4916 if (decCheckOperands(res, lhs, rhs, set)) return res;
4917 #endif
4918
4919 /* precalculate result sign */
4920 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4921
4922 /* handle infinities and NaNs */
4923 if (SPECIALARGS) { /* a special bit set */
4924 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4925 decNaNs(res, lhs, rhs, set, status);
4926 return res;}
4927 /* one or two infinities; Infinity * 0 is invalid */
4928 if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4929 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4930 *status|=DEC_Invalid_operation;
4931 return res;}
4932 uprv_decNumberZero(res);
4933 res->bits=bits|DECINF; /* infinity */
4934 return res;}
4935
4936 /* For best speed, as in DMSRCN [the original Rexx numerics */
4937 /* module], use the shorter number as the multiplier (rhs) and */
4938 /* the longer as the multiplicand (lhs) to minimise the number of */
4939 /* adds (partial products) */
4940 if (lhs->digits<rhs->digits) { /* swap... */
4941 const decNumber *hold=lhs;
4942 lhs=rhs;
4943 rhs=hold;
4944 }
4945
4946 do { /* protect allocated storage */
4947 #if DECSUBSET
4948 if (!set->extended) {
4949 /* reduce operands and set lostDigits status, as needed */
4950 if (lhs->digits>set->digits) {
4951 alloclhs=decRoundOperand(lhs, set, status);
4952 if (alloclhs==NULL) break;
4953 lhs=alloclhs;
4954 }
4955 if (rhs->digits>set->digits) {
4956 allocrhs=decRoundOperand(rhs, set, status);
4957 if (allocrhs==NULL) break;
4958 rhs=allocrhs;
4959 }
4960 }
4961 #endif
4962 /* [following code does not require input rounding] */
4963
4964 #if FASTMUL /* fastpath can be used */
4965 /* use the fast path if there are enough digits in the shorter */
4966 /* operand to make the setup and takedown worthwhile */
4967 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
4968 if (rhs->digits>NEEDTWO) { /* use fastpath... */
4969 /* calculate the number of elements in each array */
4970 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4971 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4972 iacc=ilhs+irhs;
4973
4974 /* allocate buffers if required, as usual */
4975 needbytes=ilhs*sizeof(uInt);
4976 if (needbytes>(Int)sizeof(zlhibuff)) {
4977 alloclhi=(uInt *)malloc(needbytes);
4978 zlhi=alloclhi;}
4979 needbytes=irhs*sizeof(uInt);
4980 if (needbytes>(Int)sizeof(zrhibuff)) {
4981 allocrhi=(uInt *)malloc(needbytes);
4982 zrhi=allocrhi;}
4983
4984 /* Allocating the accumulator space needs a special case when */
4985 /* DECDPUN=1 because when converting the accumulator to Units */
4986 /* after the multiplication each 8-byte item becomes 9 1-byte */
4987 /* units. Therefore iacc extra bytes are needed at the front */
4988 /* (rounded up to a multiple of 8 bytes), and the uLong */
4989 /* accumulator starts offset the appropriate number of units */
4990 /* to the right to avoid overwrite during the unchunking. */
4388f060
A
4991
4992 /* Make sure no signed int overflow below. This is always true */
4993 /* if the given numbers have less digits than DEC_MAX_DIGITS. */
4994 U_ASSERT(iacc <= INT32_MAX/sizeof(uLong));
729e4ab9
A
4995 needbytes=iacc*sizeof(uLong);
4996 #if DECDPUN==1
4997 zoff=(iacc+7)/8; /* items to offset by */
4998 needbytes+=zoff*8;
4999 #endif
5000 if (needbytes>(Int)sizeof(zaccbuff)) {
5001 allocacc=(uLong *)malloc(needbytes);
5002 zacc=(uLong *)allocacc;}
5003 if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
5004 *status|=DEC_Insufficient_storage;
5005 break;}
5006
5007 acc=(Unit *)zacc; /* -> target Unit array */
5008 #if DECDPUN==1
5009 zacc+=zoff; /* start uLong accumulator to right */
5010 #endif
5011
5012 /* assemble the chunked copies of the left and right sides */
5013 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5014 for (p=0, *lip=0; p<FASTDIGS && count>0;
5015 p+=DECDPUN, cup++, count-=DECDPUN)
5016 *lip+=*cup*powers[p];
5017 lmsi=lip-1; /* save -> msi */
5018 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5019 for (p=0, *rip=0; p<FASTDIGS && count>0;
5020 p+=DECDPUN, cup++, count-=DECDPUN)
5021 *rip+=*cup*powers[p];
5022 rmsi=rip-1; /* save -> msi */
5023
5024 /* zero the accumulator */
5025 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5026
5027 /* Start the multiplication */
5028 /* Resolving carries can dominate the cost of accumulating the */
5029 /* partial products, so this is only done when necessary. */
5030 /* Each uLong item in the accumulator can hold values up to */
5031 /* 2**64-1, and each partial product can be as large as */
5032 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
5033 /* itself 18.4 times in a uLong without overflowing, so during */
5034 /* the main calculation resolution is carried out every 18th */
5035 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
5036 /* partial products can be added to themselves 1844.6 times in */
5037 /* a uLong without overflowing, so intermediate carry */
5038 /* resolution occurs only every 14752 digits. Hence for common */
5039 /* short numbers usually only the one final carry resolution */
5040 /* occurs. */
5041 /* (The count is set via FASTLAZY to simplify experiments to */
5042 /* measure the value of this approach: a 35% improvement on a */
5043 /* [34x34] multiply.) */
5044 lazy=FASTLAZY; /* carry delay count */
5045 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
5046 lp=zacc+(rip-zrhi); /* where to add the lhs */
5047 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5048 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
5049 } /* lip loop */
5050 lazy--;
5051 if (lazy>0 && rip!=rmsi) continue;
5052 lazy=FASTLAZY; /* reset delay count */
5053 /* spin up the accumulator resolving overflows */
5054 for (lp=zacc; lp<zacc+iacc; lp++) {
5055 if (*lp<FASTBASE) continue; /* it fits */
5056 lcarry=*lp/FASTBASE; /* top part [slow divide] */
5057 /* lcarry can exceed 2**32-1, so check again; this check */
5058 /* and occasional extra divide (slow) is well worth it, as */
5059 /* it allows FASTLAZY to be increased to 18 rather than 4 */
5060 /* in the FASTDIGS=9 case */
5061 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
5062 else { /* two-place carry [fairly rare] */
5063 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
5064 *(lp+2)+=carry2; /* add to item+2 */
5065 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5066 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5067 }
5068 *(lp+1)+=carry; /* add to item above [inline] */
5069 *lp-=((uLong)FASTBASE*carry); /* [inline] */
5070 } /* carry resolution */
5071 } /* rip loop */
5072
5073 /* The multiplication is complete; time to convert back into */
5074 /* units. This can be done in-place in the accumulator and in */
5075 /* 32-bit operations, because carries were resolved after the */
5076 /* final add. This needs N-1 divides and multiplies for */
5077 /* each item in the accumulator (which will become up to N */
5078 /* units, where 2<=N<=9). */
5079 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5080 uInt item=(uInt)*lp; /* decapitate to uInt */
5081 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5082 uInt part=item/(DECDPUNMAX+1);
5083 *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5084 item=part;
5085 } /* p */
5086 *up=(Unit)item; up++; /* [final needs no division] */
5087 } /* lp */
5088 accunits=up-acc; /* count of units */
5089 }
5090 else { /* here to use units directly, without chunking ['old code'] */
5091 #endif
5092
5093 /* if accumulator will be too long for local storage, then allocate */
5094 acc=accbuff; /* -> assume buffer for accumulator */
5095 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5096 if (needbytes>(Int)sizeof(accbuff)) {
5097 allocacc=(Unit *)malloc(needbytes);
5098 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5099 acc=(Unit *)allocacc; /* use the allocated space */
5100 }
5101
5102 /* Now the main long multiplication loop */
5103 /* Unlike the equivalent in the IBM Java implementation, there */
5104 /* is no advantage in calculating from msu to lsu. So, do it */
5105 /* by the book, as it were. */
5106 /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5107 accunits=1; /* accumulator starts at '0' */
5108 *acc=0; /* .. (lsu=0) */
5109 shift=0; /* no multiplicand shift at first */
5110 madlength=D2U(lhs->digits); /* this won't change */
5111 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5112
5113 for (mer=rhs->lsu; mer<mermsup; mer++) {
5114 /* Here, *mer is the next Unit in the multiplier to use */
5115 /* If non-zero [optimization] add it... */
5116 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5117 lhs->lsu, madlength, 0,
5118 &acc[shift], *mer)
5119 + shift;
5120 else { /* extend acc with a 0; it will be used shortly */
5121 *(acc+accunits)=0; /* [this avoids length of <=0 later] */
5122 accunits++;
5123 }
5124 /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5125 shift++; /* add this for 'logical length' */
5126 } /* n */
5127 #if FASTMUL
5128 } /* unchunked units */
5129 #endif
5130 /* common end-path */
5131 #if DECTRACE
5132 decDumpAr('*', acc, accunits); /* Show exact result */
5133 #endif
5134
5135 /* acc now contains the exact result of the multiplication, */
5136 /* possibly with a leading zero unit; build the decNumber from */
5137 /* it, noting if any residue */
5138 res->bits=bits; /* set sign */
5139 res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5140
5141 /* There can be a 31-bit wrap in calculating the exponent. */
5142 /* This can only happen if both input exponents are negative and */
5143 /* both their magnitudes are large. If there was a wrap, set a */
5144 /* safe very negative exponent, from which decFinalize() will */
5145 /* raise a hard underflow shortly. */
5146 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
5147 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5148 exponent=-2*DECNUMMAXE; /* force underflow */
5149 res->exponent=exponent; /* OK to overwrite now */
5150
5151
5152 /* Set the coefficient. If any rounding, residue records */
5153 decSetCoeff(res, set, acc, res->digits, &residue, status);
5154 decFinish(res, set, &residue, status); /* final cleanup */
5155 } while(0); /* end protected */
5156
5157 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
5158 #if DECSUBSET
5159 if (allocrhs!=NULL) free(allocrhs); /* .. */
5160 if (alloclhs!=NULL) free(alloclhs); /* .. */
5161 #endif
5162 #if FASTMUL
5163 if (allocrhi!=NULL) free(allocrhi); /* .. */
5164 if (alloclhi!=NULL) free(alloclhi); /* .. */
5165 #endif
5166 return res;
5167 } /* decMultiplyOp */
5168
5169/* ------------------------------------------------------------------ */
5170/* decExpOp -- effect exponentiation */
5171/* */
5172/* This computes C = exp(A) */
5173/* */
5174/* res is C, the result. C may be A */
5175/* rhs is A */
5176/* set is the context; note that rounding mode has no effect */
5177/* */
5178/* C must have space for set->digits digits. status is updated but */
5179/* not set. */
5180/* */
5181/* Restrictions: */
5182/* */
5183/* digits, emax, and -emin in the context must be less than */
5184/* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
5185/* bounds or a zero. This is an internal routine, so these */
5186/* restrictions are contractual and not enforced. */
5187/* */
5188/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5189/* almost always be correctly rounded, but may be up to 1 ulp in */
5190/* error in rare cases. */
5191/* */
5192/* Finite results will always be full precision and Inexact, except */
5193/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
5194/* ------------------------------------------------------------------ */
5195/* This approach used here is similar to the algorithm described in */
5196/* */
5197/* Variable Precision Exponential Function, T. E. Hull and */
5198/* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5199/* pp79-91, ACM, June 1986. */
5200/* */
5201/* with the main difference being that the iterations in the series */
5202/* evaluation are terminated dynamically (which does not require the */
5203/* extra variable-precision variables which are expensive in this */
5204/* context). */
5205/* */
5206/* The error analysis in Hull & Abrham's paper applies except for the */
5207/* round-off error accumulation during the series evaluation. This */
5208/* code does not precalculate the number of iterations and so cannot */
5209/* use Horner's scheme. Instead, the accumulation is done at double- */
5210/* precision, which ensures that the additions of the terms are exact */
5211/* and do not accumulate round-off (and any round-off errors in the */
5212/* terms themselves move 'to the right' faster than they can */
5213/* accumulate). This code also extends the calculation by allowing, */
5214/* in the spirit of other decNumber operators, the input to be more */
5215/* precise than the result (the precision used is based on the more */
5216/* precise of the input or requested result). */
5217/* */
5218/* Implementation notes: */
5219/* */
5220/* 1. This is separated out as decExpOp so it can be called from */
5221/* other Mathematical functions (notably Ln) with a wider range */
5222/* than normal. In particular, it can handle the slightly wider */
5223/* (double) range needed by Ln (which has to be able to calculate */
5224/* exp(-x) where x can be the tiniest number (Ntiny). */
5225/* */
5226/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
5227/* iterations by appoximately a third with additional (although */
5228/* diminishing) returns as the range is reduced to even smaller */
5229/* fractions. However, h (the power of 10 used to correct the */
5230/* result at the end, see below) must be kept <=8 as otherwise */
5231/* the final result cannot be computed. Hence the leverage is a */
5232/* sliding value (8-h), where potentially the range is reduced */
5233/* more for smaller values. */
5234/* */
5235/* The leverage that can be applied in this way is severely */
5236/* limited by the cost of the raise-to-the power at the end, */
5237/* which dominates when the number of iterations is small (less */
5238/* than ten) or when rhs is short. As an example, the adjustment */
5239/* x**10,000,000 needs 31 multiplications, all but one full-width. */
5240/* */
5241/* 3. The restrictions (especially precision) could be raised with */
5242/* care, but the full decNumber range seems very hard within the */
5243/* 32-bit limits. */
5244/* */
5245/* 4. The working precisions for the static buffers are twice the */
5246/* obvious size to allow for calls from decNumberPower. */
5247/* ------------------------------------------------------------------ */
5248decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5249 decContext *set, uInt *status) {
5250 uInt ignore=0; /* working status */
5251 Int h; /* adjusted exponent for 0.xxxx */
5252 Int p; /* working precision */
5253 Int residue; /* rounding residue */
5254 uInt needbytes; /* for space calculations */
5255 const decNumber *x=rhs; /* (may point to safe copy later) */
5256 decContext aset, tset, dset; /* working contexts */
5257 Int comp; /* work */
5258
5259 /* the argument is often copied to normalize it, so (unusually) it */
5260 /* is treated like other buffers, using DECBUFFER, +1 in case */
5261 /* DECBUFFER is 0 */
5262 decNumber bufr[D2N(DECBUFFER*2+1)];
5263 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */
5264
5265 /* the working precision will be no more than set->digits+8+1 */
5266 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5267 /* is 0 (and twice that for the accumulator) */
5268
5269 /* buffer for t, term (working precision plus) */
5270 decNumber buft[D2N(DECBUFFER*2+9+1)];
5271 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */
5272 decNumber *t=buft; /* term */
5273 /* buffer for a, accumulator (working precision * 2), at least 9 */
5274 decNumber bufa[D2N(DECBUFFER*4+18+1)];
5275 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5276 decNumber *a=bufa; /* accumulator */
5277 /* decNumber for the divisor term; this needs at most 9 digits */
5278 /* and so can be fixed size [16 so can use standard context] */
5279 decNumber bufd[D2N(16)];
5280 decNumber *d=bufd; /* divisor */
5281 decNumber numone; /* constant 1 */
5282
5283 #if DECCHECK
5284 Int iterations=0; /* for later sanity check */
5285 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5286 #endif
5287
5288 do { /* protect allocated storage */
5289 if (SPECIALARG) { /* handle infinities and NaNs */
5290 if (decNumberIsInfinite(rhs)) { /* an infinity */
5291 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
5292 uprv_decNumberZero(res);
5293 else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
5294 }
5295 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5296 break;}
5297
5298 if (ISZERO(rhs)) { /* zeros -> exact 1 */
5299 uprv_decNumberZero(res); /* make clean 1 */
5300 *res->lsu=1; /* .. */
5301 break;} /* [no status to set] */
5302
5303 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5304 /* positive and negative tiny cases which will result in inexact */
5305 /* 1. This also allows the later add-accumulate to always be */
5306 /* exact (because its length will never be more than twice the */
5307 /* working precision). */
5308 /* The comparator (tiny) needs just one digit, so use the */
5309 /* decNumber d for it (reused as the divisor, etc., below); its */
5310 /* exponent is such that if x is positive it will have */
5311 /* set->digits-1 zeros between the decimal point and the digit, */
5312 /* which is 4, and if x is negative one more zero there as the */
5313 /* more precise result will be of the form 0.9999999 rather than */
5314 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
5315 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
5316 /* this then the result will be 1.000000 */
5317 uprv_decNumberZero(d); /* clean */
5318 *d->lsu=4; /* set 4 .. */
5319 d->exponent=-set->digits; /* * 10**(-d) */
5320 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
5321 comp=decCompare(d, rhs, 1); /* signless compare */
5322 if (comp==BADINT) {
5323 *status|=DEC_Insufficient_storage;
5324 break;}
5325 if (comp>=0) { /* rhs < d */
5326 Int shift=set->digits-1;
5327 uprv_decNumberZero(res); /* set 1 */
5328 *res->lsu=1; /* .. */
5329 res->digits=decShiftToMost(res->lsu, 1, shift);
5330 res->exponent=-shift; /* make 1.0000... */
5331 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
5332 break;} /* tiny */
5333
5334 /* set up the context to be used for calculating a, as this is */
5335 /* used on both paths below */
5336 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5337 /* accumulator bounds are as requested (could underflow) */
5338 aset.emax=set->emax; /* usual bounds */
5339 aset.emin=set->emin; /* .. */
5340 aset.clamp=0; /* and no concrete format */
5341
5342 /* calculate the adjusted (Hull & Abrham) exponent (where the */
5343 /* decimal point is just to the left of the coefficient msd) */
5344 h=rhs->exponent+rhs->digits;
5345 /* if h>8 then 10**h cannot be calculated safely; however, when */
5346 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5347 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5348 /* overflow (or underflow to 0) is guaranteed -- so this case can */
5349 /* be handled by simply forcing the appropriate excess */
5350 if (h>8) { /* overflow/underflow */
5351 /* set up here so Power call below will over or underflow to */
5352 /* zero; set accumulator to either 2 or 0.02 */
5353 /* [stack buffer for a is always big enough for this] */
5354 uprv_decNumberZero(a);
5355 *a->lsu=2; /* not 1 but < exp(1) */
5356 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5357 h=8; /* clamp so 10**h computable */
5358 p=9; /* set a working precision */
5359 }
5360 else { /* h<=8 */
5361 Int maxlever=(rhs->digits>8?1:0);
5362 /* [could/should increase this for precisions >40 or so, too] */
5363
5364 /* if h is 8, cannot normalize to a lower upper limit because */
5365 /* the final result will not be computable (see notes above), */
5366 /* but leverage can be applied whenever h is less than 8. */
5367 /* Apply as much as possible, up to a MAXLEVER digits, which */
5368 /* sets the tradeoff against the cost of the later a**(10**h). */
5369 /* As h is increased, the working precision below also */
5370 /* increases to compensate for the "constant digits at the */
5371 /* front" effect. */
5372 Int lever=MINI(8-h, maxlever); /* leverage attainable */
5373 Int use=-rhs->digits-lever; /* exponent to use for RHS */
5374 h+=lever; /* apply leverage selected */
5375 if (h<0) { /* clamp */
5376 use+=h; /* [may end up subnormal] */
5377 h=0;
5378 }
5379 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5380 if (rhs->exponent!=use) {
5381 decNumber *newrhs=bufr; /* assume will fit on stack */
5382 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5383 if (needbytes>sizeof(bufr)) { /* need malloc space */
5384 allocrhs=(decNumber *)malloc(needbytes);
5385 if (allocrhs==NULL) { /* hopeless -- abandon */
5386 *status|=DEC_Insufficient_storage;
5387 break;}
5388 newrhs=allocrhs; /* use the allocated space */
5389 }
5390 uprv_decNumberCopy(newrhs, rhs); /* copy to safe space */
5391 newrhs->exponent=use; /* normalize; now <1 */
5392 x=newrhs; /* ready for use */
5393 /* decNumberShow(x); */
5394 }
5395
5396 /* Now use the usual power series to evaluate exp(x). The */
5397 /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5398 /* third term by setting the term variable t=x, the accumulator */
5399 /* a=1, and the divisor d=2. */
5400
5401 /* First determine the working precision. From Hull & Abrham */
5402 /* this is set->digits+h+2. However, if x is 'over-precise' we */
5403 /* need to allow for all its digits to potentially participate */
5404 /* (consider an x where all the excess digits are 9s) so in */
5405 /* this case use x->digits+h+2 */
5406 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
5407
5408 /* a and t are variable precision, and depend on p, so space */
5409 /* must be allocated for them if necessary */
5410
5411 /* the accumulator needs to be able to hold 2p digits so that */
5412 /* the additions on the second and subsequent iterations are */
5413 /* sufficiently exact. */
5414 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5415 if (needbytes>sizeof(bufa)) { /* need malloc space */
5416 allocbufa=(decNumber *)malloc(needbytes);
5417 if (allocbufa==NULL) { /* hopeless -- abandon */
5418 *status|=DEC_Insufficient_storage;
5419 break;}
5420 a=allocbufa; /* use the allocated space */
5421 }
5422 /* the term needs to be able to hold p digits (which is */
5423 /* guaranteed to be larger than x->digits, so the initial copy */
5424 /* is safe); it may also be used for the raise-to-power */
5425 /* calculation below, which needs an extra two digits */
5426 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5427 if (needbytes>sizeof(buft)) { /* need malloc space */
5428 allocbuft=(decNumber *)malloc(needbytes);
5429 if (allocbuft==NULL) { /* hopeless -- abandon */
5430 *status|=DEC_Insufficient_storage;
5431 break;}
5432 t=allocbuft; /* use the allocated space */
5433 }
5434
5435 uprv_decNumberCopy(t, x); /* term=x */
5436 uprv_decNumberZero(a); *a->lsu=1; /* accumulator=1 */
5437 uprv_decNumberZero(d); *d->lsu=2; /* divisor=2 */
5438 uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5439
5440 /* set up the contexts for calculating a, t, and d */
5441 uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5442 dset=tset;
5443 /* accumulator bounds are set above, set precision now */
5444 aset.digits=p*2; /* double */
5445 /* term bounds avoid any underflow or overflow */
5446 tset.digits=p;
5447 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
5448 /* [dset.digits=16, etc., are sufficient] */
5449
5450 /* finally ready to roll */
5451 for (;;) {
5452 #if DECCHECK
5453 iterations++;
5454 #endif
5455 /* only the status from the accumulation is interesting */
5456 /* [but it should remain unchanged after first add] */
5457 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
5458 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
5459 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
5460 /* the iteration ends when the term cannot affect the result, */
5461 /* if rounded to p digits, which is when its value is smaller */
5462 /* than the accumulator by p+1 digits. There must also be */
5463 /* full precision in a. */
5464 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5465 && (a->digits>=p)) break;
5466 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
5467 } /* iterate */
5468
5469 #if DECCHECK
5470 /* just a sanity check; comment out test to show always */
5471 if (iterations>p+3)
5472 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5473 (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5474 #endif
5475 } /* h<=8 */
5476
5477 /* apply postconditioning: a=a**(10**h) -- this is calculated */
5478 /* at a slightly higher precision than Hull & Abrham suggest */
5479 if (h>0) {
5480 Int seenbit=0; /* set once a 1-bit is seen */
5481 Int i; /* counter */
5482 Int n=powers[h]; /* always positive */
5483 aset.digits=p+2; /* sufficient precision */
5484 /* avoid the overhead and many extra digits of decNumberPower */
5485 /* as all that is needed is the short 'multipliers' loop; here */
5486 /* accumulate the answer into t */
5487 uprv_decNumberZero(t); *t->lsu=1; /* acc=1 */
5488 for (i=1;;i++){ /* for each bit [top bit ignored] */
5489 /* abandon if have had overflow or terminal underflow */
5490 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5491 if (*status&DEC_Overflow || ISZERO(t)) break;}
5492 n=n<<1; /* move next bit to testable position */
5493 if (n<0) { /* top bit is set */
5494 seenbit=1; /* OK, have a significant bit */
5495 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5496 }
5497 if (i==31) break; /* that was the last bit */
5498 if (!seenbit) continue; /* no need to square 1 */
5499 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5500 } /*i*/ /* 32 bits */
5501 /* decNumberShow(t); */
5502 a=t; /* and carry on using t instead of a */
5503 }
5504
5505 /* Copy and round the result to res */
5506 residue=1; /* indicate dirt to right .. */
5507 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5508 aset.digits=set->digits; /* [use default rounding] */
5509 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5510 decFinish(res, set, &residue, status); /* cleanup/set flags */
5511 } while(0); /* end protected */
5512
5513 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
5514 if (allocbufa!=NULL) free(allocbufa); /* .. */
5515 if (allocbuft!=NULL) free(allocbuft); /* .. */
5516 /* [status is handled by caller] */
5517 return res;
5518 } /* decExpOp */
5519
5520/* ------------------------------------------------------------------ */
5521/* Initial-estimate natural logarithm table */
5522/* */
5523/* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
5524/* The result is a 4-digit encode of the coefficient (c=the */
5525/* top 14 bits encoding 0-9999) and a 2-digit encode of the */
5526/* exponent (e=the bottom 2 bits encoding 0-3) */
5527/* */
5528/* The resulting value is given by: */
5529/* */
5530/* v = -c * 10**(-e-3) */
5531/* */
5532/* where e and c are extracted from entry k = LNnn[x-10] */
5533/* where x is truncated (NB) into the range 10 through 99, */
5534/* and then c = k>>2 and e = k&3. */
5535/* ------------------------------------------------------------------ */
4388f060 5536static const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
729e4ab9
A
5537 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
5538 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
5539 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5540 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5541 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5542 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5543 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
5544 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5545 10130, 6046, 20055};
5546
5547/* ------------------------------------------------------------------ */
5548/* decLnOp -- effect natural logarithm */
5549/* */
5550/* This computes C = ln(A) */
5551/* */
5552/* res is C, the result. C may be A */
5553/* rhs is A */
5554/* set is the context; note that rounding mode has no effect */
5555/* */
5556/* C must have space for set->digits digits. */
5557/* */
5558/* Notable cases: */
5559/* A<0 -> Invalid */
5560/* A=0 -> -Infinity (Exact) */
5561/* A=+Infinity -> +Infinity (Exact) */
5562/* A=1 exactly -> 0 (Exact) */
5563/* */
5564/* Restrictions (as for Exp): */
5565/* */
5566/* digits, emax, and -emin in the context must be less than */
5567/* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
5568/* bounds or a zero. This is an internal routine, so these */
5569/* restrictions are contractual and not enforced. */
5570/* */
5571/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5572/* almost always be correctly rounded, but may be up to 1 ulp in */
5573/* error in rare cases. */
5574/* ------------------------------------------------------------------ */
5575/* The result is calculated using Newton's method, with each */
5576/* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
5577/* Epperson 1989. */
5578/* */
5579/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5580/* This has to be calculated at the sum of the precision of x and the */
5581/* working precision. */
5582/* */
5583/* Implementation notes: */
5584/* */
5585/* 1. This is separated out as decLnOp so it can be called from */
5586/* other Mathematical functions (e.g., Log 10) with a wider range */
5587/* than normal. In particular, it can handle the slightly wider */
5588/* (+9+2) range needed by a power function. */
5589/* */
5590/* 2. The speed of this function is about 10x slower than exp, as */
5591/* it typically needs 4-6 iterations for short numbers, and the */
5592/* extra precision needed adds a squaring effect, twice. */
5593/* */
5594/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
5595/* as these are common requests. ln(10) is used by log10(x). */
5596/* */
5597/* 4. An iteration might be saved by widening the LNnn table, and */
5598/* would certainly save at least one if it were made ten times */
5599/* bigger, too (for truncated fractions 0.100 through 0.999). */
5600/* However, for most practical evaluations, at least four or five */
5601/* iterations will be neede -- so this would only speed up by */
5602/* 20-25% and that probably does not justify increasing the table */
5603/* size. */
5604/* */
5605/* 5. The static buffers are larger than might be expected to allow */
5606/* for calls from decNumberPower. */
5607/* ------------------------------------------------------------------ */
4388f060
A
5608#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
5609#pragma GCC diagnostic push
5610#pragma GCC diagnostic ignored "-Warray-bounds"
5611#endif
729e4ab9
A
5612decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5613 decContext *set, uInt *status) {
5614 uInt ignore=0; /* working status accumulator */
5615 uInt needbytes; /* for space calculations */
5616 Int residue; /* rounding residue */
5617 Int r; /* rhs=f*10**r [see below] */
5618 Int p; /* working precision */
5619 Int pp; /* precision for iteration */
5620 Int t; /* work */
5621
5622 /* buffers for a (accumulator, typically precision+2) and b */
5623 /* (adjustment calculator, same size) */
5624 decNumber bufa[D2N(DECBUFFER+12)];
5625 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5626 decNumber *a=bufa; /* accumulator/work */
5627 decNumber bufb[D2N(DECBUFFER*2+2)];
5628 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */
5629 decNumber *b=bufb; /* adjustment/work */
5630
5631 decNumber numone; /* constant 1 */
5632 decNumber cmp; /* work */
5633 decContext aset, bset; /* working contexts */
5634
5635 #if DECCHECK
5636 Int iterations=0; /* for later sanity check */
5637 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5638 #endif
5639
5640 do { /* protect allocated storage */
5641 if (SPECIALARG) { /* handle infinities and NaNs */
5642 if (decNumberIsInfinite(rhs)) { /* an infinity */
5643 if (decNumberIsNegative(rhs)) /* -Infinity -> error */
5644 *status|=DEC_Invalid_operation;
5645 else uprv_decNumberCopy(res, rhs); /* +Infinity -> self */
5646 }
5647 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5648 break;}
5649
5650 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
5651 uprv_decNumberZero(res); /* make clean */
5652 res->bits=DECINF|DECNEG; /* set - infinity */
5653 break;} /* [no status to set] */
5654
5655 /* Non-zero negatives are bad... */
5656 if (decNumberIsNegative(rhs)) { /* -x -> error */
5657 *status|=DEC_Invalid_operation;
5658 break;}
5659
5660 /* Here, rhs is positive, finite, and in range */
5661
5662 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5663 if (rhs->exponent==0 && set->digits<=40) {
5664 #if DECDPUN==1
5665 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5666 #else
5667 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
5668 #endif
5669 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5670 #define LN10 "2.302585092994045684017991454684364207601"
5671 uprv_decNumberFromString(res, LN10, &aset);
5672 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5673 break;}
5674 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5675 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5676 #define LN2 "0.6931471805599453094172321214581765680755"
5677 uprv_decNumberFromString(res, LN2, &aset);
5678 *status|=(DEC_Inexact | DEC_Rounded);
5679 break;}
5680 } /* integer and short */
5681
5682 /* Determine the working precision. This is normally the */
5683 /* requested precision + 2, with a minimum of 9. However, if */
5684 /* the rhs is 'over-precise' then allow for all its digits to */
5685 /* potentially participate (consider an rhs where all the excess */
5686 /* digits are 9s) so in this case use rhs->digits+2. */
5687 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5688
5689 /* Allocate space for the accumulator and the high-precision */
5690 /* adjustment calculator, if necessary. The accumulator must */
5691 /* be able to hold p digits, and the adjustment up to */
5692 /* rhs->digits+p digits. They are also made big enough for 16 */
5693 /* digits so that they can be used for calculating the initial */
5694 /* estimate. */
5695 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5696 if (needbytes>sizeof(bufa)) { /* need malloc space */
5697 allocbufa=(decNumber *)malloc(needbytes);
5698 if (allocbufa==NULL) { /* hopeless -- abandon */
5699 *status|=DEC_Insufficient_storage;
5700 break;}
5701 a=allocbufa; /* use the allocated space */
5702 }
5703 pp=p+rhs->digits;
5704 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5705 if (needbytes>sizeof(bufb)) { /* need malloc space */
5706 allocbufb=(decNumber *)malloc(needbytes);
5707 if (allocbufb==NULL) { /* hopeless -- abandon */
5708 *status|=DEC_Insufficient_storage;
5709 break;}
5710 b=allocbufb; /* use the allocated space */
5711 }
5712
5713 /* Prepare an initial estimate in acc. Calculate this by */
5714 /* considering the coefficient of x to be a normalized fraction, */
5715 /* f, with the decimal point at far left and multiplied by */
5716 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
5717 /* ln(x) = ln(f) + ln(10)*r */
5718 /* Get the initial estimate for ln(f) from a small lookup */
5719 /* table (see above) indexed by the first two digits of f, */
5720 /* truncated. */
5721
5722 uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5723 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
5724 uprv_decNumberFromInt32(a, r); /* a=r */
5725 uprv_decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
5726 b->exponent=-6; /* .. */
5727 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
5728 /* now get top two digits of rhs into b by simple truncate and */
5729 /* force to integer */
5730 residue=0; /* (no residue) */
5731 aset.digits=2; aset.round=DEC_ROUND_DOWN;
5732 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5733 b->exponent=0; /* make integer */
5734 t=decGetInt(b); /* [cannot fail] */
5735 if (t<10) t=X10(t); /* adjust single-digit b */
5736 t=LNnn[t-10]; /* look up ln(b) */
5737 uprv_decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
5738 b->exponent=-(t&3)-3; /* set exponent */
5739 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
5740 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5741 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5742 /* the initial estimate is now in a, with up to 4 digits correct. */
5743 /* When rhs is at or near Nmax the estimate will be low, so we */
5744 /* will approach it from below, avoiding overflow when calling exp. */
5745
5746 uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
5747
5748 /* accumulator bounds are as requested (could underflow, but */
5749 /* cannot overflow) */
5750 aset.emax=set->emax;
5751 aset.emin=set->emin;
5752 aset.clamp=0; /* no concrete format */
5753 /* set up a context to be used for the multiply and subtract */
5754 bset=aset;
5755 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
5756 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
5757 /* [see decExpOp call below] */
5758 /* for each iteration double the number of digits to calculate, */
5759 /* up to a maximum of p */
5760 pp=9; /* initial precision */
5761 /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5762 /* 34+2, which is ideal for standard-sized numbers] */
5763 aset.digits=pp; /* working context */
5764 bset.digits=pp+rhs->digits; /* wider context */
5765 for (;;) { /* iterate */
5766 #if DECCHECK
5767 iterations++;
5768 if (iterations>24) break; /* consider 9 * 2**24 */
5769 #endif
5770 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
5771 /* catastrophic subtraction but it really is the difference */
5772 /* from 1 that is of interest. */
5773 /* Use the internal entry point to Exp as it allows the double */
5774 /* range for calculating exp(-a) when a is the tiniest subnormal. */
5775 a->bits^=DECNEG; /* make -a */
5776 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
5777 a->bits^=DECNEG; /* restore sign of a */
5778 /* now multiply by rhs and subtract 1, at the wider precision */
5779 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
5780 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5781
5782 /* the iteration ends when the adjustment cannot affect the */
5783 /* result by >=0.5 ulp (at the requested digits), which */
5784 /* is when its value is smaller than the accumulator by */
5785 /* set->digits+1 digits (or it is zero) -- this is a looser */
5786 /* requirement than for Exp because all that happens to the */
5787 /* accumulator after this is the final rounding (but note that */
5788 /* there must also be full precision in a, or a=0). */
5789
5790 if (decNumberIsZero(b) ||
5791 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5792 if (a->digits==p) break;
5793 if (decNumberIsZero(a)) {
5794 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5795 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
5796 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
5797 break;
5798 }
5799 /* force padding if adjustment has gone to 0 before full length */
5800 if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5801 }
5802
5803 /* not done yet ... */
5804 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
5805 if (pp==p) continue; /* precision is at maximum */
5806 /* lengthen the next calculation */
5807 pp=pp*2; /* double precision */
5808 if (pp>p) pp=p; /* clamp to maximum */
5809 aset.digits=pp; /* working context */
5810 bset.digits=pp+rhs->digits; /* wider context */
5811 } /* Newton's iteration */
5812
5813 #if DECCHECK
5814 /* just a sanity check; remove the test to show always */
5815 if (iterations>24)
5816 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5817 (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5818 #endif
5819
5820 /* Copy and round the result to res */
5821 residue=1; /* indicate dirt to right */
5822 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5823 aset.digits=set->digits; /* [use default rounding] */
5824 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5825 decFinish(res, set, &residue, status); /* cleanup/set flags */
5826 } while(0); /* end protected */
5827
5828 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5829 if (allocbufb!=NULL) free(allocbufb); /* .. */
5830 /* [status is handled by caller] */
5831 return res;
5832 } /* decLnOp */
4388f060
A
5833#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
5834#pragma GCC diagnostic pop
5835#endif
729e4ab9
A
5836
5837/* ------------------------------------------------------------------ */
5838/* decQuantizeOp -- force exponent to requested value */
5839/* */
5840/* This computes C = op(A, B), where op adjusts the coefficient */
5841/* of C (by rounding or shifting) such that the exponent (-scale) */
5842/* of C has the value B or matches the exponent of B. */
5843/* The numerical value of C will equal A, except for the effects of */
5844/* any rounding that occurred. */
5845/* */
5846/* res is C, the result. C may be A or B */
5847/* lhs is A, the number to adjust */
5848/* rhs is B, the requested exponent */
5849/* set is the context */
5850/* quant is 1 for quantize or 0 for rescale */
5851/* status is the status accumulator (this can be called without */
5852/* risk of control loss) */
5853/* */
5854/* C must have space for set->digits digits. */
5855/* */
5856/* Unless there is an error or the result is infinite, the exponent */
5857/* after the operation is guaranteed to be that requested. */
5858/* ------------------------------------------------------------------ */
5859static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5860 const decNumber *rhs, decContext *set,
5861 Flag quant, uInt *status) {
5862 #if DECSUBSET
5863 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5864 decNumber *allocrhs=NULL; /* .., rhs */
5865 #endif
5866 const decNumber *inrhs=rhs; /* save original rhs */
5867 Int reqdigits=set->digits; /* requested DIGITS */
5868 Int reqexp; /* requested exponent [-scale] */
5869 Int residue=0; /* rounding residue */
5870 Int etiny=set->emin-(reqdigits-1);
5871
5872 #if DECCHECK
5873 if (decCheckOperands(res, lhs, rhs, set)) return res;
5874 #endif
5875
5876 do { /* protect allocated storage */
5877 #if DECSUBSET
5878 if (!set->extended) {
5879 /* reduce operands and set lostDigits status, as needed */
5880 if (lhs->digits>reqdigits) {
5881 alloclhs=decRoundOperand(lhs, set, status);
5882 if (alloclhs==NULL) break;
5883 lhs=alloclhs;
5884 }
5885 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5886 allocrhs=decRoundOperand(rhs, set, status);
5887 if (allocrhs==NULL) break;
5888 rhs=allocrhs;
5889 }
5890 }
5891 #endif
5892 /* [following code does not require input rounding] */
5893
5894 /* Handle special values */
5895 if (SPECIALARGS) {
5896 /* NaNs get usual processing */
5897 if (SPECIALARGS & (DECSNAN | DECNAN))
5898 decNaNs(res, lhs, rhs, set, status);
5899 /* one infinity but not both is bad */
5900 else if ((lhs->bits ^ rhs->bits) & DECINF)
5901 *status|=DEC_Invalid_operation;
5902 /* both infinity: return lhs */
5903 else uprv_decNumberCopy(res, lhs); /* [nop if in place] */
5904 break;
5905 }
5906
5907 /* set requested exponent */
5908 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
5909 else { /* rescale -- use value of rhs */
5910 /* Original rhs must be an integer that fits and is in range, */
5911 /* which could be from -1999999997 to +999999999, thanks to */
5912 /* subnormals */
5913 reqexp=decGetInt(inrhs); /* [cannot fail] */
5914 }
5915
5916 #if DECSUBSET
5917 if (!set->extended) etiny=set->emin; /* no subnormals */
5918 #endif
5919
5920 if (reqexp==BADINT /* bad (rescale only) or .. */
5921 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
5922 || (reqexp<etiny) /* < lowest */
5923 || (reqexp>set->emax)) { /* > emax */
5924 *status|=DEC_Invalid_operation;
5925 break;}
5926
5927 /* the RHS has been processed, so it can be overwritten now if necessary */
5928 if (ISZERO(lhs)) { /* zero coefficient unchanged */
5929 uprv_decNumberCopy(res, lhs); /* [nop if in place] */
5930 res->exponent=reqexp; /* .. just set exponent */
5931 #if DECSUBSET
5932 if (!set->extended) res->bits=0; /* subset specification; no -0 */
5933 #endif
5934 }
5935 else { /* non-zero lhs */
5936 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
5937 /* if adjusted coefficient will definitely not fit, give up now */
5938 if ((lhs->digits-adjust)>reqdigits) {
5939 *status|=DEC_Invalid_operation;
5940 break;
5941 }
5942
5943 if (adjust>0) { /* increasing exponent */
5944 /* this will decrease the length of the coefficient by adjust */
5945 /* digits, and must round as it does so */
5946 decContext workset; /* work */
5947 workset=*set; /* clone rounding, etc. */
5948 workset.digits=lhs->digits-adjust; /* set requested length */
5949 /* [note that the latter can be <1, here] */
5950 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5951 decApplyRound(res, &workset, residue, status); /* .. and round */
5952 residue=0; /* [used] */
5953 /* If just rounded a 999s case, exponent will be off by one; */
5954 /* adjust back (after checking space), if so. */
5955 if (res->exponent>reqexp) {
5956 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5957 /* set->digits==3 */
5958 if (res->digits==reqdigits) { /* cannot shift by 1 */
5959 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5960 *status|=DEC_Invalid_operation;
5961 break;
5962 }
5963 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5964 res->exponent--; /* (re)adjust the exponent. */
5965 }
5966 #if DECSUBSET
5967 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5968 #endif
5969 } /* increase */
5970 else /* adjust<=0 */ { /* decreasing or = exponent */
5971 /* this will increase the length of the coefficient by -adjust */
5972 /* digits, by adding zero or more trailing zeros; this is */
5973 /* already checked for fit, above */
5974 uprv_decNumberCopy(res, lhs); /* [it will fit] */
5975 /* if padding needed (adjust<0), add it now... */
5976 if (adjust<0) {
5977 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5978 res->exponent+=adjust; /* adjust the exponent */
5979 }
5980 } /* decrease */
5981 } /* non-zero */
5982
5983 /* Check for overflow [do not use Finalize in this case, as an */
5984 /* overflow here is a "don't fit" situation] */
5985 if (res->exponent>set->emax-res->digits+1) { /* too big */
5986 *status|=DEC_Invalid_operation;
5987 break;
5988 }
5989 else {
5990 decFinalize(res, set, &residue, status); /* set subnormal flags */
5991 *status&=~DEC_Underflow; /* suppress Underflow [as per 754] */
5992 }
5993 } while(0); /* end protected */
5994
5995 #if DECSUBSET
5996 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */
5997 if (alloclhs!=NULL) free(alloclhs); /* .. */
5998 #endif
5999 return res;
6000 } /* decQuantizeOp */
6001
6002/* ------------------------------------------------------------------ */
6003/* decCompareOp -- compare, min, or max two Numbers */
6004/* */
6005/* This computes C = A ? B and carries out one of four operations: */
6006/* COMPARE -- returns the signum (as a number) giving the */
6007/* result of a comparison unless one or both */
6008/* operands is a NaN (in which case a NaN results) */
6009/* COMPSIG -- as COMPARE except that a quiet NaN raises */
6010/* Invalid operation. */
6011/* COMPMAX -- returns the larger of the operands, using the */
6012/* 754 maxnum operation */
6013/* COMPMAXMAG -- ditto, comparing absolute values */
6014/* COMPMIN -- the 754 minnum operation */
6015/* COMPMINMAG -- ditto, comparing absolute values */
6016/* COMTOTAL -- returns the signum (as a number) giving the */
6017/* result of a comparison using 754 total ordering */
6018/* */
6019/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
6020/* lhs is A */
6021/* rhs is B */
6022/* set is the context */
6023/* op is the operation flag */
6024/* status is the usual accumulator */
6025/* */
6026/* C must have space for one digit for COMPARE or set->digits for */
6027/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
6028/* ------------------------------------------------------------------ */
6029/* The emphasis here is on speed for common cases, and avoiding */
6030/* coefficient comparison if possible. */
6031/* ------------------------------------------------------------------ */
6032static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6033 const decNumber *rhs, decContext *set,
6034 Flag op, uInt *status) {
6035 #if DECSUBSET
6036 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
6037 decNumber *allocrhs=NULL; /* .., rhs */
6038 #endif
6039 Int result=0; /* default result value */
6040 uByte merged; /* work */
6041
6042 #if DECCHECK
6043 if (decCheckOperands(res, lhs, rhs, set)) return res;
6044 #endif
6045
6046 do { /* protect allocated storage */
6047 #if DECSUBSET
6048 if (!set->extended) {
6049 /* reduce operands and set lostDigits status, as needed */
6050 if (lhs->digits>set->digits) {
6051 alloclhs=decRoundOperand(lhs, set, status);
6052 if (alloclhs==NULL) {result=BADINT; break;}
6053 lhs=alloclhs;
6054 }
6055 if (rhs->digits>set->digits) {
6056 allocrhs=decRoundOperand(rhs, set, status);
6057 if (allocrhs==NULL) {result=BADINT; break;}
6058 rhs=allocrhs;
6059 }
6060 }
6061 #endif
6062 /* [following code does not require input rounding] */
6063
6064 /* If total ordering then handle differing signs 'up front' */
6065 if (op==COMPTOTAL) { /* total ordering */
6066 if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6067 result=-1;
6068 break;
6069 }
6070 if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6071 result=+1;
6072 break;
6073 }
6074 }
6075
6076 /* handle NaNs specially; let infinities drop through */
6077 /* This assumes sNaN (even just one) leads to NaN. */
6078 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6079 if (merged) { /* a NaN bit set */
6080 if (op==COMPARE); /* result will be NaN */
6081 else if (op==COMPSIG) /* treat qNaN as sNaN */
6082 *status|=DEC_Invalid_operation | DEC_sNaN;
6083 else if (op==COMPTOTAL) { /* total ordering, always finite */
6084 /* signs are known to be the same; compute the ordering here */
6085 /* as if the signs are both positive, then invert for negatives */
6086 if (!decNumberIsNaN(lhs)) result=-1;
6087 else if (!decNumberIsNaN(rhs)) result=+1;
6088 /* here if both NaNs */
6089 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6090 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6091 else { /* both NaN or both sNaN */
6092 /* now it just depends on the payload */
6093 result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6094 rhs->lsu, D2U(rhs->digits), 0);
6095 /* [Error not possible, as these are 'aligned'] */
6096 } /* both same NaNs */
6097 if (decNumberIsNegative(lhs)) result=-result;
6098 break;
6099 } /* total order */
6100
6101 else if (merged & DECSNAN); /* sNaN -> qNaN */
6102 else { /* here if MIN or MAX and one or two quiet NaNs */
6103 /* min or max -- 754 rules ignore single NaN */
6104 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6105 /* just one NaN; force choice to be the non-NaN operand */
6106 op=COMPMAX;
6107 if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6108 else result=+1; /* pick lhs */
6109 break;
6110 }
6111 } /* max or min */
6112 op=COMPNAN; /* use special path */
6113 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
6114 break;
6115 }
6116 /* have numbers */
6117 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6118 else result=decCompare(lhs, rhs, 0); /* sign matters */
6119 } while(0); /* end protected */
6120
6121 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6122 else {
6123 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6124 if (op==COMPTOTAL && result==0) {
6125 /* operands are numerically equal or same NaN (and same sign, */
6126 /* tested first); if identical, leave result 0 */
6127 if (lhs->exponent!=rhs->exponent) {
6128 if (lhs->exponent<rhs->exponent) result=-1;
6129 else result=+1;
6130 if (decNumberIsNegative(lhs)) result=-result;
6131 } /* lexp!=rexp */
6132 } /* total-order by exponent */
6133 uprv_decNumberZero(res); /* [always a valid result] */
6134 if (result!=0) { /* must be -1 or +1 */
6135 *res->lsu=1;
6136 if (result<0) res->bits=DECNEG;
6137 }
6138 }
6139 else if (op==COMPNAN); /* special, drop through */
6140 else { /* MAX or MIN, non-NaN result */
6141 Int residue=0; /* rounding accumulator */
6142 /* choose the operand for the result */
6143 const decNumber *choice;
6144 if (result==0) { /* operands are numerically equal */
6145 /* choose according to sign then exponent (see 754) */
6146 uByte slhs=(lhs->bits & DECNEG);
6147 uByte srhs=(rhs->bits & DECNEG);
6148 #if DECSUBSET
6149 if (!set->extended) { /* subset: force left-hand */
6150 op=COMPMAX;
6151 result=+1;
6152 }
6153 else
6154 #endif
6155 if (slhs!=srhs) { /* signs differ */
6156 if (slhs) result=-1; /* rhs is max */
6157 else result=+1; /* lhs is max */
6158 }
6159 else if (slhs && srhs) { /* both negative */
6160 if (lhs->exponent<rhs->exponent) result=+1;
6161 else result=-1;
6162 /* [if equal, use lhs, technically identical] */
6163 }
6164 else { /* both positive */
6165 if (lhs->exponent>rhs->exponent) result=+1;
6166 else result=-1;
6167 /* [ditto] */
6168 }
6169 } /* numerically equal */
6170 /* here result will be non-0; reverse if looking for MIN */
6171 if (op==COMPMIN || op==COMPMINMAG) result=-result;
6172 choice=(result>0 ? lhs : rhs); /* choose */
6173 /* copy chosen to result, rounding if need be */
6174 decCopyFit(res, choice, set, &residue, status);
6175 decFinish(res, set, &residue, status);
6176 }
6177 }
6178 #if DECSUBSET
6179 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */
6180 if (alloclhs!=NULL) free(alloclhs); /* .. */
6181 #endif
6182 return res;
6183 } /* decCompareOp */
6184
6185/* ------------------------------------------------------------------ */
6186/* decCompare -- compare two decNumbers by numerical value */
6187/* */
6188/* This routine compares A ? B without altering them. */
6189/* */
6190/* Arg1 is A, a decNumber which is not a NaN */
6191/* Arg2 is B, a decNumber which is not a NaN */
6192/* Arg3 is 1 for a sign-independent compare, 0 otherwise */
6193/* */
6194/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6195/* (the only possible failure is an allocation error) */
6196/* ------------------------------------------------------------------ */
6197static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6198 Flag abs_c) {
6199 Int result; /* result value */
6200 Int sigr; /* rhs signum */
6201 Int compare; /* work */
6202
6203 result=1; /* assume signum(lhs) */
6204 if (ISZERO(lhs)) result=0;
6205 if (abs_c) {
6206 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
6207 /* RHS is non-zero */
6208 if (result==0) return -1; /* LHS is 0; RHS wins */
6209 /* [here, both non-zero, result=1] */
6210 }
6211 else { /* signs matter */
6212 if (result && decNumberIsNegative(lhs)) result=-1;
6213 sigr=1; /* compute signum(rhs) */
6214 if (ISZERO(rhs)) sigr=0;
6215 else if (decNumberIsNegative(rhs)) sigr=-1;
6216 if (result > sigr) return +1; /* L > R, return 1 */
6217 if (result < sigr) return -1; /* L < R, return -1 */
6218 if (result==0) return 0; /* both 0 */
6219 }
6220
6221 /* signums are the same; both are non-zero */
6222 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
6223 if (decNumberIsInfinite(rhs)) {
6224 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6225 else result=-result; /* only rhs infinite */
6226 }
6227 return result;
6228 }
6229 /* must compare the coefficients, allowing for exponents */
6230 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
6231 /* swap sides, and sign */
6232 const decNumber *temp=lhs;
6233 lhs=rhs;
6234 rhs=temp;
6235 result=-result;
6236 }
6237 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6238 rhs->lsu, D2U(rhs->digits),
6239 rhs->exponent-lhs->exponent);
6240 if (compare!=BADINT) compare*=result; /* comparison succeeded */
6241 return compare;
6242 } /* decCompare */
6243
6244/* ------------------------------------------------------------------ */
6245/* decUnitCompare -- compare two >=0 integers in Unit arrays */
6246/* */
6247/* This routine compares A ? B*10**E where A and B are unit arrays */
6248/* A is a plain integer */
6249/* B has an exponent of E (which must be non-negative) */
6250/* */
6251/* Arg1 is A first Unit (lsu) */
6252/* Arg2 is A length in Units */
6253/* Arg3 is B first Unit (lsu) */
6254/* Arg4 is B length in Units */
6255/* Arg5 is E (0 if the units are aligned) */
6256/* */
6257/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6258/* (the only possible failure is an allocation error, which can */
6259/* only occur if E!=0) */
6260/* ------------------------------------------------------------------ */
6261static Int decUnitCompare(const Unit *a, Int alength,
6262 const Unit *b, Int blength, Int exp) {
6263 Unit *acc; /* accumulator for result */
6264 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6265 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
6266 Int accunits, need; /* units in use or needed for acc */
6267 const Unit *l, *r, *u; /* work */
6268 Int expunits, exprem, result; /* .. */
6269
6270 if (exp==0) { /* aligned; fastpath */
6271 if (alength>blength) return 1;
6272 if (alength<blength) return -1;
6273 /* same number of units in both -- need unit-by-unit compare */
6274 l=a+alength-1;
6275 r=b+alength-1;
6276 for (;l>=a; l--, r--) {
6277 if (*l>*r) return 1;
6278 if (*l<*r) return -1;
6279 }
6280 return 0; /* all units match */
6281 } /* aligned */
6282
6283 /* Unaligned. If one is >1 unit longer than the other, padded */
6284 /* approximately, then can return easily */
6285 if (alength>blength+(Int)D2U(exp)) return 1;
6286 if (alength+1<blength+(Int)D2U(exp)) return -1;
6287
6288 /* Need to do a real subtract. For this, a result buffer is needed */
6289 /* even though only the sign is of interest. Its length needs */
6290 /* to be the larger of alength and padded blength, +2 */
6291 need=blength+D2U(exp); /* maximum real length of B */
6292 if (need<alength) need=alength;
6293 need+=2;
6294 acc=accbuff; /* assume use local buffer */
6295 if (need*sizeof(Unit)>sizeof(accbuff)) {
6296 allocacc=(Unit *)malloc(need*sizeof(Unit));
6297 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */
6298 acc=allocacc;
6299 }
6300 /* Calculate units and remainder from exponent. */
6301 expunits=exp/DECDPUN;
6302 exprem=exp%DECDPUN;
6303 /* subtract [A+B*(-m)] */
6304 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6305 -(Int)powers[exprem]);
6306 /* [UnitAddSub result may have leading zeros, even on zero] */
6307 if (accunits<0) result=-1; /* negative result */
6308 else { /* non-negative result */
6309 /* check units of the result before freeing any storage */
6310 for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6311 result=(*u==0 ? 0 : +1);
6312 }
6313 /* clean up and return the result */
6314 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
6315 return result;
6316 } /* decUnitCompare */
6317
6318/* ------------------------------------------------------------------ */
6319/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
6320/* */
6321/* This routine performs the calculation: */
6322/* */
6323/* C=A+(B*M) */
6324/* */
6325/* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
6326/* */
6327/* A may be shorter or longer than B. */
6328/* */
6329/* Leading zeros are not removed after a calculation. The result is */
6330/* either the same length as the longer of A and B (adding any */
6331/* shift), or one Unit longer than that (if a Unit carry occurred). */
6332/* */
6333/* A and B content are not altered unless C is also A or B. */
6334/* C may be the same array as A or B, but only if no zero padding is */
6335/* requested (that is, C may be B only if bshift==0). */
6336/* C is filled from the lsu; only those units necessary to complete */
6337/* the calculation are referenced. */
6338/* */
6339/* Arg1 is A first Unit (lsu) */
6340/* Arg2 is A length in Units */
6341/* Arg3 is B first Unit (lsu) */
6342/* Arg4 is B length in Units */
6343/* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
6344/* Arg6 is C first Unit (lsu) */
6345/* Arg7 is M, the multiplier */
6346/* */
6347/* returns the count of Units written to C, which will be non-zero */
6348/* and negated if the result is negative. That is, the sign of the */
6349/* returned Int is the sign of the result (positive for zero) and */
6350/* the absolute value of the Int is the count of Units. */
6351/* */
6352/* It is the caller's responsibility to make sure that C size is */
6353/* safe, allowing space if necessary for a one-Unit carry. */
6354/* */
6355/* This routine is severely performance-critical; *any* change here */
6356/* must be measured (timed) to assure no performance degradation. */
6357/* In particular, trickery here tends to be counter-productive, as */
6358/* increased complexity of code hurts register optimizations on */
6359/* register-poor architectures. Avoiding divisions is nearly */
6360/* always a Good Idea, however. */
6361/* */
6362/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
6363/* (IBM Warwick, UK) for some of the ideas used in this routine. */
6364/* ------------------------------------------------------------------ */
6365static Int decUnitAddSub(const Unit *a, Int alength,
6366 const Unit *b, Int blength, Int bshift,
6367 Unit *c, Int m) {
6368 const Unit *alsu=a; /* A lsu [need to remember it] */
6369 Unit *clsu=c; /* C ditto */
6370 Unit *minC; /* low water mark for C */
6371 Unit *maxC; /* high water mark for C */
6372 eInt carry=0; /* carry integer (could be Long) */
6373 Int add; /* work */
6374 #if DECDPUN<=4 /* myriadal, millenary, etc. */
6375 Int est; /* estimated quotient */
6376 #endif
6377
6378 #if DECTRACE
6379 if (alength<1 || blength<1)
6380 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6381 #endif
6382
6383 maxC=c+alength; /* A is usually the longer */
6384 minC=c+blength; /* .. and B the shorter */
6385 if (bshift!=0) { /* B is shifted; low As copy across */
6386 minC+=bshift;
6387 /* if in place [common], skip copy unless there's a gap [rare] */
6388 if (a==c && bshift<=alength) {
6389 c+=bshift;
6390 a+=bshift;
6391 }
6392 else for (; c<clsu+bshift; a++, c++) { /* copy needed */
6393 if (a<alsu+alength) *c=*a;
6394 else *c=0;
6395 }
6396 }
6397 if (minC>maxC) { /* swap */
6398 Unit *hold=minC;
6399 minC=maxC;
6400 maxC=hold;
6401 }
6402
6403 /* For speed, do the addition as two loops; the first where both A */
6404 /* and B contribute, and the second (if necessary) where only one or */
6405 /* other of the numbers contribute. */
6406 /* Carry handling is the same (i.e., duplicated) in each case. */
6407 for (; c<minC; c++) {
6408 carry+=*a;
6409 a++;
6410 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
6411 b++; /* here is not a win] */
6412 /* here carry is new Unit of digits; it could be +ve or -ve */
6413 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6414 *c=(Unit)carry;
6415 carry=0;
6416 continue;
6417 }
6418 #if DECDPUN==4 /* use divide-by-multiply */
6419 if (carry>=0) {
6420 est=(((ueInt)carry>>11)*53687)>>18;
6421 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6422 carry=est; /* likely quotient [89%] */
6423 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6424 carry++;
6425 *c-=DECDPUNMAX+1;
6426 continue;
6427 }
6428 /* negative case */
6429 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6430 est=(((ueInt)carry>>11)*53687)>>18;
6431 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6432 carry=est-(DECDPUNMAX+1); /* correctly negative */
6433 if (*c<DECDPUNMAX+1) continue; /* was OK */
6434 carry++;
6435 *c-=DECDPUNMAX+1;
6436 #elif DECDPUN==3
6437 if (carry>=0) {
6438 est=(((ueInt)carry>>3)*16777)>>21;
6439 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6440 carry=est; /* likely quotient [99%] */
6441 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6442 carry++;
6443 *c-=DECDPUNMAX+1;
6444 continue;
6445 }
6446 /* negative case */
6447 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6448 est=(((ueInt)carry>>3)*16777)>>21;
6449 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6450 carry=est-(DECDPUNMAX+1); /* correctly negative */
6451 if (*c<DECDPUNMAX+1) continue; /* was OK */
6452 carry++;
6453 *c-=DECDPUNMAX+1;
6454 #elif DECDPUN<=2
6455 /* Can use QUOT10 as carry <= 4 digits */
6456 if (carry>=0) {
6457 est=QUOT10(carry, DECDPUN);
6458 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6459 carry=est; /* quotient */
6460 continue;
6461 }
6462 /* negative case */
6463 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6464 est=QUOT10(carry, DECDPUN);
6465 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6466 carry=est-(DECDPUNMAX+1); /* correctly negative */
6467 #else
6468 /* remainder operator is undefined if negative, so must test */
6469 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
6470 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
6471 carry=1;
6472 continue;
6473 }
6474 if (carry>=0) {
6475 *c=(Unit)(carry%(DECDPUNMAX+1));
6476 carry=carry/(DECDPUNMAX+1);
6477 continue;
6478 }
6479 /* negative case */
6480 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6481 *c=(Unit)(carry%(DECDPUNMAX+1));
6482 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6483 #endif
6484 } /* c */
6485
6486 /* now may have one or other to complete */
6487 /* [pretest to avoid loop setup/shutdown] */
6488 if (c<maxC) for (; c<maxC; c++) {
6489 if (a<alsu+alength) { /* still in A */
6490 carry+=*a;
6491 a++;
6492 }
6493 else { /* inside B */
6494 carry+=((eInt)*b)*m;
6495 b++;
6496 }
6497 /* here carry is new Unit of digits; it could be +ve or -ve and */
6498 /* magnitude up to DECDPUNMAX squared */
6499 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6500 *c=(Unit)carry;
6501 carry=0;
6502 continue;
6503 }
6504 /* result for this unit is negative or >DECDPUNMAX */
6505 #if DECDPUN==4 /* use divide-by-multiply */
6506 if (carry>=0) {
6507 est=(((ueInt)carry>>11)*53687)>>18;
6508 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6509 carry=est; /* likely quotient [79.7%] */
6510 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6511 carry++;
6512 *c-=DECDPUNMAX+1;
6513 continue;
6514 }
6515 /* negative case */
6516 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6517 est=(((ueInt)carry>>11)*53687)>>18;
6518 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6519 carry=est-(DECDPUNMAX+1); /* correctly negative */
6520 if (*c<DECDPUNMAX+1) continue; /* was OK */
6521 carry++;
6522 *c-=DECDPUNMAX+1;
6523 #elif DECDPUN==3
6524 if (carry>=0) {
6525 est=(((ueInt)carry>>3)*16777)>>21;
6526 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6527 carry=est; /* likely quotient [99%] */
6528 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6529 carry++;
6530 *c-=DECDPUNMAX+1;
6531 continue;
6532 }
6533 /* negative case */
6534 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6535 est=(((ueInt)carry>>3)*16777)>>21;
6536 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6537 carry=est-(DECDPUNMAX+1); /* correctly negative */
6538 if (*c<DECDPUNMAX+1) continue; /* was OK */
6539 carry++;
6540 *c-=DECDPUNMAX+1;
6541 #elif DECDPUN<=2
6542 if (carry>=0) {
6543 est=QUOT10(carry, DECDPUN);
6544 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6545 carry=est; /* quotient */
6546 continue;
6547 }
6548 /* negative case */
6549 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6550 est=QUOT10(carry, DECDPUN);
6551 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6552 carry=est-(DECDPUNMAX+1); /* correctly negative */
6553 #else
6554 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
6555 *c=(Unit)(carry-(DECDPUNMAX+1));
6556 carry=1;
6557 continue;
6558 }
6559 /* remainder operator is undefined if negative, so must test */
6560 if (carry>=0) {
6561 *c=(Unit)(carry%(DECDPUNMAX+1));
6562 carry=carry/(DECDPUNMAX+1);
6563 continue;
6564 }
6565 /* negative case */
6566 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6567 *c=(Unit)(carry%(DECDPUNMAX+1));
6568 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6569 #endif
6570 } /* c */
6571
6572 /* OK, all A and B processed; might still have carry or borrow */
6573 /* return number of Units in the result, negated if a borrow */
6574 if (carry==0) return c-clsu; /* no carry, so no more to do */
6575 if (carry>0) { /* positive carry */
6576 *c=(Unit)carry; /* place as new unit */
6577 c++; /* .. */
6578 return c-clsu;
6579 }
6580 /* -ve carry: it's a borrow; complement needed */
6581 add=1; /* temporary carry... */
6582 for (c=clsu; c<maxC; c++) {
6583 add=DECDPUNMAX+add-*c;
6584 if (add<=DECDPUNMAX) {
6585 *c=(Unit)add;
6586 add=0;
6587 }
6588 else {
6589 *c=0;
6590 add=1;
6591 }
6592 }
6593 /* add an extra unit iff it would be non-zero */
6594 #if DECTRACE
6595 printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6596 #endif
6597 if ((add-carry-1)!=0) {
6598 *c=(Unit)(add-carry-1);
6599 c++; /* interesting, include it */
6600 }
6601 return clsu-c; /* -ve result indicates borrowed */
6602 } /* decUnitAddSub */
6603
6604/* ------------------------------------------------------------------ */
6605/* decTrim -- trim trailing zeros or normalize */
6606/* */
6607/* dn is the number to trim or normalize */
6608/* set is the context to use to check for clamp */
6609/* all is 1 to remove all trailing zeros, 0 for just fraction ones */
6610/* noclamp is 1 to unconditional (unclamped) trim */
6611/* dropped returns the number of discarded trailing zeros */
6612/* returns dn */
6613/* */
6614/* If clamp is set in the context then the number of zeros trimmed */
6615/* may be limited if the exponent is high. */
6616/* All fields are updated as required. This is a utility operation, */
6617/* so special values are unchanged and no error is possible. */
6618/* ------------------------------------------------------------------ */
6619static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6620 Flag noclamp, Int *dropped) {
6621 Int d, exp; /* work */
6622 uInt cut; /* .. */
6623 Unit *up; /* -> current Unit */
6624
6625 #if DECCHECK
6626 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6627 #endif
6628
6629 *dropped=0; /* assume no zeros dropped */
6630 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
6631 || (*dn->lsu & 0x01)) return dn; /* .. or odd */
6632 if (ISZERO(dn)) { /* .. or 0 */
6633 dn->exponent=0; /* (sign is preserved) */
6634 return dn;
6635 }
6636
6637 /* have a finite number which is even */
6638 exp=dn->exponent;
6639 cut=1; /* digit (1-DECDPUN) in Unit */
6640 up=dn->lsu; /* -> current Unit */
6641 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6642 /* slice by powers */
6643 #if DECDPUN<=4
6644 uInt quot=QUOT10(*up, cut);
6645 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
6646 #else
6647 if (*up%powers[cut]!=0) break; /* found non-0 digit */
6648 #endif
6649 /* have a trailing 0 */
6650 if (!all) { /* trimming */
6651 /* [if exp>0 then all trailing 0s are significant for trim] */
6652 if (exp<=0) { /* if digit might be significant */
6653 if (exp==0) break; /* then quit */
6654 exp++; /* next digit might be significant */
6655 }
6656 }
6657 cut++; /* next power */
6658 if (cut>DECDPUN) { /* need new Unit */
6659 up++;
6660 cut=1;
6661 }
6662 } /* d */
6663 if (d==0) return dn; /* none to drop */
6664
6665 /* may need to limit drop if clamping */
6666 if (set->clamp && !noclamp) {
6667 Int maxd=set->emax-set->digits+1-dn->exponent;
6668 if (maxd<=0) return dn; /* nothing possible */
6669 if (d>maxd) d=maxd;
6670 }
6671
6672 /* effect the drop */
6673 decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6674 dn->exponent+=d; /* maintain numerical value */
6675 dn->digits-=d; /* new length */
6676 *dropped=d; /* report the count */
6677 return dn;
6678 } /* decTrim */
6679
6680/* ------------------------------------------------------------------ */
6681/* decReverse -- reverse a Unit array in place */
6682/* */
6683/* ulo is the start of the array */
6684/* uhi is the end of the array (highest Unit to include) */
6685/* */
6686/* The units ulo through uhi are reversed in place (if the number */
6687/* of units is odd, the middle one is untouched). Note that the */
6688/* digit(s) in each unit are unaffected. */
6689/* ------------------------------------------------------------------ */
6690static void decReverse(Unit *ulo, Unit *uhi) {
6691 Unit temp;
6692 for (; ulo<uhi; ulo++, uhi--) {
6693 temp=*ulo;
6694 *ulo=*uhi;
6695 *uhi=temp;
6696 }
6697 return;
6698 } /* decReverse */
6699
6700/* ------------------------------------------------------------------ */
6701/* decShiftToMost -- shift digits in array towards most significant */
6702/* */
6703/* uar is the array */
6704/* digits is the count of digits in use in the array */
6705/* shift is the number of zeros to pad with (least significant); */
6706/* it must be zero or positive */
6707/* */
6708/* returns the new length of the integer in the array, in digits */
6709/* */
6710/* No overflow is permitted (that is, the uar array must be known to */
6711/* be large enough to hold the result, after shifting). */
6712/* ------------------------------------------------------------------ */
6713static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6714 Unit *target, *source, *first; /* work */
6715 Int cut; /* odd 0's to add */
6716 uInt next; /* work */
6717
6718 if (shift==0) return digits; /* [fastpath] nothing to do */
6719 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
6720 *uar=(Unit)(*uar*powers[shift]);
6721 return digits+shift;
6722 }
6723
6724 next=0; /* all paths */
6725 source=uar+D2U(digits)-1; /* where msu comes from */
6726 target=source+D2U(shift); /* where upper part of first cut goes */
6727 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
6728 if (cut==0) { /* unit-boundary case */
6729 for (; source>=uar; source--, target--) *target=*source;
6730 }
6731 else {
6732 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6733 for (; source>=uar; source--, target--) {
6734 /* split the source Unit and accumulate remainder for next */
6735 #if DECDPUN<=4
6736 uInt quot=QUOT10(*source, cut);
6737 uInt rem=*source-quot*powers[cut];
6738 next+=quot;
6739 #else
6740 uInt rem=*source%powers[cut];
6741 next+=*source/powers[cut];
6742 #endif
6743 if (target<=first) *target=(Unit)next; /* write to target iff valid */
6744 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
6745 }
6746 } /* shift-move */
6747
6748 /* propagate any partial unit to one below and clear the rest */
6749 for (; target>=uar; target--) {
6750 *target=(Unit)next;
6751 next=0;
6752 }
6753 return digits+shift;
6754 } /* decShiftToMost */
6755
6756/* ------------------------------------------------------------------ */
6757/* decShiftToLeast -- shift digits in array towards least significant */
6758/* */
6759/* uar is the array */
6760/* units is length of the array, in units */
6761/* shift is the number of digits to remove from the lsu end; it */
6762/* must be zero or positive and <= than units*DECDPUN. */
6763/* */
6764/* returns the new length of the integer in the array, in units */
6765/* */
6766/* Removed digits are discarded (lost). Units not required to hold */
6767/* the final result are unchanged. */
6768/* ------------------------------------------------------------------ */
6769static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6770 Unit *target, *up; /* work */
6771 Int cut, count; /* work */
6772 Int quot, rem; /* for division */
6773
6774 if (shift==0) return units; /* [fastpath] nothing to do */
6775 if (shift==units*DECDPUN) { /* [fastpath] little to do */
6776 *uar=0; /* all digits cleared gives zero */
6777 return 1; /* leaves just the one */
6778 }
6779
6780 target=uar; /* both paths */
6781 cut=MSUDIGITS(shift);
6782 if (cut==DECDPUN) { /* unit-boundary case; easy */
6783 up=uar+D2U(shift);
6784 for (; up<uar+units; target++, up++) *target=*up;
6785 return target-uar;
6786 }
6787
6788 /* messier */
6789 up=uar+D2U(shift-cut); /* source; correct to whole Units */
6790 count=units*DECDPUN-shift; /* the maximum new length */
6791 #if DECDPUN<=4
6792 quot=QUOT10(*up, cut);
6793 #else
6794 quot=*up/powers[cut];
6795 #endif
6796 for (; ; target++) {
6797 *target=(Unit)quot;
6798 count-=(DECDPUN-cut);
6799 if (count<=0) break;
6800 up++;
6801 quot=*up;
6802 #if DECDPUN<=4
6803 quot=QUOT10(quot, cut);
6804 rem=*up-quot*powers[cut];
6805 #else
6806 rem=quot%powers[cut];
6807 quot=quot/powers[cut];
6808 #endif
6809 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6810 count-=cut;
6811 if (count<=0) break;
6812 }
6813 return target-uar+1;
6814 } /* decShiftToLeast */
6815
6816#if DECSUBSET
6817/* ------------------------------------------------------------------ */
6818/* decRoundOperand -- round an operand [used for subset only] */
6819/* */
6820/* dn is the number to round (dn->digits is > set->digits) */
6821/* set is the relevant context */
6822/* status is the status accumulator */
6823/* */
6824/* returns an allocated decNumber with the rounded result. */
6825/* */
6826/* lostDigits and other status may be set by this. */
6827/* */
6828/* Since the input is an operand, it must not be modified. */
6829/* Instead, return an allocated decNumber, rounded as required. */
6830/* It is the caller's responsibility to free the allocated storage. */
6831/* */
6832/* If no storage is available then the result cannot be used, so NULL */
6833/* is returned. */
6834/* ------------------------------------------------------------------ */
6835static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6836 uInt *status) {
6837 decNumber *res; /* result structure */
6838 uInt newstatus=0; /* status from round */
6839 Int residue=0; /* rounding accumulator */
6840
6841 /* Allocate storage for the returned decNumber, big enough for the */
6842 /* length specified by the context */
6843 res=(decNumber *)malloc(sizeof(decNumber)
6844 +(D2U(set->digits)-1)*sizeof(Unit));
6845 if (res==NULL) {
6846 *status|=DEC_Insufficient_storage;
6847 return NULL;
6848 }
6849 decCopyFit(res, dn, set, &residue, &newstatus);
6850 decApplyRound(res, set, residue, &newstatus);
6851
6852 /* If that set Inexact then "lost digits" is raised... */
6853 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6854 *status|=newstatus;
6855 return res;
6856 } /* decRoundOperand */
6857#endif
6858
6859/* ------------------------------------------------------------------ */
6860/* decCopyFit -- copy a number, truncating the coefficient if needed */
6861/* */
6862/* dest is the target decNumber */
6863/* src is the source decNumber */
6864/* set is the context [used for length (digits) and rounding mode] */
6865/* residue is the residue accumulator */
6866/* status contains the current status to be updated */
6867/* */
6868/* (dest==src is allowed and will be a no-op if fits) */
6869/* All fields are updated as required. */
6870/* ------------------------------------------------------------------ */
6871static void decCopyFit(decNumber *dest, const decNumber *src,
6872 decContext *set, Int *residue, uInt *status) {
6873 dest->bits=src->bits;
6874 dest->exponent=src->exponent;
6875 decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6876 } /* decCopyFit */
6877
6878/* ------------------------------------------------------------------ */
6879/* decSetCoeff -- set the coefficient of a number */
6880/* */
6881/* dn is the number whose coefficient array is to be set. */
6882/* It must have space for set->digits digits */
6883/* set is the context [for size] */
6884/* lsu -> lsu of the source coefficient [may be dn->lsu] */
6885/* len is digits in the source coefficient [may be dn->digits] */
6886/* residue is the residue accumulator. This has values as in */
6887/* decApplyRound, and will be unchanged unless the */
6888/* target size is less than len. In this case, the */
6889/* coefficient is truncated and the residue is updated to */
6890/* reflect the previous residue and the dropped digits. */
6891/* status is the status accumulator, as usual */
6892/* */
6893/* The coefficient may already be in the number, or it can be an */
6894/* external intermediate array. If it is in the number, lsu must == */
6895/* dn->lsu and len must == dn->digits. */
6896/* */
6897/* Note that the coefficient length (len) may be < set->digits, and */
6898/* in this case this merely copies the coefficient (or is a no-op */
6899/* if dn->lsu==lsu). */
6900/* */
6901/* Note also that (only internally, from decQuantizeOp and */
6902/* decSetSubnormal) the value of set->digits may be less than one, */
6903/* indicating a round to left. This routine handles that case */
6904/* correctly; caller ensures space. */
6905/* */
6906/* dn->digits, dn->lsu (and as required), and dn->exponent are */
6907/* updated as necessary. dn->bits (sign) is unchanged. */
6908/* */
6909/* DEC_Rounded status is set if any digits are discarded. */
6910/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6911/* incoming residue was non-0 (implies rounded) */
6912/* ------------------------------------------------------------------ */
6913/* mapping array: maps 0-9 to canonical residues, so that a residue */
6914/* can be adjusted in the range [-1, +1] and achieve correct rounding */
6915/* 0 1 2 3 4 5 6 7 8 9 */
6916static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6917static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6918 Int len, Int *residue, uInt *status) {
6919 Int discard; /* number of digits to discard */
6920 uInt cut; /* cut point in Unit */
6921 const Unit *up; /* work */
6922 Unit *target; /* .. */
6923 Int count; /* .. */
6924 #if DECDPUN<=4
6925 uInt temp; /* .. */
6926 #endif
6927
6928 discard=len-set->digits; /* digits to discard */
6929 if (discard<=0) { /* no digits are being discarded */
6930 if (dn->lsu!=lsu) { /* copy needed */
6931 /* copy the coefficient array to the result number; no shift needed */
6932 count=len; /* avoids D2U */
6933 up=lsu;
6934 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6935 *target=*up;
6936 dn->digits=len; /* set the new length */
6937 }
6938 /* dn->exponent and residue are unchanged, record any inexactitude */
6939 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6940 return;
6941 }
6942
6943 /* some digits must be discarded ... */
6944 dn->exponent+=discard; /* maintain numerical value */
6945 *status|=DEC_Rounded; /* accumulate Rounded status */
6946 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6947
6948 if (discard>len) { /* everything, +1, is being discarded */
6949 /* guard digit is 0 */
6950 /* residue is all the number [NB could be all 0s] */
6951 if (*residue<=0) { /* not already positive */
6952 count=len; /* avoids D2U */
6953 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6954 *residue=1;
6955 break; /* no need to check any others */
6956 }
6957 }
6958 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6959 *dn->lsu=0; /* coefficient will now be 0 */
6960 dn->digits=1; /* .. */
6961 return;
6962 } /* total discard */
6963
6964 /* partial discard [most common case] */
6965 /* here, at least the first (most significant) discarded digit exists */
6966
6967 /* spin up the number, noting residue during the spin, until get to */
6968 /* the Unit with the first discarded digit. When reach it, extract */
6969 /* it and remember its position */
6970 count=0;
6971 for (up=lsu;; up++) {
6972 count+=DECDPUN;
6973 if (count>=discard) break; /* full ones all checked */
6974 if (*up!=0) *residue=1;
6975 } /* up */
6976
6977 /* here up -> Unit with first discarded digit */
6978 cut=discard-(count-DECDPUN)-1;
6979 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
6980 Unit half=(Unit)powers[DECDPUN]>>1;
6981 /* set residue directly */
6982 if (*up>=half) {
6983 if (*up>half) *residue=7;
6984 else *residue+=5; /* add sticky bit */
6985 }
6986 else { /* <half */
6987 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
6988 }
6989 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
6990 *dn->lsu=0; /* .. result is 0 */
6991 dn->digits=1; /* .. */
6992 }
6993 else { /* shift to least */
6994 count=set->digits; /* now digits to end up with */
6995 dn->digits=count; /* set the new length */
6996 up++; /* move to next */
6997 /* on unit boundary, so shift-down copy loop is simple */
6998 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6999 *target=*up;
7000 }
7001 } /* unit-boundary case */
7002
7003 else { /* discard digit is in low digit(s), and not top digit */
7004 uInt discard1; /* first discarded digit */
7005 uInt quot, rem; /* for divisions */
7006 if (cut==0) quot=*up; /* is at bottom of unit */
7007 else /* cut>0 */ { /* it's not at bottom of unit */
7008 #if DECDPUN<=4
4388f060 7009 U_ASSERT(cut >= 0 && cut <= 4);
729e4ab9
A
7010 quot=QUOT10(*up, cut);
7011 rem=*up-quot*powers[cut];
7012 #else
7013 rem=*up%powers[cut];
7014 quot=*up/powers[cut];
7015 #endif
7016 if (rem!=0) *residue=1;
7017 }
7018 /* discard digit is now at bottom of quot */
7019 #if DECDPUN<=4
7020 temp=(quot*6554)>>16; /* fast /10 */
7021 /* Vowels algorithm here not a win (9 instructions) */
7022 discard1=quot-X10(temp);
7023 quot=temp;
7024 #else
7025 discard1=quot%10;
7026 quot=quot/10;
7027 #endif
7028 /* here, discard1 is the guard digit, and residue is everything */
7029 /* else [use mapping array to accumulate residue safely] */
7030 *residue+=resmap[discard1];
7031 cut++; /* update cut */
7032 /* here: up -> Unit of the array with bottom digit */
7033 /* cut is the division point for each Unit */
7034 /* quot holds the uncut high-order digits for the current unit */
7035 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7036 *dn->lsu=0; /* .. result is 0 */
7037 dn->digits=1; /* .. */
7038 }
7039 else { /* shift to least needed */
7040 count=set->digits; /* now digits to end up with */
7041 dn->digits=count; /* set the new length */
7042 /* shift-copy the coefficient array to the result number */
7043 for (target=dn->lsu; ; target++) {
7044 *target=(Unit)quot;
7045 count-=(DECDPUN-cut);
7046 if (count<=0) break;
7047 up++;
7048 quot=*up;
7049 #if DECDPUN<=4
7050 quot=QUOT10(quot, cut);
7051 rem=*up-quot*powers[cut];
7052 #else
7053 rem=quot%powers[cut];
7054 quot=quot/powers[cut];
7055 #endif
7056 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7057 count-=cut;
7058 if (count<=0) break;
7059 } /* shift-copy loop */
7060 } /* shift to least */
7061 } /* not unit boundary */
7062
7063 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7064 return;
7065 } /* decSetCoeff */
7066
7067/* ------------------------------------------------------------------ */
7068/* decApplyRound -- apply pending rounding to a number */
7069/* */
7070/* dn is the number, with space for set->digits digits */
7071/* set is the context [for size and rounding mode] */
7072/* residue indicates pending rounding, being any accumulated */
7073/* guard and sticky information. It may be: */
7074/* 6-9: rounding digit is >5 */
7075/* 5: rounding digit is exactly half-way */
7076/* 1-4: rounding digit is <5 and >0 */
7077/* 0: the coefficient is exact */
7078/* -1: as 1, but the hidden digits are subtractive, that */
7079/* is, of the opposite sign to dn. In this case the */
7080/* coefficient must be non-0. This case occurs when */
7081/* subtracting a small number (which can be reduced to */
7082/* a sticky bit); see decAddOp. */
7083/* status is the status accumulator, as usual */
7084/* */
7085/* This routine applies rounding while keeping the length of the */
7086/* coefficient constant. The exponent and status are unchanged */
7087/* except if: */
7088/* */
7089/* -- the coefficient was increased and is all nines (in which */
7090/* case Overflow could occur, and is handled directly here so */
7091/* the caller does not need to re-test for overflow) */
7092/* */
7093/* -- the coefficient was decreased and becomes all nines (in which */
7094/* case Underflow could occur, and is also handled directly). */
7095/* */
7096/* All fields in dn are updated as required. */
7097/* */
7098/* ------------------------------------------------------------------ */
7099static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7100 uInt *status) {
7101 Int bump; /* 1 if coefficient needs to be incremented */
7102 /* -1 if coefficient needs to be decremented */
7103
7104 if (residue==0) return; /* nothing to apply */
7105
7106 bump=0; /* assume a smooth ride */
7107
7108 /* now decide whether, and how, to round, depending on mode */
7109 switch (set->round) {
7110 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
7111 /* This is the same as DEC_ROUND_DOWN unless there is a */
7112 /* positive residue and the lsd of dn is 0 or 5, in which case */
7113 /* it is bumped; when residue is <0, the number is therefore */
7114 /* bumped down unless the final digit was 1 or 6 (in which */
7115 /* case it is bumped down and then up -- a no-op) */
7116 Int lsd5=*dn->lsu%5; /* get lsd and quintate */
7117 if (residue<0 && lsd5!=1) bump=-1;
7118 else if (residue>0 && lsd5==0) bump=1;
7119 /* [bump==1 could be applied directly; use common path for clarity] */
7120 break;} /* r-05 */
7121
7122 case DEC_ROUND_DOWN: {
7123 /* no change, except if negative residue */
7124 if (residue<0) bump=-1;
7125 break;} /* r-d */
7126
7127 case DEC_ROUND_HALF_DOWN: {
7128 if (residue>5) bump=1;
7129 break;} /* r-h-d */
7130
7131 case DEC_ROUND_HALF_EVEN: {
7132 if (residue>5) bump=1; /* >0.5 goes up */
7133 else if (residue==5) { /* exactly 0.5000... */
7134 /* 0.5 goes up iff [new] lsd is odd */
7135 if (*dn->lsu & 0x01) bump=1;
7136 }
7137 break;} /* r-h-e */
7138
7139 case DEC_ROUND_HALF_UP: {
7140 if (residue>=5) bump=1;
7141 break;} /* r-h-u */
7142
7143 case DEC_ROUND_UP: {
7144 if (residue>0) bump=1;
7145 break;} /* r-u */
7146
7147 case DEC_ROUND_CEILING: {
7148 /* same as _UP for positive numbers, and as _DOWN for negatives */
7149 /* [negative residue cannot occur on 0] */
7150 if (decNumberIsNegative(dn)) {
7151 if (residue<0) bump=-1;
7152 }
7153 else {
7154 if (residue>0) bump=1;
7155 }
7156 break;} /* r-c */
7157
7158 case DEC_ROUND_FLOOR: {
7159 /* same as _UP for negative numbers, and as _DOWN for positive */
7160 /* [negative residue cannot occur on 0] */
7161 if (!decNumberIsNegative(dn)) {
7162 if (residue<0) bump=-1;
7163 }
7164 else {
7165 if (residue>0) bump=1;
7166 }
7167 break;} /* r-f */
7168
7169 default: { /* e.g., DEC_ROUND_MAX */
7170 *status|=DEC_Invalid_context;
7171 #if DECTRACE || (DECCHECK && DECVERB)
7172 printf("Unknown rounding mode: %d\n", set->round);
7173 #endif
7174 break;}
7175 } /* switch */
7176
7177 /* now bump the number, up or down, if need be */
7178 if (bump==0) return; /* no action required */
7179
7180 /* Simply use decUnitAddSub unless bumping up and the number is */
7181 /* all nines. In this special case set to 100... explicitly */
7182 /* and adjust the exponent by one (as otherwise could overflow */
7183 /* the array) */
7184 /* Similarly handle all-nines result if bumping down. */
7185 if (bump>0) {
7186 Unit *up; /* work */
7187 uInt count=dn->digits; /* digits to be checked */
7188 for (up=dn->lsu; ; up++) {
7189 if (count<=DECDPUN) {
7190 /* this is the last Unit (the msu) */
7191 if (*up!=powers[count]-1) break; /* not still 9s */
7192 /* here if it, too, is all nines */
7193 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
7194 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7195 dn->exponent++; /* and bump exponent */
7196 /* [which, very rarely, could cause Overflow...] */
7197 if ((dn->exponent+dn->digits)>set->emax+1) {
7198 decSetOverflow(dn, set, status);
7199 }
7200 return; /* done */
7201 }
7202 /* a full unit to check, with more to come */
7203 if (*up!=DECDPUNMAX) break; /* not still 9s */
7204 count-=DECDPUN;
7205 } /* up */
7206 } /* bump>0 */
7207 else { /* -1 */
7208 /* here checking for a pre-bump of 1000... (leading 1, all */
7209 /* other digits zero) */
7210 Unit *up, *sup; /* work */
7211 uInt count=dn->digits; /* digits to be checked */
7212 for (up=dn->lsu; ; up++) {
7213 if (count<=DECDPUN) {
7214 /* this is the last Unit (the msu) */
7215 if (*up!=powers[count-1]) break; /* not 100.. */
7216 /* here if have the 1000... case */
7217 sup=up; /* save msu pointer */
7218 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
7219 /* others all to all-nines, too */
7220 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7221 dn->exponent--; /* and bump exponent */
7222
7223 /* iff the number was at the subnormal boundary (exponent=etiny) */
7224 /* then the exponent is now out of range, so it will in fact get */
7225 /* clamped to etiny and the final 9 dropped. */
7226 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7227 /* dn->exponent, set->digits); */
7228 if (dn->exponent+1==set->emin-set->digits+1) {
7229 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
7230 else {
7231 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
7232 dn->digits--;
7233 }
7234 dn->exponent++;
7235 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7236 }
7237 return; /* done */
7238 }
7239
7240 /* a full unit to check, with more to come */
7241 if (*up!=0) break; /* not still 0s */
7242 count-=DECDPUN;
7243 } /* up */
7244
7245 } /* bump<0 */
7246
7247 /* Actual bump needed. Do it. */
7248 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7249 } /* decApplyRound */
7250
7251#if DECSUBSET
7252/* ------------------------------------------------------------------ */
7253/* decFinish -- finish processing a number */
7254/* */
7255/* dn is the number */
7256/* set is the context */
7257/* residue is the rounding accumulator (as in decApplyRound) */
7258/* status is the accumulator */
7259/* */
7260/* This finishes off the current number by: */
7261/* 1. If not extended: */
7262/* a. Converting a zero result to clean '0' */
7263/* b. Reducing positive exponents to 0, if would fit in digits */
7264/* 2. Checking for overflow and subnormals (always) */
7265/* Note this is just Finalize when no subset arithmetic. */
7266/* All fields are updated as required. */
7267/* ------------------------------------------------------------------ */
7268static void decFinish(decNumber *dn, decContext *set, Int *residue,
7269 uInt *status) {
7270 if (!set->extended) {
7271 if ISZERO(dn) { /* value is zero */
7272 dn->exponent=0; /* clean exponent .. */
7273 dn->bits=0; /* .. and sign */
7274 return; /* no error possible */
7275 }
7276 if (dn->exponent>=0) { /* non-negative exponent */
7277 /* >0; reduce to integer if possible */
7278 if (set->digits >= (dn->exponent+dn->digits)) {
7279 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7280 dn->exponent=0;
7281 }
7282 }
7283 } /* !extended */
7284
7285 decFinalize(dn, set, residue, status);
7286 } /* decFinish */
7287#endif
7288
7289/* ------------------------------------------------------------------ */
7290/* decFinalize -- final check, clamp, and round of a number */
7291/* */
7292/* dn is the number */
7293/* set is the context */
7294/* residue is the rounding accumulator (as in decApplyRound) */
7295/* status is the status accumulator */
7296/* */
7297/* This finishes off the current number by checking for subnormal */
7298/* results, applying any pending rounding, checking for overflow, */
7299/* and applying any clamping. */
7300/* Underflow and overflow conditions are raised as appropriate. */
7301/* All fields are updated as required. */
7302/* ------------------------------------------------------------------ */
7303static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7304 uInt *status) {
7305 Int shift; /* shift needed if clamping */
7306 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
7307
7308 /* Must be careful, here, when checking the exponent as the */
7309 /* adjusted exponent could overflow 31 bits [because it may already */
7310 /* be up to twice the expected]. */
7311
7312 /* First test for subnormal. This must be done before any final */
7313 /* round as the result could be rounded to Nmin or 0. */
7314 if (dn->exponent<=tinyexp) { /* prefilter */
7315 Int comp;
7316 decNumber nmin;
7317 /* A very nasty case here is dn == Nmin and residue<0 */
7318 if (dn->exponent<tinyexp) {
7319 /* Go handle subnormals; this will apply round if needed. */
7320 decSetSubnormal(dn, set, residue, status);
7321 return;
7322 }
7323 /* Equals case: only subnormal if dn=Nmin and negative residue */
7324 uprv_decNumberZero(&nmin);
7325 nmin.lsu[0]=1;
7326 nmin.exponent=set->emin;
7327 comp=decCompare(dn, &nmin, 1); /* (signless compare) */
7328 if (comp==BADINT) { /* oops */
7329 *status|=DEC_Insufficient_storage; /* abandon... */
7330 return;
7331 }
7332 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
7333 decApplyRound(dn, set, *residue, status); /* might force down */
7334 decSetSubnormal(dn, set, residue, status);
7335 return;
7336 }
7337 }
7338
7339 /* now apply any pending round (this could raise overflow). */
7340 if (*residue!=0) decApplyRound(dn, set, *residue, status);
7341
7342 /* Check for overflow [redundant in the 'rare' case] or clamp */
7343 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
7344
7345
7346 /* here when might have an overflow or clamp to do */
7347 if (dn->exponent>set->emax-dn->digits+1) { /* too big */
7348 decSetOverflow(dn, set, status);
7349 return;
7350 }
7351 /* here when the result is normal but in clamp range */
7352 if (!set->clamp) return;
7353
7354 /* here when need to apply the IEEE exponent clamp (fold-down) */
7355 shift=dn->exponent-(set->emax-set->digits+1);
7356
7357 /* shift coefficient (if non-zero) */
7358 if (!ISZERO(dn)) {
7359 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7360 }
7361 dn->exponent-=shift; /* adjust the exponent to match */
7362 *status|=DEC_Clamped; /* and record the dirty deed */
7363 return;
7364 } /* decFinalize */
7365
7366/* ------------------------------------------------------------------ */
7367/* decSetOverflow -- set number to proper overflow value */
7368/* */
7369/* dn is the number (used for sign [only] and result) */
7370/* set is the context [used for the rounding mode, etc.] */
7371/* status contains the current status to be updated */
7372/* */
7373/* This sets the sign of a number and sets its value to either */
7374/* Infinity or the maximum finite value, depending on the sign of */
7375/* dn and the rounding mode, following IEEE 754 rules. */
7376/* ------------------------------------------------------------------ */
7377static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7378 Flag needmax=0; /* result is maximum finite value */
7379 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
7380
7381 if (ISZERO(dn)) { /* zero does not overflow magnitude */
7382 Int emax=set->emax; /* limit value */
7383 if (set->clamp) emax-=set->digits-1; /* lower if clamping */
7384 if (dn->exponent>emax) { /* clamp required */
7385 dn->exponent=emax;
7386 *status|=DEC_Clamped;
7387 }
7388 return;
7389 }
7390
7391 uprv_decNumberZero(dn);
7392 switch (set->round) {
7393 case DEC_ROUND_DOWN: {
7394 needmax=1; /* never Infinity */
7395 break;} /* r-d */
7396 case DEC_ROUND_05UP: {
7397 needmax=1; /* never Infinity */
7398 break;} /* r-05 */
7399 case DEC_ROUND_CEILING: {
7400 if (sign) needmax=1; /* Infinity if non-negative */
7401 break;} /* r-c */
7402 case DEC_ROUND_FLOOR: {
7403 if (!sign) needmax=1; /* Infinity if negative */
7404 break;} /* r-f */
7405 default: break; /* Infinity in all other cases */
7406 }
7407 if (needmax) {
7408 decSetMaxValue(dn, set);
7409 dn->bits=sign; /* set sign */
7410 }
7411 else dn->bits=sign|DECINF; /* Value is +/-Infinity */
7412 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7413 } /* decSetOverflow */
7414
7415/* ------------------------------------------------------------------ */
7416/* decSetMaxValue -- set number to +Nmax (maximum normal value) */
7417/* */
7418/* dn is the number to set */
7419/* set is the context [used for digits and emax] */
7420/* */
7421/* This sets the number to the maximum positive value. */
7422/* ------------------------------------------------------------------ */
7423static void decSetMaxValue(decNumber *dn, decContext *set) {
7424 Unit *up; /* work */
7425 Int count=set->digits; /* nines to add */
7426 dn->digits=count;
7427 /* fill in all nines to set maximum value */
7428 for (up=dn->lsu; ; up++) {
7429 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
7430 else { /* this is the msu */
7431 *up=(Unit)(powers[count]-1);
7432 break;
7433 }
7434 count-=DECDPUN; /* filled those digits */
7435 } /* up */
7436 dn->bits=0; /* + sign */
7437 dn->exponent=set->emax-set->digits+1;
7438 } /* decSetMaxValue */
7439
7440/* ------------------------------------------------------------------ */
7441/* decSetSubnormal -- process value whose exponent is <Emin */
7442/* */
7443/* dn is the number (used as input as well as output; it may have */
7444/* an allowed subnormal value, which may need to be rounded) */
7445/* set is the context [used for the rounding mode] */
7446/* residue is any pending residue */
7447/* status contains the current status to be updated */
7448/* */
7449/* If subset mode, set result to zero and set Underflow flags. */
7450/* */
7451/* Value may be zero with a low exponent; this does not set Subnormal */
7452/* but the exponent will be clamped to Etiny. */
7453/* */
7454/* Otherwise ensure exponent is not out of range, and round as */
7455/* necessary. Underflow is set if the result is Inexact. */
7456/* ------------------------------------------------------------------ */
7457static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7458 uInt *status) {
7459 decContext workset; /* work */
7460 Int etiny, adjust; /* .. */
7461
7462 #if DECSUBSET
7463 /* simple set to zero and 'hard underflow' for subset */
7464 if (!set->extended) {
7465 uprv_decNumberZero(dn);
7466 /* always full overflow */
7467 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7468 return;
7469 }
7470 #endif
7471
7472 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7473 /* (Etiny) if needed */
7474 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
7475
7476 if ISZERO(dn) { /* value is zero */
7477 /* residue can never be non-zero here */
7478 #if DECCHECK
7479 if (*residue!=0) {
7480 printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7481 *status|=DEC_Invalid_operation;
7482 }
7483 #endif
7484 if (dn->exponent<etiny) { /* clamp required */
7485 dn->exponent=etiny;
7486 *status|=DEC_Clamped;
7487 }
7488 return;
7489 }
7490
7491 *status|=DEC_Subnormal; /* have a non-zero subnormal */
7492 adjust=etiny-dn->exponent; /* calculate digits to remove */
7493 if (adjust<=0) { /* not out of range; unrounded */
7494 /* residue can never be non-zero here, except in the Nmin-residue */
7495 /* case (which is a subnormal result), so can take fast-path here */
7496 /* it may already be inexact (from setting the coefficient) */
7497 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7498 return;
7499 }
7500
7501 /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7502 /* [this code is similar to that in rescale] */
7503 workset=*set; /* clone rounding, etc. */
7504 workset.digits=dn->digits-adjust; /* set requested length */
7505 workset.emin-=adjust; /* and adjust emin to match */
7506 /* [note that the latter can be <1, here, similar to Rescale case] */
7507 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7508 decApplyRound(dn, &workset, *residue, status);
7509
7510 /* Use 754 default rule: Underflow is set iff Inexact */
7511 /* [independent of whether trapped] */
7512 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7513
7514 /* if rounded up a 999s case, exponent will be off by one; adjust */
7515 /* back if so [it will fit, because it was shortened earlier] */
7516 if (dn->exponent>etiny) {
7517 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7518 dn->exponent--; /* (re)adjust the exponent. */
7519 }
7520
7521 /* if rounded to zero, it is by definition clamped... */
7522 if (ISZERO(dn)) *status|=DEC_Clamped;
7523 } /* decSetSubnormal */
7524
7525/* ------------------------------------------------------------------ */
7526/* decCheckMath - check entry conditions for a math function */
7527/* */
7528/* This checks the context and the operand */
7529/* */
7530/* rhs is the operand to check */
7531/* set is the context to check */
7532/* status is unchanged if both are good */
7533/* */
7534/* returns non-zero if status is changed, 0 otherwise */
7535/* */
7536/* Restrictions enforced: */
7537/* */
7538/* digits, emax, and -emin in the context must be less than */
7539/* DEC_MAX_MATH (999999), and A must be within these bounds if */
7540/* non-zero. Invalid_operation is set in the status if a */
7541/* restriction is violated. */
7542/* ------------------------------------------------------------------ */
7543static uInt decCheckMath(const decNumber *rhs, decContext *set,
7544 uInt *status) {
7545 uInt save=*status; /* record */
7546 if (set->digits>DEC_MAX_MATH
7547 || set->emax>DEC_MAX_MATH
7548 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7549 else if ((rhs->digits>DEC_MAX_MATH
7550 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7551 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7552 && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7553 return (*status!=save);
7554 } /* decCheckMath */
7555
7556/* ------------------------------------------------------------------ */
7557/* decGetInt -- get integer from a number */
7558/* */
7559/* dn is the number [which will not be altered] */
7560/* */
7561/* returns one of: */
7562/* BADINT if there is a non-zero fraction */
7563/* the converted integer */
7564/* BIGEVEN if the integer is even and magnitude > 2*10**9 */
7565/* BIGODD if the integer is odd and magnitude > 2*10**9 */
7566/* */
7567/* This checks and gets a whole number from the input decNumber. */
7568/* The sign can be determined from dn by the caller when BIGEVEN or */
7569/* BIGODD is returned. */
7570/* ------------------------------------------------------------------ */
7571static Int decGetInt(const decNumber *dn) {
7572 Int theInt; /* result accumulator */
7573 const Unit *up; /* work */
7574 Int got; /* digits (real or not) processed */
7575 Int ilength=dn->digits+dn->exponent; /* integral length */
7576 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
7577
7578 /* The number must be an integer that fits in 10 digits */
7579 /* Assert, here, that 10 is enough for any rescale Etiny */
7580 #if DEC_MAX_EMAX > 999999999
7581 #error GetInt may need updating [for Emax]
7582 #endif
7583 #if DEC_MIN_EMIN < -999999999
7584 #error GetInt may need updating [for Emin]
7585 #endif
7586 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
7587
7588 up=dn->lsu; /* ready for lsu */
7589 theInt=0; /* ready to accumulate */
7590 if (dn->exponent>=0) { /* relatively easy */
7591 /* no fractional part [usual]; allow for positive exponent */
7592 got=dn->exponent;
7593 }
7594 else { /* -ve exponent; some fractional part to check and discard */
7595 Int count=-dn->exponent; /* digits to discard */
7596 /* spin up whole units until reach the Unit with the unit digit */
7597 for (; count>=DECDPUN; up++) {
7598 if (*up!=0) return BADINT; /* non-zero Unit to discard */
7599 count-=DECDPUN;
7600 }
7601 if (count==0) got=0; /* [a multiple of DECDPUN] */
7602 else { /* [not multiple of DECDPUN] */
7603 Int rem; /* work */
7604 /* slice off fraction digits and check for non-zero */
7605 #if DECDPUN<=4
7606 theInt=QUOT10(*up, count);
7607 rem=*up-theInt*powers[count];
7608 #else
7609 rem=*up%powers[count]; /* slice off discards */
7610 theInt=*up/powers[count];
7611 #endif
7612 if (rem!=0) return BADINT; /* non-zero fraction */
7613 /* it looks good */
7614 got=DECDPUN-count; /* number of digits so far */
7615 up++; /* ready for next */
7616 }
7617 }
7618 /* now it's known there's no fractional part */
7619
7620 /* tricky code now, to accumulate up to 9.3 digits */
7621 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7622
7623 if (ilength<11) {
7624 Int save=theInt;
7625 /* collect any remaining unit(s) */
7626 for (; got<ilength; up++) {
7627 theInt+=*up*powers[got];
7628 got+=DECDPUN;
7629 }
7630 if (ilength==10) { /* need to check for wrap */
7631 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7632 /* [that test also disallows the BADINT result case] */
7633 else if (neg && theInt>1999999997) ilength=11;
7634 else if (!neg && theInt>999999999) ilength=11;
7635 if (ilength==11) theInt=save; /* restore correct low bit */
7636 }
7637 }
7638
7639 if (ilength>10) { /* too big */
7640 if (theInt&1) return BIGODD; /* bottom bit 1 */
7641 return BIGEVEN; /* bottom bit 0 */
7642 }
7643
7644 if (neg) theInt=-theInt; /* apply sign */
7645 return theInt;
7646 } /* decGetInt */
7647
7648/* ------------------------------------------------------------------ */
7649/* decDecap -- decapitate the coefficient of a number */
7650/* */
7651/* dn is the number to be decapitated */
7652/* drop is the number of digits to be removed from the left of dn; */
7653/* this must be <= dn->digits (if equal, the coefficient is */
7654/* set to 0) */
7655/* */
7656/* Returns dn; dn->digits will be <= the initial digits less drop */
7657/* (after removing drop digits there may be leading zero digits */
7658/* which will also be removed). Only dn->lsu and dn->digits change. */
7659/* ------------------------------------------------------------------ */
7660static decNumber *decDecap(decNumber *dn, Int drop) {
7661 Unit *msu; /* -> target cut point */
7662 Int cut; /* work */
7663 if (drop>=dn->digits) { /* losing the whole thing */
7664 #if DECCHECK
7665 if (drop>dn->digits)
7666 printf("decDecap called with drop>digits [%ld>%ld]\n",
7667 (LI)drop, (LI)dn->digits);
7668 #endif
7669 dn->lsu[0]=0;
7670 dn->digits=1;
7671 return dn;
7672 }
7673 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
7674 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
7675 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
7676 /* that may have left leading zero digits, so do a proper count... */
7677 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7678 return dn;
7679 } /* decDecap */
7680
7681/* ------------------------------------------------------------------ */
7682/* decBiStr -- compare string with pairwise options */
7683/* */
7684/* targ is the string to compare */
7685/* str1 is one of the strings to compare against (length may be 0) */
7686/* str2 is the other; it must be the same length as str1 */
7687/* */
7688/* returns 1 if strings compare equal, (that is, it is the same */
7689/* length as str1 and str2, and each character of targ is in either */
7690/* str1 or str2 in the corresponding position), or 0 otherwise */
7691/* */
7692/* This is used for generic caseless compare, including the awkward */
7693/* case of the Turkish dotted and dotless Is. Use as (for example): */
7694/* if (decBiStr(test, "mike", "MIKE")) ... */
7695/* ------------------------------------------------------------------ */
7696static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7697 for (;;targ++, str1++, str2++) {
7698 if (*targ!=*str1 && *targ!=*str2) return 0;
7699 /* *targ has a match in one (or both, if terminator) */
7700 if (*targ=='\0') break;
7701 } /* forever */
7702 return 1;
7703 } /* decBiStr */
7704
7705/* ------------------------------------------------------------------ */
7706/* decNaNs -- handle NaN operand or operands */
7707/* */
7708/* res is the result number */
7709/* lhs is the first operand */
7710/* rhs is the second operand, or NULL if none */
7711/* context is used to limit payload length */
7712/* status contains the current status */
7713/* returns res in case convenient */
7714/* */
7715/* Called when one or both operands is a NaN, and propagates the */
7716/* appropriate result to res. When an sNaN is found, it is changed */
7717/* to a qNaN and Invalid operation is set. */
7718/* ------------------------------------------------------------------ */
7719static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7720 const decNumber *rhs, decContext *set,
7721 uInt *status) {
7722 /* This decision tree ends up with LHS being the source pointer, */
7723 /* and status updated if need be */
7724 if (lhs->bits & DECSNAN)
7725 *status|=DEC_Invalid_operation | DEC_sNaN;
7726 else if (rhs==NULL);
7727 else if (rhs->bits & DECSNAN) {
7728 lhs=rhs;
7729 *status|=DEC_Invalid_operation | DEC_sNaN;
7730 }
7731 else if (lhs->bits & DECNAN);
7732 else lhs=rhs;
7733
7734 /* propagate the payload */
7735 if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy */
7736 else { /* too long */
7737 const Unit *ul;
7738 Unit *ur, *uresp1;
7739 /* copy safe number of units, then decapitate */
7740 res->bits=lhs->bits; /* need sign etc. */
7741 uresp1=res->lsu+D2U(set->digits);
7742 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7743 res->digits=D2U(set->digits)*DECDPUN;
7744 /* maybe still too long */
7745 if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7746 }
7747
7748 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
7749 res->bits|=DECNAN; /* .. preserving sign */
7750 res->exponent=0; /* clean exponent */
7751 /* [coefficient was copied/decapitated] */
7752 return res;
7753 } /* decNaNs */
7754
7755/* ------------------------------------------------------------------ */
7756/* decStatus -- apply non-zero status */
7757/* */
7758/* dn is the number to set if error */
7759/* status contains the current status (not yet in context) */
7760/* set is the context */
7761/* */
7762/* If the status is an error status, the number is set to a NaN, */
7763/* unless the error was an overflow, divide-by-zero, or underflow, */
7764/* in which case the number will have already been set. */
7765/* */
7766/* The context status is then updated with the new status. Note that */
7767/* this may raise a signal, so control may never return from this */
7768/* routine (hence resources must be recovered before it is called). */
7769/* ------------------------------------------------------------------ */
7770static void decStatus(decNumber *dn, uInt status, decContext *set) {
7771 if (status & DEC_NaNs) { /* error status -> NaN */
7772 /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7773 if (status & DEC_sNaN) status&=~DEC_sNaN;
7774 else {
7775 uprv_decNumberZero(dn); /* other error: clean throughout */
7776 dn->bits=DECNAN; /* and make a quiet NaN */
7777 }
7778 }
7779 uprv_decContextSetStatus(set, status); /* [may not return] */
7780 return;
7781 } /* decStatus */
7782
7783/* ------------------------------------------------------------------ */
7784/* decGetDigits -- count digits in a Units array */
7785/* */
7786/* uar is the Unit array holding the number (this is often an */
7787/* accumulator of some sort) */
7788/* len is the length of the array in units [>=1] */
7789/* */
7790/* returns the number of (significant) digits in the array */
7791/* */
7792/* All leading zeros are excluded, except the last if the array has */
7793/* only zero Units. */
7794/* ------------------------------------------------------------------ */
7795/* This may be called twice during some operations. */
7796static Int decGetDigits(Unit *uar, Int len) {
7797 Unit *up=uar+(len-1); /* -> msu */
7798 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
7799 #if DECDPUN>4
7800 uInt const *pow; /* work */
7801 #endif
7802 /* (at least 1 in final msu) */
7803 #if DECCHECK
7804 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7805 #endif
7806
7807 for (; up>=uar; up--) {
7808 if (*up==0) { /* unit is all 0s */
7809 if (digits==1) break; /* a zero has one digit */
7810 digits-=DECDPUN; /* adjust for 0 unit */
7811 continue;}
7812 /* found the first (most significant) non-zero Unit */
7813 #if DECDPUN>1 /* not done yet */
7814 if (*up<10) break; /* is 1-9 */
7815 digits++;
7816 #if DECDPUN>2 /* not done yet */
7817 if (*up<100) break; /* is 10-99 */
7818 digits++;
7819 #if DECDPUN>3 /* not done yet */
7820 if (*up<1000) break; /* is 100-999 */
7821 digits++;
7822 #if DECDPUN>4 /* count the rest ... */
7823 for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7824 #endif
7825 #endif
7826 #endif
7827 #endif
7828 break;
7829 } /* up */
7830 return digits;
7831 } /* decGetDigits */
7832
7833#if DECTRACE | DECCHECK
7834/* ------------------------------------------------------------------ */
7835/* decNumberShow -- display a number [debug aid] */
7836/* dn is the number to show */
7837/* */
7838/* Shows: sign, exponent, coefficient (msu first), digits */
7839/* or: sign, special-value */
7840/* ------------------------------------------------------------------ */
7841/* this is public so other modules can use it */
7842void uprv_decNumberShow(const decNumber *dn) {
7843 const Unit *up; /* work */
7844 uInt u, d; /* .. */
7845 Int cut; /* .. */
7846 char isign='+'; /* main sign */
7847 if (dn==NULL) {
7848 printf("NULL\n");
7849 return;}
7850 if (decNumberIsNegative(dn)) isign='-';
7851 printf(" >> %c ", isign);
7852 if (dn->bits&DECSPECIAL) { /* Is a special value */
7853 if (decNumberIsInfinite(dn)) printf("Infinity");
7854 else { /* a NaN */
7855 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
7856 else printf("NaN");
7857 }
7858 /* if coefficient and exponent are 0, no more to do */
7859 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7860 printf("\n");
7861 return;}
7862 /* drop through to report other information */
7863 printf(" ");
7864 }
7865
7866 /* now carefully display the coefficient */
7867 up=dn->lsu+D2U(dn->digits)-1; /* msu */
7868 printf("%ld", (LI)*up);
7869 for (up=up-1; up>=dn->lsu; up--) {
7870 u=*up;
7871 printf(":");
7872 for (cut=DECDPUN-1; cut>=0; cut--) {
7873 d=u/powers[cut];
7874 u-=d*powers[cut];
7875 printf("%ld", (LI)d);
7876 } /* cut */
7877 } /* up */
7878 if (dn->exponent!=0) {
7879 char esign='+';
7880 if (dn->exponent<0) esign='-';
7881 printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7882 }
7883 printf(" [%ld]\n", (LI)dn->digits);
7884 } /* decNumberShow */
7885#endif
7886
7887#if DECTRACE || DECCHECK
7888/* ------------------------------------------------------------------ */
7889/* decDumpAr -- display a unit array [debug/check aid] */
7890/* name is a single-character tag name */
7891/* ar is the array to display */
7892/* len is the length of the array in Units */
7893/* ------------------------------------------------------------------ */
7894static void decDumpAr(char name, const Unit *ar, Int len) {
7895 Int i;
7896 const char *spec;
7897 #if DECDPUN==9
7898 spec="%09d ";
7899 #elif DECDPUN==8
7900 spec="%08d ";
7901 #elif DECDPUN==7
7902 spec="%07d ";
7903 #elif DECDPUN==6
7904 spec="%06d ";
7905 #elif DECDPUN==5
7906 spec="%05d ";
7907 #elif DECDPUN==4
7908 spec="%04d ";
7909 #elif DECDPUN==3
7910 spec="%03d ";
7911 #elif DECDPUN==2
7912 spec="%02d ";
7913 #else
7914 spec="%d ";
7915 #endif
7916 printf(" :%c: ", name);
7917 for (i=len-1; i>=0; i--) {
7918 if (i==len-1) printf("%ld ", (LI)ar[i]);
7919 else printf(spec, ar[i]);
7920 }
7921 printf("\n");
7922 return;}
7923#endif
7924
7925#if DECCHECK
7926/* ------------------------------------------------------------------ */
7927/* decCheckOperands -- check operand(s) to a routine */
7928/* res is the result structure (not checked; it will be set to */
7929/* quiet NaN if error found (and it is not NULL)) */
7930/* lhs is the first operand (may be DECUNRESU) */
7931/* rhs is the second (may be DECUNUSED) */
7932/* set is the context (may be DECUNCONT) */
7933/* returns 0 if both operands, and the context are clean, or 1 */
7934/* otherwise (in which case the context will show an error, */
7935/* unless NULL). Note that res is not cleaned; caller should */
7936/* handle this so res=NULL case is safe. */
7937/* The caller is expected to abandon immediately if 1 is returned. */
7938/* ------------------------------------------------------------------ */
7939static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7940 const decNumber *rhs, decContext *set) {
7941 Flag bad=0;
7942 if (set==NULL) { /* oops; hopeless */
7943 #if DECTRACE || DECVERB
7944 printf("Reference to context is NULL.\n");
7945 #endif
7946 bad=1;
7947 return 1;}
7948 else if (set!=DECUNCONT
7949 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7950 bad=1;
7951 #if DECTRACE || DECVERB
7952 printf("Bad context [digits=%ld round=%ld].\n",
7953 (LI)set->digits, (LI)set->round);
7954 #endif
7955 }
7956 else {
7957 if (res==NULL) {
7958 bad=1;
7959 #if DECTRACE
7960 /* this one not DECVERB as standard tests include NULL */
7961 printf("Reference to result is NULL.\n");
7962 #endif
7963 }
7964 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7965 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7966 }
7967 if (bad) {
7968 if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7969 if (res!=DECUNRESU && res!=NULL) {
7970 uprv_decNumberZero(res);
7971 res->bits=DECNAN; /* qNaN */
7972 }
7973 }
7974 return bad;
7975 } /* decCheckOperands */
7976
7977/* ------------------------------------------------------------------ */
7978/* decCheckNumber -- check a number */
7979/* dn is the number to check */
7980/* returns 0 if the number is clean, or 1 otherwise */
7981/* */
7982/* The number is considered valid if it could be a result from some */
7983/* operation in some valid context. */
7984/* ------------------------------------------------------------------ */
7985static Flag decCheckNumber(const decNumber *dn) {
7986 const Unit *up; /* work */
7987 uInt maxuint; /* .. */
7988 Int ae, d, digits; /* .. */
7989 Int emin, emax; /* .. */
7990
7991 if (dn==NULL) { /* hopeless */
7992 #if DECTRACE
7993 /* this one not DECVERB as standard tests include NULL */
7994 printf("Reference to decNumber is NULL.\n");
7995 #endif
7996 return 1;}
7997
7998 /* check special values */
7999 if (dn->bits & DECSPECIAL) {
8000 if (dn->exponent!=0) {
8001 #if DECTRACE || DECVERB
8002 printf("Exponent %ld (not 0) for a special value [%02x].\n",
8003 (LI)dn->exponent, dn->bits);
8004 #endif
8005 return 1;}
8006
8007 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
8008 if (decNumberIsInfinite(dn)) {
8009 if (dn->digits!=1) {
8010 #if DECTRACE || DECVERB
8011 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8012 #endif
8013 return 1;}
8014 if (*dn->lsu!=0) {
8015 #if DECTRACE || DECVERB
8016 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8017 #endif
8018 decDumpAr('I', dn->lsu, D2U(dn->digits));
8019 return 1;}
8020 } /* Inf */
8021 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
8022 /* concrete formats (decimal64, etc.). */
8023 return 0;
8024 }
8025
8026 /* check the coefficient */
8027 if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8028 #if DECTRACE || DECVERB
8029 printf("Digits %ld in number.\n", (LI)dn->digits);
8030 #endif
8031 return 1;}
8032
8033 d=dn->digits;
8034
8035 for (up=dn->lsu; d>0; up++) {
8036 if (d>DECDPUN) maxuint=DECDPUNMAX;
8037 else { /* reached the msu */
8038 maxuint=powers[d]-1;
8039 if (dn->digits>1 && *up<powers[d-1]) {
8040 #if DECTRACE || DECVERB
8041 printf("Leading 0 in number.\n");
8042 uprv_decNumberShow(dn);
8043 #endif
8044 return 1;}
8045 }
8046 if (*up>maxuint) {
8047 #if DECTRACE || DECVERB
8048 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8049 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8050 #endif
8051 return 1;}
8052 d-=DECDPUN;
8053 }
8054
8055 /* check the exponent. Note that input operands can have exponents */
8056 /* which are out of the set->emin/set->emax and set->digits range */
8057 /* (just as they can have more digits than set->digits). */
8058 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
8059 emax=DECNUMMAXE;
8060 emin=DECNUMMINE;
8061 digits=DECNUMMAXP;
8062 if (ae<emin-(digits-1)) {
8063 #if DECTRACE || DECVERB
8064 printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8065 uprv_decNumberShow(dn);
8066 #endif
8067 return 1;}
8068 if (ae>+emax) {
8069 #if DECTRACE || DECVERB
8070 printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8071 uprv_decNumberShow(dn);
8072 #endif
8073 return 1;}
8074
8075 return 0; /* it's OK */
8076 } /* decCheckNumber */
8077
8078/* ------------------------------------------------------------------ */
8079/* decCheckInexact -- check a normal finite inexact result has digits */
8080/* dn is the number to check */
8081/* set is the context (for status and precision) */
8082/* sets Invalid operation, etc., if some digits are missing */
8083/* [this check is not made for DECSUBSET compilation or when */
8084/* subnormal is not set] */
8085/* ------------------------------------------------------------------ */
8086static void decCheckInexact(const decNumber *dn, decContext *set) {
8087 #if !DECSUBSET && DECEXTFLAG
8088 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8089 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8090 #if DECTRACE || DECVERB
8091 printf("Insufficient digits [%ld] on normal Inexact result.\n",
8092 (LI)dn->digits);
8093 uprv_decNumberShow(dn);
8094 #endif
8095 uprv_decContextSetStatus(set, DEC_Invalid_operation);
8096 }
8097 #else
8098 /* next is a noop for quiet compiler */
8099 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8100 #endif
8101 return;
8102 } /* decCheckInexact */
8103#endif
8104
8105#if DECALLOC
8106#undef malloc
8107#undef free
8108/* ------------------------------------------------------------------ */
8109/* decMalloc -- accountable allocation routine */
8110/* n is the number of bytes to allocate */
8111/* */
8112/* Semantics is the same as the stdlib malloc routine, but bytes */
8113/* allocated are accounted for globally, and corruption fences are */
8114/* added before and after the 'actual' storage. */
8115/* ------------------------------------------------------------------ */
8116/* This routine allocates storage with an extra twelve bytes; 8 are */
8117/* at the start and hold: */
8118/* 0-3 the original length requested */
8119/* 4-7 buffer corruption detection fence (DECFENCE, x4) */
8120/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8121/* ------------------------------------------------------------------ */
8122static void *decMalloc(size_t n) {
8123 uInt size=n+12; /* true size */
8124 void *alloc; /* -> allocated storage */
8125 uByte *b, *b0; /* work */
8126 uInt uiwork; /* for macros */
8127
8128 alloc=malloc(size); /* -> allocated storage */
8129 if (alloc==NULL) return NULL; /* out of strorage */
8130 b0=(uByte *)alloc; /* as bytes */
8131 decAllocBytes+=n; /* account for storage */
8132 UBFROMUI(alloc, n); /* save n */
8133 /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n); */
8134 for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8135 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8136 return b0+8; /* -> play area */
8137 } /* decMalloc */
8138
8139/* ------------------------------------------------------------------ */
8140/* decFree -- accountable free routine */
8141/* alloc is the storage to free */
8142/* */
8143/* Semantics is the same as the stdlib malloc routine, except that */
8144/* the global storage accounting is updated and the fences are */
8145/* checked to ensure that no routine has written 'out of bounds'. */
8146/* ------------------------------------------------------------------ */
8147/* This routine first checks that the fences have not been corrupted. */
8148/* It then frees the storage using the 'truw' storage address (that */
8149/* is, offset by 8). */
8150/* ------------------------------------------------------------------ */
8151static void decFree(void *alloc) {
8152 uInt n; /* original length */
8153 uByte *b, *b0; /* work */
8154 uInt uiwork; /* for macros */
8155
8156 if (alloc==NULL) return; /* allowed; it's a nop */
8157 b0=(uByte *)alloc; /* as bytes */
8158 b0-=8; /* -> true start of storage */
8159 n=UBTOUI(b0); /* lift length */
8160 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8161 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8162 b-b0-8, (LI)b0);
8163 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8164 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8165 b-b0-8, (LI)b0, (LI)n);
8166 free(b0); /* drop the storage */
8167 decAllocBytes-=n; /* account for storage */
8168 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8169 } /* decFree */
8170#define malloc(a) decMalloc(a)
8171#define free(a) decFree(a)
8172#endif