]> git.proxmox.com Git - mirror_qemu.git/blame - libdecnumber/decNumber.c
libdecnumber: Introduce decNumberFrom[U]Int64
[mirror_qemu.git] / libdecnumber / decNumber.c
CommitLineData
72ac97cd
TM
1/* Decimal number arithmetic module for the decNumber C Library.
2 Copyright (C) 2005, 2007 Free Software Foundation, Inc.
3 Contributed by IBM Corporation. Author Mike Cowlishaw.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 In addition to the permissions in the GNU General Public License,
13 the Free Software Foundation gives you unlimited permission to link
14 the compiled version of this file into combinations with other
15 programs, and to distribute those combinations without any
16 restriction coming from the use of this file. (The General Public
17 License restrictions do apply in other respects; for example, they
18 cover modification of the file, and distribution when not linked
19 into a combine executable.)
20
21 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22 WARRANTY; without even the implied warranty of MERCHANTABILITY or
23 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
24 for more details.
25
26 You should have received a copy of the GNU General Public License
27 along with GCC; see the file COPYING. If not, write to the Free
28 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29 02110-1301, USA. */
30
31/* ------------------------------------------------------------------ */
32/* Decimal Number arithmetic module */
33/* ------------------------------------------------------------------ */
34/* This module comprises the routines for General Decimal Arithmetic */
35/* as defined in the specification which may be found on the */
36/* http://www2.hursley.ibm.com/decimal web pages. It implements both */
37/* the full ('extended') arithmetic and the simpler ('subset') */
38/* arithmetic. */
39/* */
40/* Usage notes: */
41/* */
42/* 1. This code is ANSI C89 except: */
43/* */
44/* If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
45/* uint64_t types may be used. To avoid these, set DECUSE64=0 */
46/* and DECDPUN<=4 (see documentation). */
47/* */
48/* 2. The decNumber format which this library uses is optimized for */
49/* efficient processing of relatively short numbers; in particular */
50/* it allows the use of fixed sized structures and minimizes copy */
51/* and move operations. It does, however, support arbitrary */
52/* precision (up to 999,999,999 digits) and arbitrary exponent */
53/* range (Emax in the range 0 through 999,999,999 and Emin in the */
54/* range -999,999,999 through 0). Mathematical functions (for */
55/* example decNumberExp) as identified below are restricted more */
56/* tightly: digits, emax, and -emin in the context must be <= */
57/* DEC_MAX_MATH (999999), and their operand(s) must be within */
58/* these bounds. */
59/* */
60/* 3. Logical functions are further restricted; their operands must */
61/* be finite, positive, have an exponent of zero, and all digits */
62/* must be either 0 or 1. The result will only contain digits */
63/* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
64/* */
65/* 4. Operands to operator functions are never modified unless they */
66/* are also specified to be the result number (which is always */
67/* permitted). Other than that case, operands must not overlap. */
68/* */
69/* 5. Error handling: the type of the error is ORed into the status */
70/* flags in the current context (decContext structure). The */
71/* SIGFPE signal is then raised if the corresponding trap-enabler */
72/* flag in the decContext is set (is 1). */
73/* */
74/* It is the responsibility of the caller to clear the status */
75/* flags as required. */
76/* */
77/* The result of any routine which returns a number will always */
78/* be a valid number (which may be a special value, such as an */
79/* Infinity or NaN). */
80/* */
81/* 6. The decNumber format is not an exchangeable concrete */
82/* representation as it comprises fields which may be machine- */
83/* dependent (packed or unpacked, or special length, for example). */
84/* Canonical conversions to and from strings are provided; other */
85/* conversions are available in separate modules. */
86/* */
87/* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
88/* to 1 for extended operand checking (including NULL operands). */
89/* Results are undefined if a badly-formed structure (or a NULL */
90/* pointer to a structure) is provided, though with DECCHECK */
91/* enabled the operator routines are protected against exceptions. */
92/* (Except if the result pointer is NULL, which is unrecoverable.) */
93/* */
94/* However, the routines will never cause exceptions if they are */
95/* given well-formed operands, even if the value of the operands */
96/* is inappropriate for the operation and DECCHECK is not set. */
97/* (Except for SIGFPE, as and where documented.) */
98/* */
99/* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
100/* ------------------------------------------------------------------ */
101/* Implementation notes for maintenance of this module: */
102/* */
103/* 1. Storage leak protection: Routines which use malloc are not */
104/* permitted to use return for fastpath or error exits (i.e., */
105/* they follow strict structured programming conventions). */
106/* Instead they have a do{}while(0); construct surrounding the */
107/* code which is protected -- break may be used to exit this. */
108/* Other routines can safely use the return statement inline. */
109/* */
110/* Storage leak accounting can be enabled using DECALLOC. */
111/* */
112/* 2. All loops use the for(;;) construct. Any do construct does */
113/* not loop; it is for allocation protection as just described. */
114/* */
115/* 3. Setting status in the context must always be the very last */
116/* action in a routine, as non-0 status may raise a trap and hence */
117/* the call to set status may not return (if the handler uses long */
118/* jump). Therefore all cleanup must be done first. In general, */
119/* to achieve this status is accumulated and is only applied just */
120/* before return by calling decContextSetStatus (via decStatus). */
121/* */
122/* Routines which allocate storage cannot, in general, use the */
123/* 'top level' routines which could cause a non-returning */
124/* transfer of control. The decXxxxOp routines are safe (do not */
125/* call decStatus even if traps are set in the context) and should */
126/* be used instead (they are also a little faster). */
127/* */
128/* 4. Exponent checking is minimized by allowing the exponent to */
129/* grow outside its limits during calculations, provided that */
130/* the decFinalize function is called later. Multiplication and */
131/* division, and intermediate calculations in exponentiation, */
132/* require more careful checks because of the risk of 31-bit */
133/* overflow (the most negative valid exponent is -1999999997, for */
134/* a 999999999-digit number with adjusted exponent of -999999999). */
135/* */
136/* 5. Rounding is deferred until finalization of results, with any */
137/* 'off to the right' data being represented as a single digit */
138/* residue (in the range -1 through 9). This avoids any double- */
139/* rounding when more than one shortening takes place (for */
140/* example, when a result is subnormal). */
141/* */
142/* 6. The digits count is allowed to rise to a multiple of DECDPUN */
143/* during many operations, so whole Units are handled and exact */
144/* accounting of digits is not needed. The correct digits value */
145/* is found by decGetDigits, which accounts for leading zeros. */
146/* This must be called before any rounding if the number of digits */
147/* is not known exactly. */
148/* */
149/* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
150/* numbers up to four digits, using appropriate constants. This */
151/* is not useful for longer numbers because overflow of 32 bits */
152/* would lead to 4 multiplies, which is almost as expensive as */
153/* a divide (unless a floating-point or 64-bit multiply is */
154/* assumed to be available). */
155/* */
156/* 8. Unusual abbreviations that may be used in the commentary: */
157/* lhs -- left hand side (operand, of an operation) */
158/* lsd -- least significant digit (of coefficient) */
159/* lsu -- least significant Unit (of coefficient) */
160/* msd -- most significant digit (of coefficient) */
161/* msi -- most significant item (in an array) */
162/* msu -- most significant Unit (of coefficient) */
163/* rhs -- right hand side (operand, of an operation) */
164/* +ve -- positive */
165/* -ve -- negative */
166/* ** -- raise to the power */
167/* ------------------------------------------------------------------ */
168
169#include <stdlib.h> /* for malloc, free, etc. */
170#include <stdio.h> /* for printf [if needed] */
171#include <string.h> /* for strcpy */
172#include <ctype.h> /* for lower */
0f2d3732
TM
173#include "libdecnumber/dconfig.h"
174#include "libdecnumber/decNumber.h"
175#include "libdecnumber/decNumberLocal.h"
72ac97cd
TM
176
177/* Constants */
178/* Public lookup table used by the D2U macro */
179const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
180
181#define DECVERB 1 /* set to 1 for verbose DECCHECK */
182#define powers DECPOWERS /* old internal name */
183
184/* Local constants */
185#define DIVIDE 0x80 /* Divide operators */
186#define REMAINDER 0x40 /* .. */
187#define DIVIDEINT 0x20 /* .. */
188#define REMNEAR 0x10 /* .. */
189#define COMPARE 0x01 /* Compare operators */
190#define COMPMAX 0x02 /* .. */
191#define COMPMIN 0x03 /* .. */
192#define COMPTOTAL 0x04 /* .. */
193#define COMPNAN 0x05 /* .. [NaN processing] */
194#define COMPSIG 0x06 /* .. [signaling COMPARE] */
195#define COMPMAXMAG 0x07 /* .. */
196#define COMPMINMAG 0x08 /* .. */
197
198#define DEC_sNaN 0x40000000 /* local status: sNaN signal */
199#define BADINT (Int)0x80000000 /* most-negative Int; error indicator */
200/* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
201#define BIGEVEN (Int)0x80000002
202#define BIGODD (Int)0x80000003
203
204static Unit uarrone[1]={1}; /* Unit array of 1, used for incrementing */
205
206/* Granularity-dependent code */
207#if DECDPUN<=4
208 #define eInt Int /* extended integer */
209 #define ueInt uInt /* unsigned extended integer */
210 /* Constant multipliers for divide-by-power-of five using reciprocal */
211 /* multiply, after removing powers of 2 by shifting, and final shift */
212 /* of 17 [we only need up to **4] */
213 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
214 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
215 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
216#else
217 /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
218 #if !DECUSE64
219 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
220 #endif
221 #define eInt Long /* extended integer */
222 #define ueInt uLong /* unsigned extended integer */
223#endif
224
225/* Local routines */
226static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
227 decContext *, uByte, uInt *);
228static Flag decBiStr(const char *, const char *, const char *);
229static uInt decCheckMath(const decNumber *, decContext *, uInt *);
230static void decApplyRound(decNumber *, decContext *, Int, uInt *);
231static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
232static decNumber * decCompareOp(decNumber *, const decNumber *,
233 const decNumber *, decContext *,
234 Flag, uInt *);
235static void decCopyFit(decNumber *, const decNumber *, decContext *,
236 Int *, uInt *);
237static decNumber * decDecap(decNumber *, Int);
238static decNumber * decDivideOp(decNumber *, const decNumber *,
239 const decNumber *, decContext *, Flag, uInt *);
240static decNumber * decExpOp(decNumber *, const decNumber *,
241 decContext *, uInt *);
242static void decFinalize(decNumber *, decContext *, Int *, uInt *);
243static Int decGetDigits(Unit *, Int);
244static Int decGetInt(const decNumber *);
245static decNumber * decLnOp(decNumber *, const decNumber *,
246 decContext *, uInt *);
247static decNumber * decMultiplyOp(decNumber *, const decNumber *,
248 const decNumber *, decContext *,
249 uInt *);
250static decNumber * decNaNs(decNumber *, const decNumber *,
251 const decNumber *, decContext *, uInt *);
252static decNumber * decQuantizeOp(decNumber *, const decNumber *,
253 const decNumber *, decContext *, Flag,
254 uInt *);
255static void decReverse(Unit *, Unit *);
256static void decSetCoeff(decNumber *, decContext *, const Unit *,
257 Int, Int *, uInt *);
258static void decSetMaxValue(decNumber *, decContext *);
259static void decSetOverflow(decNumber *, decContext *, uInt *);
260static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
261static Int decShiftToLeast(Unit *, Int, Int);
262static Int decShiftToMost(Unit *, Int, Int);
263static void decStatus(decNumber *, uInt, decContext *);
264static void decToString(const decNumber *, char[], Flag);
265static decNumber * decTrim(decNumber *, decContext *, Flag, Int *);
266static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
267 Unit *, Int);
268static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
269
270#if !DECSUBSET
271/* decFinish == decFinalize when no subset arithmetic needed */
272#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
273#else
274static void decFinish(decNumber *, decContext *, Int *, uInt *);
275static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
276#endif
277
278/* Local macros */
279/* masked special-values bits */
280#define SPECIALARG (rhs->bits & DECSPECIAL)
281#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
282
283/* Diagnostic macros, etc. */
284#if DECALLOC
285/* Handle malloc/free accounting. If enabled, our accountable routines */
286/* are used; otherwise the code just goes straight to the system malloc */
287/* and free routines. */
288#define malloc(a) decMalloc(a)
289#define free(a) decFree(a)
290#define DECFENCE 0x5a /* corruption detector */
291/* 'Our' malloc and free: */
292static void *decMalloc(size_t);
293static void decFree(void *);
294uInt decAllocBytes=0; /* count of bytes allocated */
295/* Note that DECALLOC code only checks for storage buffer overflow. */
296/* To check for memory leaks, the decAllocBytes variable must be */
297/* checked to be 0 at appropriate times (e.g., after the test */
298/* harness completes a set of tests). This checking may be unreliable */
299/* if the testing is done in a multi-thread environment. */
300#endif
301
302#if DECCHECK
303/* Optional checking routines. Enabling these means that decNumber */
304/* and decContext operands to operator routines are checked for */
305/* correctness. This roughly doubles the execution time of the */
306/* fastest routines (and adds 600+ bytes), so should not normally be */
307/* used in 'production'. */
308/* decCheckInexact is used to check that inexact results have a full */
309/* complement of digits (where appropriate -- this is not the case */
310/* for Quantize, for example) */
311#define DECUNRESU ((decNumber *)(void *)0xffffffff)
312#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
313#define DECUNCONT ((decContext *)(void *)(0xffffffff))
314static Flag decCheckOperands(decNumber *, const decNumber *,
315 const decNumber *, decContext *);
316static Flag decCheckNumber(const decNumber *);
317static void decCheckInexact(const decNumber *, decContext *);
318#endif
319
320#if DECTRACE || DECCHECK
321/* Optional trace/debugging routines (may or may not be used) */
322void decNumberShow(const decNumber *); /* displays the components of a number */
323static void decDumpAr(char, const Unit *, Int);
324#endif
325
326/* ================================================================== */
327/* Conversions */
328/* ================================================================== */
329
330/* ------------------------------------------------------------------ */
331/* from-int32 -- conversion from Int or uInt */
332/* */
333/* dn is the decNumber to receive the integer */
334/* in or uin is the integer to be converted */
335/* returns dn */
336/* */
337/* No error is possible. */
338/* ------------------------------------------------------------------ */
339decNumber * decNumberFromInt32(decNumber *dn, Int in) {
340 uInt unsig;
341 if (in>=0) unsig=in;
342 else { /* negative (possibly BADINT) */
343 if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
344 else unsig=-in; /* invert */
345 }
346 /* in is now positive */
347 decNumberFromUInt32(dn, unsig);
348 if (in<0) dn->bits=DECNEG; /* sign needed */
349 return dn;
350 } /* decNumberFromInt32 */
351
352decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
353 Unit *up; /* work pointer */
354 decNumberZero(dn); /* clean */
355 if (uin==0) return dn; /* [or decGetDigits bad call] */
356 for (up=dn->lsu; uin>0; up++) {
357 *up=(Unit)(uin%(DECDPUNMAX+1));
358 uin=uin/(DECDPUNMAX+1);
359 }
360 dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
361 return dn;
362 } /* decNumberFromUInt32 */
363
364/* ------------------------------------------------------------------ */
365/* to-int32 -- conversion to Int or uInt */
366/* */
367/* dn is the decNumber to convert */
368/* set is the context for reporting errors */
369/* returns the converted decNumber, or 0 if Invalid is set */
370/* */
371/* Invalid is set if the decNumber does not have exponent==0 or if */
372/* it is a NaN, Infinite, or out-of-range. */
373/* ------------------------------------------------------------------ */
374Int decNumberToInt32(const decNumber *dn, decContext *set) {
375 #if DECCHECK
376 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
377 #endif
378
379 /* special or too many digits, or bad exponent */
380 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
381 else { /* is a finite integer with 10 or fewer digits */
382 Int d; /* work */
383 const Unit *up; /* .. */
384 uInt hi=0, lo; /* .. */
385 up=dn->lsu; /* -> lsu */
386 lo=*up; /* get 1 to 9 digits */
387 #if DECDPUN>1 /* split to higher */
388 hi=lo/10;
389 lo=lo%10;
390 #endif
391 up++;
392 /* collect remaining Units, if any, into hi */
393 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
394 /* now low has the lsd, hi the remainder */
395 if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
396 /* most-negative is a reprieve */
397 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
398 /* bad -- drop through */
399 }
400 else { /* in-range always */
401 Int i=X10(hi)+lo;
402 if (dn->bits&DECNEG) return -i;
403 return i;
404 }
405 } /* integer */
406 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
407 return 0;
408 } /* decNumberToInt32 */
409
410uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
411 #if DECCHECK
412 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
413 #endif
414 /* special or too many digits, or bad exponent, or negative (<0) */
415 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
416 || (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
417 else { /* is a finite integer with 10 or fewer digits */
418 Int d; /* work */
419 const Unit *up; /* .. */
420 uInt hi=0, lo; /* .. */
421 up=dn->lsu; /* -> lsu */
422 lo=*up; /* get 1 to 9 digits */
423 #if DECDPUN>1 /* split to higher */
424 hi=lo/10;
425 lo=lo%10;
426 #endif
427 up++;
428 /* collect remaining Units, if any, into hi */
429 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
430
431 /* now low has the lsd, hi the remainder */
432 if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
433 else return X10(hi)+lo;
434 } /* integer */
435 decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
436 return 0;
437 } /* decNumberToUInt32 */
438
8e706db2
TM
439decNumber *decNumberFromInt64(decNumber *dn, int64_t in)
440{
441 uint64_t unsig = in;
442 if (in < 0) {
443 unsig = -unsig;
444 }
445
446 decNumberFromUInt64(dn, unsig);
447 if (in < 0) {
448 dn->bits = DECNEG; /* sign needed */
449 }
450 return dn;
451} /* decNumberFromInt64 */
452
453decNumber *decNumberFromUInt64(decNumber *dn, uint64_t uin)
454{
455 Unit *up; /* work pointer */
456 decNumberZero(dn); /* clean */
457 if (uin == 0) {
458 return dn; /* [or decGetDigits bad call] */
459 }
460 for (up = dn->lsu; uin > 0; up++) {
461 *up = (Unit)(uin % (DECDPUNMAX + 1));
462 uin = uin / (DECDPUNMAX + 1);
463 }
464 dn->digits = decGetDigits(dn->lsu, up-dn->lsu);
465 return dn;
466} /* decNumberFromUInt64 */
467
468
72ac97cd
TM
469/* ------------------------------------------------------------------ */
470/* to-scientific-string -- conversion to numeric string */
471/* to-engineering-string -- conversion to numeric string */
472/* */
473/* decNumberToString(dn, string); */
474/* decNumberToEngString(dn, string); */
475/* */
476/* dn is the decNumber to convert */
477/* string is the string where the result will be laid out */
478/* */
479/* string must be at least dn->digits+14 characters long */
480/* */
481/* No error is possible, and no status can be set. */
482/* ------------------------------------------------------------------ */
483char * decNumberToString(const decNumber *dn, char *string){
484 decToString(dn, string, 0);
485 return string;
486 } /* DecNumberToString */
487
488char * decNumberToEngString(const decNumber *dn, char *string){
489 decToString(dn, string, 1);
490 return string;
491 } /* DecNumberToEngString */
492
493/* ------------------------------------------------------------------ */
494/* to-number -- conversion from numeric string */
495/* */
496/* decNumberFromString -- convert string to decNumber */
497/* dn -- the number structure to fill */
498/* chars[] -- the string to convert ('\0' terminated) */
499/* set -- the context used for processing any error, */
500/* determining the maximum precision available */
501/* (set.digits), determining the maximum and minimum */
502/* exponent (set.emax and set.emin), determining if */
503/* extended values are allowed, and checking the */
504/* rounding mode if overflow occurs or rounding is */
505/* needed. */
506/* */
507/* The length of the coefficient and the size of the exponent are */
508/* checked by this routine, so the correct error (Underflow or */
509/* Overflow) can be reported or rounding applied, as necessary. */
510/* */
511/* If bad syntax is detected, the result will be a quiet NaN. */
512/* ------------------------------------------------------------------ */
513decNumber * decNumberFromString(decNumber *dn, const char chars[],
514 decContext *set) {
515 Int exponent=0; /* working exponent [assume 0] */
516 uByte bits=0; /* working flags [assume +ve] */
517 Unit *res; /* where result will be built */
518 Unit resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
519 /* [+9 allows for ln() constants] */
520 Unit *allocres=NULL; /* -> allocated result, iff allocated */
521 Int d=0; /* count of digits found in decimal part */
522 const char *dotchar=NULL; /* where dot was found */
523 const char *cfirst=chars; /* -> first character of decimal part */
524 const char *last=NULL; /* -> last digit of decimal part */
525 const char *c; /* work */
526 Unit *up; /* .. */
527 #if DECDPUN>1
528 Int cut, out; /* .. */
529 #endif
530 Int residue; /* rounding residue */
531 uInt status=0; /* error code */
532
533 #if DECCHECK
534 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
535 return decNumberZero(dn);
536 #endif
537
538 do { /* status & malloc protection */
539 for (c=chars;; c++) { /* -> input character */
540 if (*c>='0' && *c<='9') { /* test for Arabic digit */
541 last=c;
542 d++; /* count of real digits */
543 continue; /* still in decimal part */
544 }
545 if (*c=='.' && dotchar==NULL) { /* first '.' */
546 dotchar=c; /* record offset into decimal part */
547 if (c==cfirst) cfirst++; /* first digit must follow */
548 continue;}
549 if (c==chars) { /* first in string... */
550 if (*c=='-') { /* valid - sign */
551 cfirst++;
552 bits=DECNEG;
553 continue;}
554 if (*c=='+') { /* valid + sign */
555 cfirst++;
556 continue;}
557 }
558 /* *c is not a digit, or a valid +, -, or '.' */
559 break;
560 } /* c */
561
562 if (last==NULL) { /* no digits yet */
563 status=DEC_Conversion_syntax;/* assume the worst */
564 if (*c=='\0') break; /* and no more to come... */
565 #if DECSUBSET
566 /* if subset then infinities and NaNs are not allowed */
567 if (!set->extended) break; /* hopeless */
568 #endif
569 /* Infinities and NaNs are possible, here */
570 if (dotchar!=NULL) break; /* .. unless had a dot */
571 decNumberZero(dn); /* be optimistic */
572 if (decBiStr(c, "infinity", "INFINITY")
573 || decBiStr(c, "inf", "INF")) {
574 dn->bits=bits | DECINF;
575 status=0; /* is OK */
576 break; /* all done */
577 }
578 /* a NaN expected */
579 /* 2003.09.10 NaNs are now permitted to have a sign */
580 dn->bits=bits | DECNAN; /* assume simple NaN */
581 if (*c=='s' || *c=='S') { /* looks like an sNaN */
582 c++;
583 dn->bits=bits | DECSNAN;
584 }
585 if (*c!='n' && *c!='N') break; /* check caseless "NaN" */
586 c++;
587 if (*c!='a' && *c!='A') break; /* .. */
588 c++;
589 if (*c!='n' && *c!='N') break; /* .. */
590 c++;
591 /* now either nothing, or nnnn payload, expected */
592 /* -> start of integer and skip leading 0s [including plain 0] */
593 for (cfirst=c; *cfirst=='0';) cfirst++;
594 if (*cfirst=='\0') { /* "NaN" or "sNaN", maybe with all 0s */
595 status=0; /* it's good */
596 break; /* .. */
597 }
598 /* something other than 0s; setup last and d as usual [no dots] */
599 for (c=cfirst;; c++, d++) {
600 if (*c<'0' || *c>'9') break; /* test for Arabic digit */
601 last=c;
602 }
603 if (*c!='\0') break; /* not all digits */
604 if (d>set->digits-1) {
605 /* [NB: payload in a decNumber can be full length unless */
606 /* clamped, in which case can only be digits-1] */
607 if (set->clamp) break;
608 if (d>set->digits) break;
609 } /* too many digits? */
610 /* good; drop through to convert the integer to coefficient */
611 status=0; /* syntax is OK */
612 bits=dn->bits; /* for copy-back */
613 } /* last==NULL */
614
615 else if (*c!='\0') { /* more to process... */
616 /* had some digits; exponent is only valid sequence now */
617 Flag nege; /* 1=negative exponent */
618 const char *firstexp; /* -> first significant exponent digit */
619 status=DEC_Conversion_syntax;/* assume the worst */
620 if (*c!='e' && *c!='E') break;
621 /* Found 'e' or 'E' -- now process explicit exponent */
622 /* 1998.07.11: sign no longer required */
623 nege=0;
624 c++; /* to (possible) sign */
625 if (*c=='-') {nege=1; c++;}
626 else if (*c=='+') c++;
627 if (*c=='\0') break;
628
629 for (; *c=='0' && *(c+1)!='\0';) c++; /* strip insignificant zeros */
630 firstexp=c; /* save exponent digit place */
631 for (; ;c++) {
632 if (*c<'0' || *c>'9') break; /* not a digit */
633 exponent=X10(exponent)+(Int)*c-(Int)'0';
634 } /* c */
635 /* if not now on a '\0', *c must not be a digit */
636 if (*c!='\0') break;
637
638 /* (this next test must be after the syntax checks) */
639 /* if it was too long the exponent may have wrapped, so check */
640 /* carefully and set it to a certain overflow if wrap possible */
641 if (c>=firstexp+9+1) {
642 if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
643 /* [up to 1999999999 is OK, for example 1E-1000000998] */
644 }
645 if (nege) exponent=-exponent; /* was negative */
646 status=0; /* is OK */
647 } /* stuff after digits */
648
649 /* Here when whole string has been inspected; syntax is good */
650 /* cfirst->first digit (never dot), last->last digit (ditto) */
651
652 /* strip leading zeros/dot [leave final 0 if all 0's] */
653 if (*cfirst=='0') { /* [cfirst has stepped over .] */
654 for (c=cfirst; c<last; c++, cfirst++) {
655 if (*c=='.') continue; /* ignore dots */
656 if (*c!='0') break; /* non-zero found */
657 d--; /* 0 stripped */
658 } /* c */
659 #if DECSUBSET
660 /* make a rapid exit for easy zeros if !extended */
661 if (*cfirst=='0' && !set->extended) {
662 decNumberZero(dn); /* clean result */
663 break; /* [could be return] */
664 }
665 #endif
666 } /* at least one leading 0 */
667
668 /* Handle decimal point... */
669 if (dotchar!=NULL && dotchar<last) /* non-trailing '.' found? */
670 exponent-=(last-dotchar); /* adjust exponent */
671 /* [we can now ignore the .] */
672
673 /* OK, the digits string is good. Assemble in the decNumber, or in */
674 /* a temporary units array if rounding is needed */
675 if (d<=set->digits) res=dn->lsu; /* fits into supplied decNumber */
676 else { /* rounding needed */
677 Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
678 res=resbuff; /* assume use local buffer */
679 if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
680 allocres=(Unit *)malloc(needbytes);
681 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
682 res=allocres;
683 }
684 }
685 /* res now -> number lsu, buffer, or allocated storage for Unit array */
686
687 /* Place the coefficient into the selected Unit array */
688 /* [this is often 70% of the cost of this function when DECDPUN>1] */
689 #if DECDPUN>1
690 out=0; /* accumulator */
691 up=res+D2U(d)-1; /* -> msu */
692 cut=d-(up-res)*DECDPUN; /* digits in top unit */
693 for (c=cfirst;; c++) { /* along the digits */
694 if (*c=='.') continue; /* ignore '.' [don't decrement cut] */
695 out=X10(out)+(Int)*c-(Int)'0';
696 if (c==last) break; /* done [never get to trailing '.'] */
697 cut--;
698 if (cut>0) continue; /* more for this unit */
699 *up=(Unit)out; /* write unit */
700 up--; /* prepare for unit below.. */
701 cut=DECDPUN; /* .. */
702 out=0; /* .. */
703 } /* c */
704 *up=(Unit)out; /* write lsu */
705
706 #else
707 /* DECDPUN==1 */
708 up=res; /* -> lsu */
709 for (c=last; c>=cfirst; c--) { /* over each character, from least */
710 if (*c=='.') continue; /* ignore . [don't step up] */
711 *up=(Unit)((Int)*c-(Int)'0');
712 up++;
713 } /* c */
714 #endif
715
716 dn->bits=bits;
717 dn->exponent=exponent;
718 dn->digits=d;
719
720 /* if not in number (too long) shorten into the number */
721 if (d>set->digits) {
722 residue=0;
723 decSetCoeff(dn, set, res, d, &residue, &status);
724 /* always check for overflow or subnormal and round as needed */
725 decFinalize(dn, set, &residue, &status);
726 }
727 else { /* no rounding, but may still have overflow or subnormal */
728 /* [these tests are just for performance; finalize repeats them] */
729 if ((dn->exponent-1<set->emin-dn->digits)
730 || (dn->exponent-1>set->emax-set->digits)) {
731 residue=0;
732 decFinalize(dn, set, &residue, &status);
733 }
734 }
735 /* decNumberShow(dn); */
736 } while(0); /* [for break] */
737
738 if (allocres!=NULL) free(allocres); /* drop any storage used */
739 if (status!=0) decStatus(dn, status, set);
740 return dn;
741 } /* decNumberFromString */
742
743/* ================================================================== */
744/* Operators */
745/* ================================================================== */
746
747/* ------------------------------------------------------------------ */
748/* decNumberAbs -- absolute value operator */
749/* */
750/* This computes C = abs(A) */
751/* */
752/* res is C, the result. C may be A */
753/* rhs is A */
754/* set is the context */
755/* */
756/* See also decNumberCopyAbs for a quiet bitwise version of this. */
757/* C must have space for set->digits digits. */
758/* ------------------------------------------------------------------ */
759/* This has the same effect as decNumberPlus unless A is negative, */
760/* in which case it has the same effect as decNumberMinus. */
761/* ------------------------------------------------------------------ */
762decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
763 decContext *set) {
764 decNumber dzero; /* for 0 */
765 uInt status=0; /* accumulator */
766
767 #if DECCHECK
768 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
769 #endif
770
771 decNumberZero(&dzero); /* set 0 */
772 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
773 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
774 if (status!=0) decStatus(res, status, set);
775 #if DECCHECK
776 decCheckInexact(res, set);
777 #endif
778 return res;
779 } /* decNumberAbs */
780
781/* ------------------------------------------------------------------ */
782/* decNumberAdd -- add two Numbers */
783/* */
784/* This computes C = A + B */
785/* */
786/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
787/* lhs is A */
788/* rhs is B */
789/* set is the context */
790/* */
791/* C must have space for set->digits digits. */
792/* ------------------------------------------------------------------ */
793/* This just calls the routine shared with Subtract */
794decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
795 const decNumber *rhs, decContext *set) {
796 uInt status=0; /* accumulator */
797 decAddOp(res, lhs, rhs, set, 0, &status);
798 if (status!=0) decStatus(res, status, set);
799 #if DECCHECK
800 decCheckInexact(res, set);
801 #endif
802 return res;
803 } /* decNumberAdd */
804
805/* ------------------------------------------------------------------ */
806/* decNumberAnd -- AND two Numbers, digitwise */
807/* */
808/* This computes C = A & B */
809/* */
810/* res is C, the result. C may be A and/or B (e.g., X=X&X) */
811/* lhs is A */
812/* rhs is B */
813/* set is the context (used for result length and error report) */
814/* */
815/* C must have space for set->digits digits. */
816/* */
817/* Logical function restrictions apply (see above); a NaN is */
818/* returned with Invalid_operation if a restriction is violated. */
819/* ------------------------------------------------------------------ */
820decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
821 const decNumber *rhs, decContext *set) {
822 const Unit *ua, *ub; /* -> operands */
823 const Unit *msua, *msub; /* -> operand msus */
824 Unit *uc, *msuc; /* -> result and its msu */
825 Int msudigs; /* digits in res msu */
826 #if DECCHECK
827 if (decCheckOperands(res, lhs, rhs, set)) return res;
828 #endif
829
830 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
831 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
832 decStatus(res, DEC_Invalid_operation, set);
833 return res;
834 }
835
836 /* operands are valid */
837 ua=lhs->lsu; /* bottom-up */
838 ub=rhs->lsu; /* .. */
839 uc=res->lsu; /* .. */
840 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
841 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
842 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
843 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
844 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
845 Unit a, b; /* extract units */
846 if (ua>msua) a=0;
847 else a=*ua;
848 if (ub>msub) b=0;
849 else b=*ub;
850 *uc=0; /* can now write back */
851 if (a|b) { /* maybe 1 bits to examine */
852 Int i, j;
853 *uc=0; /* can now write back */
854 /* This loop could be unrolled and/or use BIN2BCD tables */
855 for (i=0; i<DECDPUN; i++) {
856 if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
857 j=a%10;
858 a=a/10;
859 j|=b%10;
860 b=b/10;
861 if (j>1) {
862 decStatus(res, DEC_Invalid_operation, set);
863 return res;
864 }
865 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
866 } /* each digit */
867 } /* both OK */
868 } /* each unit */
869 /* [here uc-1 is the msu of the result] */
870 res->digits=decGetDigits(res->lsu, uc-res->lsu);
871 res->exponent=0; /* integer */
872 res->bits=0; /* sign=0 */
873 return res; /* [no status to set] */
874 } /* decNumberAnd */
875
876/* ------------------------------------------------------------------ */
877/* decNumberCompare -- compare two Numbers */
878/* */
879/* This computes C = A ? B */
880/* */
881/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
882/* lhs is A */
883/* rhs is B */
884/* set is the context */
885/* */
886/* C must have space for one digit (or NaN). */
887/* ------------------------------------------------------------------ */
888decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
889 const decNumber *rhs, decContext *set) {
890 uInt status=0; /* accumulator */
891 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
892 if (status!=0) decStatus(res, status, set);
893 return res;
894 } /* decNumberCompare */
895
896/* ------------------------------------------------------------------ */
897/* decNumberCompareSignal -- compare, signalling on all NaNs */
898/* */
899/* This computes C = A ? B */
900/* */
901/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
902/* lhs is A */
903/* rhs is B */
904/* set is the context */
905/* */
906/* C must have space for one digit (or NaN). */
907/* ------------------------------------------------------------------ */
908decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
909 const decNumber *rhs, decContext *set) {
910 uInt status=0; /* accumulator */
911 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
912 if (status!=0) decStatus(res, status, set);
913 return res;
914 } /* decNumberCompareSignal */
915
916/* ------------------------------------------------------------------ */
917/* decNumberCompareTotal -- compare two Numbers, using total ordering */
918/* */
919/* This computes C = A ? B, under total ordering */
920/* */
921/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
922/* lhs is A */
923/* rhs is B */
924/* set is the context */
925/* */
926/* C must have space for one digit; the result will always be one of */
927/* -1, 0, or 1. */
928/* ------------------------------------------------------------------ */
929decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
930 const decNumber *rhs, decContext *set) {
931 uInt status=0; /* accumulator */
932 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
933 if (status!=0) decStatus(res, status, set);
934 return res;
935 } /* decNumberCompareTotal */
936
937/* ------------------------------------------------------------------ */
938/* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
939/* */
940/* This computes C = |A| ? |B|, under total ordering */
941/* */
942/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
943/* lhs is A */
944/* rhs is B */
945/* set is the context */
946/* */
947/* C must have space for one digit; the result will always be one of */
948/* -1, 0, or 1. */
949/* ------------------------------------------------------------------ */
950decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
951 const decNumber *rhs, decContext *set) {
952 uInt status=0; /* accumulator */
953 uInt needbytes; /* for space calculations */
954 decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
955 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
956 decNumber bufb[D2N(DECBUFFER+1)];
957 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
958 decNumber *a, *b; /* temporary pointers */
959
960 #if DECCHECK
961 if (decCheckOperands(res, lhs, rhs, set)) return res;
962 #endif
963
964 do { /* protect allocated storage */
965 /* if either is negative, take a copy and absolute */
966 if (decNumberIsNegative(lhs)) { /* lhs<0 */
967 a=bufa;
968 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
969 if (needbytes>sizeof(bufa)) { /* need malloc space */
970 allocbufa=(decNumber *)malloc(needbytes);
971 if (allocbufa==NULL) { /* hopeless -- abandon */
972 status|=DEC_Insufficient_storage;
973 break;}
974 a=allocbufa; /* use the allocated space */
975 }
976 decNumberCopy(a, lhs); /* copy content */
977 a->bits&=~DECNEG; /* .. and clear the sign */
978 lhs=a; /* use copy from here on */
979 }
980 if (decNumberIsNegative(rhs)) { /* rhs<0 */
981 b=bufb;
982 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
983 if (needbytes>sizeof(bufb)) { /* need malloc space */
984 allocbufb=(decNumber *)malloc(needbytes);
985 if (allocbufb==NULL) { /* hopeless -- abandon */
986 status|=DEC_Insufficient_storage;
987 break;}
988 b=allocbufb; /* use the allocated space */
989 }
990 decNumberCopy(b, rhs); /* copy content */
991 b->bits&=~DECNEG; /* .. and clear the sign */
992 rhs=b; /* use copy from here on */
993 }
994 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
995 } while(0); /* end protected */
996
997 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
998 if (allocbufb!=NULL) free(allocbufb); /* .. */
999 if (status!=0) decStatus(res, status, set);
1000 return res;
1001 } /* decNumberCompareTotalMag */
1002
1003/* ------------------------------------------------------------------ */
1004/* decNumberDivide -- divide one number by another */
1005/* */
1006/* This computes C = A / B */
1007/* */
1008/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
1009/* lhs is A */
1010/* rhs is B */
1011/* set is the context */
1012/* */
1013/* C must have space for set->digits digits. */
1014/* ------------------------------------------------------------------ */
1015decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
1016 const decNumber *rhs, decContext *set) {
1017 uInt status=0; /* accumulator */
1018 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1019 if (status!=0) decStatus(res, status, set);
1020 #if DECCHECK
1021 decCheckInexact(res, set);
1022 #endif
1023 return res;
1024 } /* decNumberDivide */
1025
1026/* ------------------------------------------------------------------ */
1027/* decNumberDivideInteger -- divide and return integer quotient */
1028/* */
1029/* This computes C = A # B, where # is the integer divide operator */
1030/* */
1031/* res is C, the result. C may be A and/or B (e.g., X=X#X) */
1032/* lhs is A */
1033/* rhs is B */
1034/* set is the context */
1035/* */
1036/* C must have space for set->digits digits. */
1037/* ------------------------------------------------------------------ */
1038decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1039 const decNumber *rhs, decContext *set) {
1040 uInt status=0; /* accumulator */
1041 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1042 if (status!=0) decStatus(res, status, set);
1043 return res;
1044 } /* decNumberDivideInteger */
1045
1046/* ------------------------------------------------------------------ */
1047/* decNumberExp -- exponentiation */
1048/* */
1049/* This computes C = exp(A) */
1050/* */
1051/* res is C, the result. C may be A */
1052/* rhs is A */
1053/* set is the context; note that rounding mode has no effect */
1054/* */
1055/* C must have space for set->digits digits. */
1056/* */
1057/* Mathematical function restrictions apply (see above); a NaN is */
1058/* returned with Invalid_operation if a restriction is violated. */
1059/* */
1060/* Finite results will always be full precision and Inexact, except */
1061/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1062/* */
1063/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1064/* almost always be correctly rounded, but may be up to 1 ulp in */
1065/* error in rare cases. */
1066/* ------------------------------------------------------------------ */
1067/* This is a wrapper for decExpOp which can handle the slightly wider */
1068/* (double) range needed by Ln (which has to be able to calculate */
1069/* exp(-a) where a can be the tiniest number (Ntiny). */
1070/* ------------------------------------------------------------------ */
1071decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1072 decContext *set) {
1073 uInt status=0; /* accumulator */
1074 #if DECSUBSET
1075 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1076 #endif
1077
1078 #if DECCHECK
1079 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1080 #endif
1081
1082 /* Check restrictions; these restrictions ensure that if h=8 (see */
1083 /* decExpOp) then the result will either overflow or underflow to 0. */
1084 /* Other math functions restrict the input range, too, for inverses. */
1085 /* If not violated then carry out the operation. */
1086 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1087 #if DECSUBSET
1088 if (!set->extended) {
1089 /* reduce operand and set lostDigits status, as needed */
1090 if (rhs->digits>set->digits) {
1091 allocrhs=decRoundOperand(rhs, set, &status);
1092 if (allocrhs==NULL) break;
1093 rhs=allocrhs;
1094 }
1095 }
1096 #endif
1097 decExpOp(res, rhs, set, &status);
1098 } while(0); /* end protected */
1099
1100 #if DECSUBSET
1101 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1102 #endif
1103 /* apply significant status */
1104 if (status!=0) decStatus(res, status, set);
1105 #if DECCHECK
1106 decCheckInexact(res, set);
1107 #endif
1108 return res;
1109 } /* decNumberExp */
1110
1111/* ------------------------------------------------------------------ */
1112/* decNumberFMA -- fused multiply add */
1113/* */
1114/* This computes D = (A * B) + C with only one rounding */
1115/* */
1116/* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1117/* lhs is A */
1118/* rhs is B */
1119/* fhs is C [far hand side] */
1120/* set is the context */
1121/* */
1122/* Mathematical function restrictions apply (see above); a NaN is */
1123/* returned with Invalid_operation if a restriction is violated. */
1124/* */
1125/* C must have space for set->digits digits. */
1126/* ------------------------------------------------------------------ */
1127decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1128 const decNumber *rhs, const decNumber *fhs,
1129 decContext *set) {
1130 uInt status=0; /* accumulator */
1131 decContext dcmul; /* context for the multiplication */
1132 uInt needbytes; /* for space calculations */
1133 decNumber bufa[D2N(DECBUFFER*2+1)];
1134 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1135 decNumber *acc; /* accumulator pointer */
1136 decNumber dzero; /* work */
1137
1138 #if DECCHECK
1139 if (decCheckOperands(res, lhs, rhs, set)) return res;
1140 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1141 #endif
1142
1143 do { /* protect allocated storage */
1144 #if DECSUBSET
1145 if (!set->extended) { /* [undefined if subset] */
1146 status|=DEC_Invalid_operation;
1147 break;}
1148 #endif
1149 /* Check math restrictions [these ensure no overflow or underflow] */
1150 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1151 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1152 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1153 /* set up context for multiply */
1154 dcmul=*set;
1155 dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1156 /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1157 dcmul.emax=DEC_MAX_EMAX; /* effectively unbounded .. */
1158 dcmul.emin=DEC_MIN_EMIN; /* [thanks to Math restrictions] */
1159 /* set up decNumber space to receive the result of the multiply */
1160 acc=bufa; /* may fit */
1161 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1162 if (needbytes>sizeof(bufa)) { /* need malloc space */
1163 allocbufa=(decNumber *)malloc(needbytes);
1164 if (allocbufa==NULL) { /* hopeless -- abandon */
1165 status|=DEC_Insufficient_storage;
1166 break;}
1167 acc=allocbufa; /* use the allocated space */
1168 }
1169 /* multiply with extended range and necessary precision */
1170 /*printf("emin=%ld\n", dcmul.emin); */
1171 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1172 /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1173 /* status; if either is seen than ignore fhs (in case it is */
1174 /* another sNaN) and set acc to NaN unless we had an sNaN */
1175 /* [decMultiplyOp leaves that to caller] */
1176 /* Note sNaN has to go through addOp to shorten payload if */
1177 /* necessary */
1178 if ((status&DEC_Invalid_operation)!=0) {
1179 if (!(status&DEC_sNaN)) { /* but be true invalid */
1180 decNumberZero(res); /* acc not yet set */
1181 res->bits=DECNAN;
1182 break;
1183 }
1184 decNumberZero(&dzero); /* make 0 (any non-NaN would do) */
1185 fhs=&dzero; /* use that */
1186 }
1187 #if DECCHECK
1188 else { /* multiply was OK */
1189 if (status!=0) printf("Status=%08lx after FMA multiply\n", status);
1190 }
1191 #endif
1192 /* add the third operand and result -> res, and all is done */
1193 decAddOp(res, acc, fhs, set, 0, &status);
1194 } while(0); /* end protected */
1195
1196 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1197 if (status!=0) decStatus(res, status, set);
1198 #if DECCHECK
1199 decCheckInexact(res, set);
1200 #endif
1201 return res;
1202 } /* decNumberFMA */
1203
1204/* ------------------------------------------------------------------ */
1205/* decNumberInvert -- invert a Number, digitwise */
1206/* */
1207/* This computes C = ~A */
1208/* */
1209/* res is C, the result. C may be A (e.g., X=~X) */
1210/* rhs is A */
1211/* set is the context (used for result length and error report) */
1212/* */
1213/* C must have space for set->digits digits. */
1214/* */
1215/* Logical function restrictions apply (see above); a NaN is */
1216/* returned with Invalid_operation if a restriction is violated. */
1217/* ------------------------------------------------------------------ */
1218decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1219 decContext *set) {
1220 const Unit *ua, *msua; /* -> operand and its msu */
1221 Unit *uc, *msuc; /* -> result and its msu */
1222 Int msudigs; /* digits in res msu */
1223 #if DECCHECK
1224 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1225 #endif
1226
1227 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1228 decStatus(res, DEC_Invalid_operation, set);
1229 return res;
1230 }
1231 /* operand is valid */
1232 ua=rhs->lsu; /* bottom-up */
1233 uc=res->lsu; /* .. */
1234 msua=ua+D2U(rhs->digits)-1; /* -> msu of rhs */
1235 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1236 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1237 for (; uc<=msuc; ua++, uc++) { /* Unit loop */
1238 Unit a; /* extract unit */
1239 Int i, j; /* work */
1240 if (ua>msua) a=0;
1241 else a=*ua;
1242 *uc=0; /* can now write back */
1243 /* always need to examine all bits in rhs */
1244 /* This loop could be unrolled and/or use BIN2BCD tables */
1245 for (i=0; i<DECDPUN; i++) {
1246 if ((~a)&1) *uc=*uc+(Unit)powers[i]; /* effect INVERT */
1247 j=a%10;
1248 a=a/10;
1249 if (j>1) {
1250 decStatus(res, DEC_Invalid_operation, set);
1251 return res;
1252 }
1253 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1254 } /* each digit */
1255 } /* each unit */
1256 /* [here uc-1 is the msu of the result] */
1257 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1258 res->exponent=0; /* integer */
1259 res->bits=0; /* sign=0 */
1260 return res; /* [no status to set] */
1261 } /* decNumberInvert */
1262
1263/* ------------------------------------------------------------------ */
1264/* decNumberLn -- natural logarithm */
1265/* */
1266/* This computes C = ln(A) */
1267/* */
1268/* res is C, the result. C may be A */
1269/* rhs is A */
1270/* set is the context; note that rounding mode has no effect */
1271/* */
1272/* C must have space for set->digits digits. */
1273/* */
1274/* Notable cases: */
1275/* A<0 -> Invalid */
1276/* A=0 -> -Infinity (Exact) */
1277/* A=+Infinity -> +Infinity (Exact) */
1278/* A=1 exactly -> 0 (Exact) */
1279/* */
1280/* Mathematical function restrictions apply (see above); a NaN is */
1281/* returned with Invalid_operation if a restriction is violated. */
1282/* */
1283/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1284/* almost always be correctly rounded, but may be up to 1 ulp in */
1285/* error in rare cases. */
1286/* ------------------------------------------------------------------ */
1287/* This is a wrapper for decLnOp which can handle the slightly wider */
1288/* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1289/* to calculate at p+e+2). */
1290/* ------------------------------------------------------------------ */
1291decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1292 decContext *set) {
1293 uInt status=0; /* accumulator */
1294 #if DECSUBSET
1295 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1296 #endif
1297
1298 #if DECCHECK
1299 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1300 #endif
1301
1302 /* Check restrictions; this is a math function; if not violated */
1303 /* then carry out the operation. */
1304 if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1305 #if DECSUBSET
1306 if (!set->extended) {
1307 /* reduce operand and set lostDigits status, as needed */
1308 if (rhs->digits>set->digits) {
1309 allocrhs=decRoundOperand(rhs, set, &status);
1310 if (allocrhs==NULL) break;
1311 rhs=allocrhs;
1312 }
1313 /* special check in subset for rhs=0 */
1314 if (ISZERO(rhs)) { /* +/- zeros -> error */
1315 status|=DEC_Invalid_operation;
1316 break;}
1317 } /* extended=0 */
1318 #endif
1319 decLnOp(res, rhs, set, &status);
1320 } while(0); /* end protected */
1321
1322 #if DECSUBSET
1323 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
1324 #endif
1325 /* apply significant status */
1326 if (status!=0) decStatus(res, status, set);
1327 #if DECCHECK
1328 decCheckInexact(res, set);
1329 #endif
1330 return res;
1331 } /* decNumberLn */
1332
1333/* ------------------------------------------------------------------ */
1334/* decNumberLogB - get adjusted exponent, by 754r rules */
1335/* */
1336/* This computes C = adjustedexponent(A) */
1337/* */
1338/* res is C, the result. C may be A */
1339/* rhs is A */
1340/* set is the context, used only for digits and status */
1341/* */
1342/* C must have space for 10 digits (A might have 10**9 digits and */
1343/* an exponent of +999999999, or one digit and an exponent of */
1344/* -1999999999). */
1345/* */
1346/* This returns the adjusted exponent of A after (in theory) padding */
1347/* with zeros on the right to set->digits digits while keeping the */
1348/* same value. The exponent is not limited by emin/emax. */
1349/* */
1350/* Notable cases: */
1351/* A<0 -> Use |A| */
1352/* A=0 -> -Infinity (Division by zero) */
1353/* A=Infinite -> +Infinity (Exact) */
1354/* A=1 exactly -> 0 (Exact) */
1355/* NaNs are propagated as usual */
1356/* ------------------------------------------------------------------ */
1357decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1358 decContext *set) {
1359 uInt status=0; /* accumulator */
1360
1361 #if DECCHECK
1362 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1363 #endif
1364
1365 /* NaNs as usual; Infinities return +Infinity; 0->oops */
1366 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1367 else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1368 else if (decNumberIsZero(rhs)) {
1369 decNumberZero(res); /* prepare for Infinity */
1370 res->bits=DECNEG|DECINF; /* -Infinity */
1371 status|=DEC_Division_by_zero; /* as per 754r */
1372 }
1373 else { /* finite non-zero */
1374 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1375 decNumberFromInt32(res, ae); /* lay it out */
1376 }
1377
1378 if (status!=0) decStatus(res, status, set);
1379 return res;
1380 } /* decNumberLogB */
1381
1382/* ------------------------------------------------------------------ */
1383/* decNumberLog10 -- logarithm in base 10 */
1384/* */
1385/* This computes C = log10(A) */
1386/* */
1387/* res is C, the result. C may be A */
1388/* rhs is A */
1389/* set is the context; note that rounding mode has no effect */
1390/* */
1391/* C must have space for set->digits digits. */
1392/* */
1393/* Notable cases: */
1394/* A<0 -> Invalid */
1395/* A=0 -> -Infinity (Exact) */
1396/* A=+Infinity -> +Infinity (Exact) */
1397/* A=10**n (if n is an integer) -> n (Exact) */
1398/* */
1399/* Mathematical function restrictions apply (see above); a NaN is */
1400/* returned with Invalid_operation if a restriction is violated. */
1401/* */
1402/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1403/* almost always be correctly rounded, but may be up to 1 ulp in */
1404/* error in rare cases. */
1405/* ------------------------------------------------------------------ */
1406/* This calculates ln(A)/ln(10) using appropriate precision. For */
1407/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1408/* requested digits and t is the number of digits in the exponent */
1409/* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1410/* fastpath in decLnOp. The final division is done to the requested */
1411/* precision. */
1412/* ------------------------------------------------------------------ */
1413decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1414 decContext *set) {
1415 uInt status=0, ignore=0; /* status accumulators */
1416 uInt needbytes; /* for space calculations */
1417 Int p; /* working precision */
1418 Int t; /* digits in exponent of A */
1419
1420 /* buffers for a and b working decimals */
1421 /* (adjustment calculator, same size) */
1422 decNumber bufa[D2N(DECBUFFER+2)];
1423 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
1424 decNumber *a=bufa; /* temporary a */
1425 decNumber bufb[D2N(DECBUFFER+2)];
1426 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
1427 decNumber *b=bufb; /* temporary b */
1428 decNumber bufw[D2N(10)]; /* working 2-10 digit number */
1429 decNumber *w=bufw; /* .. */
1430 #if DECSUBSET
1431 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
1432 #endif
1433
1434 decContext aset; /* working context */
1435
1436 #if DECCHECK
1437 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1438 #endif
1439
1440 /* Check restrictions; this is a math function; if not violated */
1441 /* then carry out the operation. */
1442 if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1443 #if DECSUBSET
1444 if (!set->extended) {
1445 /* reduce operand and set lostDigits status, as needed */
1446 if (rhs->digits>set->digits) {
1447 allocrhs=decRoundOperand(rhs, set, &status);
1448 if (allocrhs==NULL) break;
1449 rhs=allocrhs;
1450 }
1451 /* special check in subset for rhs=0 */
1452 if (ISZERO(rhs)) { /* +/- zeros -> error */
1453 status|=DEC_Invalid_operation;
1454 break;}
1455 } /* extended=0 */
1456 #endif
1457
1458 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1459
1460 /* handle exact powers of 10; only check if +ve finite */
1461 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1462 Int residue=0; /* (no residue) */
1463 uInt copystat=0; /* clean status */
1464
1465 /* round to a single digit... */
1466 aset.digits=1;
1467 decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1468 /* if exact and the digit is 1, rhs is a power of 10 */
1469 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1470 /* the exponent, conveniently, is the power of 10; making */
1471 /* this the result needs a little care as it might not fit, */
1472 /* so first convert it into the working number, and then move */
1473 /* to res */
1474 decNumberFromInt32(w, w->exponent);
1475 residue=0;
1476 decCopyFit(res, w, set, &residue, &status); /* copy & round */
1477 decFinish(res, set, &residue, &status); /* cleanup/set flags */
1478 break;
1479 } /* not a power of 10 */
1480 } /* not a candidate for exact */
1481
1482 /* simplify the information-content calculation to use 'total */
1483 /* number of digits in a, including exponent' as compared to the */
1484 /* requested digits, as increasing this will only rarely cost an */
1485 /* iteration in ln(a) anyway */
1486 t=6; /* it can never be >6 */
1487
1488 /* allocate space when needed... */
1489 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1490 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1491 if (needbytes>sizeof(bufa)) { /* need malloc space */
1492 allocbufa=(decNumber *)malloc(needbytes);
1493 if (allocbufa==NULL) { /* hopeless -- abandon */
1494 status|=DEC_Insufficient_storage;
1495 break;}
1496 a=allocbufa; /* use the allocated space */
1497 }
1498 aset.digits=p; /* as calculated */
1499 aset.emax=DEC_MAX_MATH; /* usual bounds */
1500 aset.emin=-DEC_MAX_MATH; /* .. */
1501 aset.clamp=0; /* and no concrete format */
1502 decLnOp(a, rhs, &aset, &status); /* a=ln(rhs) */
1503
1504 /* skip the division if the result so far is infinite, NaN, or */
1505 /* zero, or there was an error; note NaN from sNaN needs copy */
1506 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1507 if (a->bits&DECSPECIAL || ISZERO(a)) {
1508 decNumberCopy(res, a); /* [will fit] */
1509 break;}
1510
1511 /* for ln(10) an extra 3 digits of precision are needed */
1512 p=set->digits+3;
1513 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1514 if (needbytes>sizeof(bufb)) { /* need malloc space */
1515 allocbufb=(decNumber *)malloc(needbytes);
1516 if (allocbufb==NULL) { /* hopeless -- abandon */
1517 status|=DEC_Insufficient_storage;
1518 break;}
1519 b=allocbufb; /* use the allocated space */
1520 }
1521 decNumberZero(w); /* set up 10... */
1522 #if DECDPUN==1
1523 w->lsu[1]=1; w->lsu[0]=0; /* .. */
1524 #else
1525 w->lsu[0]=10; /* .. */
1526 #endif
1527 w->digits=2; /* .. */
1528
1529 aset.digits=p;
1530 decLnOp(b, w, &aset, &ignore); /* b=ln(10) */
1531
1532 aset.digits=set->digits; /* for final divide */
1533 decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1534 } while(0); /* [for break] */
1535
1536 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1537 if (allocbufb!=NULL) free(allocbufb); /* .. */
1538 #if DECSUBSET
1539 if (allocrhs !=NULL) free(allocrhs); /* .. */
1540 #endif
1541 /* apply significant status */
1542 if (status!=0) decStatus(res, status, set);
1543 #if DECCHECK
1544 decCheckInexact(res, set);
1545 #endif
1546 return res;
1547 } /* decNumberLog10 */
1548
1549/* ------------------------------------------------------------------ */
1550/* decNumberMax -- compare two Numbers and return the maximum */
1551/* */
1552/* This computes C = A ? B, returning the maximum by 754R rules */
1553/* */
1554/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1555/* lhs is A */
1556/* rhs is B */
1557/* set is the context */
1558/* */
1559/* C must have space for set->digits digits. */
1560/* ------------------------------------------------------------------ */
1561decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1562 const decNumber *rhs, decContext *set) {
1563 uInt status=0; /* accumulator */
1564 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1565 if (status!=0) decStatus(res, status, set);
1566 #if DECCHECK
1567 decCheckInexact(res, set);
1568 #endif
1569 return res;
1570 } /* decNumberMax */
1571
1572/* ------------------------------------------------------------------ */
1573/* decNumberMaxMag -- compare and return the maximum by magnitude */
1574/* */
1575/* This computes C = A ? B, returning the maximum by 754R rules */
1576/* */
1577/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1578/* lhs is A */
1579/* rhs is B */
1580/* set is the context */
1581/* */
1582/* C must have space for set->digits digits. */
1583/* ------------------------------------------------------------------ */
1584decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1585 const decNumber *rhs, decContext *set) {
1586 uInt status=0; /* accumulator */
1587 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1588 if (status!=0) decStatus(res, status, set);
1589 #if DECCHECK
1590 decCheckInexact(res, set);
1591 #endif
1592 return res;
1593 } /* decNumberMaxMag */
1594
1595/* ------------------------------------------------------------------ */
1596/* decNumberMin -- compare two Numbers and return the minimum */
1597/* */
1598/* This computes C = A ? B, returning the minimum by 754R rules */
1599/* */
1600/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1601/* lhs is A */
1602/* rhs is B */
1603/* set is the context */
1604/* */
1605/* C must have space for set->digits digits. */
1606/* ------------------------------------------------------------------ */
1607decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1608 const decNumber *rhs, decContext *set) {
1609 uInt status=0; /* accumulator */
1610 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1611 if (status!=0) decStatus(res, status, set);
1612 #if DECCHECK
1613 decCheckInexact(res, set);
1614 #endif
1615 return res;
1616 } /* decNumberMin */
1617
1618/* ------------------------------------------------------------------ */
1619/* decNumberMinMag -- compare and return the minimum by magnitude */
1620/* */
1621/* This computes C = A ? B, returning the minimum by 754R rules */
1622/* */
1623/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1624/* lhs is A */
1625/* rhs is B */
1626/* set is the context */
1627/* */
1628/* C must have space for set->digits digits. */
1629/* ------------------------------------------------------------------ */
1630decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1631 const decNumber *rhs, decContext *set) {
1632 uInt status=0; /* accumulator */
1633 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1634 if (status!=0) decStatus(res, status, set);
1635 #if DECCHECK
1636 decCheckInexact(res, set);
1637 #endif
1638 return res;
1639 } /* decNumberMinMag */
1640
1641/* ------------------------------------------------------------------ */
1642/* decNumberMinus -- prefix minus operator */
1643/* */
1644/* This computes C = 0 - A */
1645/* */
1646/* res is C, the result. C may be A */
1647/* rhs is A */
1648/* set is the context */
1649/* */
1650/* See also decNumberCopyNegate for a quiet bitwise version of this. */
1651/* C must have space for set->digits digits. */
1652/* ------------------------------------------------------------------ */
1653/* Simply use AddOp for the subtract, which will do the necessary. */
1654/* ------------------------------------------------------------------ */
1655decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1656 decContext *set) {
1657 decNumber dzero;
1658 uInt status=0; /* accumulator */
1659
1660 #if DECCHECK
1661 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1662 #endif
1663
1664 decNumberZero(&dzero); /* make 0 */
1665 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1666 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1667 if (status!=0) decStatus(res, status, set);
1668 #if DECCHECK
1669 decCheckInexact(res, set);
1670 #endif
1671 return res;
1672 } /* decNumberMinus */
1673
1674/* ------------------------------------------------------------------ */
1675/* decNumberNextMinus -- next towards -Infinity */
1676/* */
1677/* This computes C = A - infinitesimal, rounded towards -Infinity */
1678/* */
1679/* res is C, the result. C may be A */
1680/* rhs is A */
1681/* set is the context */
1682/* */
1683/* This is a generalization of 754r NextDown. */
1684/* ------------------------------------------------------------------ */
1685decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1686 decContext *set) {
1687 decNumber dtiny; /* constant */
1688 decContext workset=*set; /* work */
1689 uInt status=0; /* accumulator */
1690 #if DECCHECK
1691 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1692 #endif
1693
1694 /* +Infinity is the special case */
1695 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1696 decSetMaxValue(res, set); /* is +ve */
1697 /* there is no status to set */
1698 return res;
1699 }
1700 decNumberZero(&dtiny); /* start with 0 */
1701 dtiny.lsu[0]=1; /* make number that is .. */
1702 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1703 workset.round=DEC_ROUND_FLOOR;
1704 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1705 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1706 if (status!=0) decStatus(res, status, set);
1707 return res;
1708 } /* decNumberNextMinus */
1709
1710/* ------------------------------------------------------------------ */
1711/* decNumberNextPlus -- next towards +Infinity */
1712/* */
1713/* This computes C = A + infinitesimal, rounded towards +Infinity */
1714/* */
1715/* res is C, the result. C may be A */
1716/* rhs is A */
1717/* set is the context */
1718/* */
1719/* This is a generalization of 754r NextUp. */
1720/* ------------------------------------------------------------------ */
1721decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1722 decContext *set) {
1723 decNumber dtiny; /* constant */
1724 decContext workset=*set; /* work */
1725 uInt status=0; /* accumulator */
1726 #if DECCHECK
1727 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1728 #endif
1729
1730 /* -Infinity is the special case */
1731 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1732 decSetMaxValue(res, set);
1733 res->bits=DECNEG; /* negative */
1734 /* there is no status to set */
1735 return res;
1736 }
1737 decNumberZero(&dtiny); /* start with 0 */
1738 dtiny.lsu[0]=1; /* make number that is .. */
1739 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1740 workset.round=DEC_ROUND_CEILING;
1741 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1742 status&=DEC_Invalid_operation|DEC_sNaN; /* only sNaN Invalid please */
1743 if (status!=0) decStatus(res, status, set);
1744 return res;
1745 } /* decNumberNextPlus */
1746
1747/* ------------------------------------------------------------------ */
1748/* decNumberNextToward -- next towards rhs */
1749/* */
1750/* This computes C = A +/- infinitesimal, rounded towards */
1751/* +/-Infinity in the direction of B, as per 754r nextafter rules */
1752/* */
1753/* res is C, the result. C may be A or B. */
1754/* lhs is A */
1755/* rhs is B */
1756/* set is the context */
1757/* */
1758/* This is a generalization of 754r NextAfter. */
1759/* ------------------------------------------------------------------ */
1760decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1761 const decNumber *rhs, decContext *set) {
1762 decNumber dtiny; /* constant */
1763 decContext workset=*set; /* work */
1764 Int result; /* .. */
1765 uInt status=0; /* accumulator */
1766 #if DECCHECK
1767 if (decCheckOperands(res, lhs, rhs, set)) return res;
1768 #endif
1769
1770 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1771 decNaNs(res, lhs, rhs, set, &status);
1772 }
1773 else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1774 result=decCompare(lhs, rhs, 0); /* sign matters */
1775 if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1776 else { /* valid compare */
1777 if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */
1778 else { /* differ: need NextPlus or NextMinus */
1779 uByte sub; /* add or subtract */
1780 if (result<0) { /* lhs<rhs, do nextplus */
1781 /* -Infinity is the special case */
1782 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1783 decSetMaxValue(res, set);
1784 res->bits=DECNEG; /* negative */
1785 return res; /* there is no status to set */
1786 }
1787 workset.round=DEC_ROUND_CEILING;
1788 sub=0; /* add, please */
1789 } /* plus */
1790 else { /* lhs>rhs, do nextminus */
1791 /* +Infinity is the special case */
1792 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1793 decSetMaxValue(res, set);
1794 return res; /* there is no status to set */
1795 }
1796 workset.round=DEC_ROUND_FLOOR;
1797 sub=DECNEG; /* subtract, please */
1798 } /* minus */
1799 decNumberZero(&dtiny); /* start with 0 */
1800 dtiny.lsu[0]=1; /* make number that is .. */
1801 dtiny.exponent=DEC_MIN_EMIN-1; /* .. smaller than tiniest */
1802 decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1803 /* turn off exceptions if the result is a normal number */
1804 /* (including Nmin), otherwise let all status through */
1805 if (decNumberIsNormal(res, set)) status=0;
1806 } /* unequal */
1807 } /* compare OK */
1808 } /* numeric */
1809 if (status!=0) decStatus(res, status, set);
1810 return res;
1811 } /* decNumberNextToward */
1812
1813/* ------------------------------------------------------------------ */
1814/* decNumberOr -- OR two Numbers, digitwise */
1815/* */
1816/* This computes C = A | B */
1817/* */
1818/* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1819/* lhs is A */
1820/* rhs is B */
1821/* set is the context (used for result length and error report) */
1822/* */
1823/* C must have space for set->digits digits. */
1824/* */
1825/* Logical function restrictions apply (see above); a NaN is */
1826/* returned with Invalid_operation if a restriction is violated. */
1827/* ------------------------------------------------------------------ */
1828decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1829 const decNumber *rhs, decContext *set) {
1830 const Unit *ua, *ub; /* -> operands */
1831 const Unit *msua, *msub; /* -> operand msus */
1832 Unit *uc, *msuc; /* -> result and its msu */
1833 Int msudigs; /* digits in res msu */
1834 #if DECCHECK
1835 if (decCheckOperands(res, lhs, rhs, set)) return res;
1836 #endif
1837
1838 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1839 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1840 decStatus(res, DEC_Invalid_operation, set);
1841 return res;
1842 }
1843 /* operands are valid */
1844 ua=lhs->lsu; /* bottom-up */
1845 ub=rhs->lsu; /* .. */
1846 uc=res->lsu; /* .. */
1847 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
1848 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
1849 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
1850 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
1851 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
1852 Unit a, b; /* extract units */
1853 if (ua>msua) a=0;
1854 else a=*ua;
1855 if (ub>msub) b=0;
1856 else b=*ub;
1857 *uc=0; /* can now write back */
1858 if (a|b) { /* maybe 1 bits to examine */
1859 Int i, j;
1860 /* This loop could be unrolled and/or use BIN2BCD tables */
1861 for (i=0; i<DECDPUN; i++) {
1862 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; /* effect OR */
1863 j=a%10;
1864 a=a/10;
1865 j|=b%10;
1866 b=b/10;
1867 if (j>1) {
1868 decStatus(res, DEC_Invalid_operation, set);
1869 return res;
1870 }
1871 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
1872 } /* each digit */
1873 } /* non-zero */
1874 } /* each unit */
1875 /* [here uc-1 is the msu of the result] */
1876 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1877 res->exponent=0; /* integer */
1878 res->bits=0; /* sign=0 */
1879 return res; /* [no status to set] */
1880 } /* decNumberOr */
1881
1882/* ------------------------------------------------------------------ */
1883/* decNumberPlus -- prefix plus operator */
1884/* */
1885/* This computes C = 0 + A */
1886/* */
1887/* res is C, the result. C may be A */
1888/* rhs is A */
1889/* set is the context */
1890/* */
1891/* See also decNumberCopy for a quiet bitwise version of this. */
1892/* C must have space for set->digits digits. */
1893/* ------------------------------------------------------------------ */
1894/* This simply uses AddOp; Add will take fast path after preparing A. */
1895/* Performance is a concern here, as this routine is often used to */
1896/* check operands and apply rounding and overflow/underflow testing. */
1897/* ------------------------------------------------------------------ */
1898decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1899 decContext *set) {
1900 decNumber dzero;
1901 uInt status=0; /* accumulator */
1902 #if DECCHECK
1903 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1904 #endif
1905
1906 decNumberZero(&dzero); /* make 0 */
1907 dzero.exponent=rhs->exponent; /* [no coefficient expansion] */
1908 decAddOp(res, &dzero, rhs, set, 0, &status);
1909 if (status!=0) decStatus(res, status, set);
1910 #if DECCHECK
1911 decCheckInexact(res, set);
1912 #endif
1913 return res;
1914 } /* decNumberPlus */
1915
1916/* ------------------------------------------------------------------ */
1917/* decNumberMultiply -- multiply two Numbers */
1918/* */
1919/* This computes C = A x B */
1920/* */
1921/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1922/* lhs is A */
1923/* rhs is B */
1924/* set is the context */
1925/* */
1926/* C must have space for set->digits digits. */
1927/* ------------------------------------------------------------------ */
1928decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1929 const decNumber *rhs, decContext *set) {
1930 uInt status=0; /* accumulator */
1931 decMultiplyOp(res, lhs, rhs, set, &status);
1932 if (status!=0) decStatus(res, status, set);
1933 #if DECCHECK
1934 decCheckInexact(res, set);
1935 #endif
1936 return res;
1937 } /* decNumberMultiply */
1938
1939/* ------------------------------------------------------------------ */
1940/* decNumberPower -- raise a number to a power */
1941/* */
1942/* This computes C = A ** B */
1943/* */
1944/* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1945/* lhs is A */
1946/* rhs is B */
1947/* set is the context */
1948/* */
1949/* C must have space for set->digits digits. */
1950/* */
1951/* Mathematical function restrictions apply (see above); a NaN is */
1952/* returned with Invalid_operation if a restriction is violated. */
1953/* */
1954/* However, if 1999999997<=B<=999999999 and B is an integer then the */
1955/* restrictions on A and the context are relaxed to the usual bounds, */
1956/* for compatibility with the earlier (integer power only) version */
1957/* of this function. */
1958/* */
1959/* When B is an integer, the result may be exact, even if rounded. */
1960/* */
1961/* The final result is rounded according to the context; it will */
1962/* almost always be correctly rounded, but may be up to 1 ulp in */
1963/* error in rare cases. */
1964/* ------------------------------------------------------------------ */
1965decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1966 const decNumber *rhs, decContext *set) {
1967 #if DECSUBSET
1968 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
1969 decNumber *allocrhs=NULL; /* .., rhs */
1970 #endif
1971 decNumber *allocdac=NULL; /* -> allocated acc buffer, iff used */
1972 decNumber *allocinv=NULL; /* -> allocated 1/x buffer, iff used */
1973 Int reqdigits=set->digits; /* requested DIGITS */
1974 Int n; /* rhs in binary */
1975 Flag rhsint=0; /* 1 if rhs is an integer */
1976 Flag useint=0; /* 1 if can use integer calculation */
1977 Flag isoddint=0; /* 1 if rhs is an integer and odd */
1978 Int i; /* work */
1979 #if DECSUBSET
1980 Int dropped; /* .. */
1981 #endif
1982 uInt needbytes; /* buffer size needed */
1983 Flag seenbit; /* seen a bit while powering */
1984 Int residue=0; /* rounding residue */
1985 uInt status=0; /* accumulators */
1986 uByte bits=0; /* result sign if errors */
1987 decContext aset; /* working context */
1988 decNumber dnOne; /* work value 1... */
1989 /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1990 decNumber dacbuff[D2N(DECBUFFER+9)];
1991 decNumber *dac=dacbuff; /* -> result accumulator */
1992 /* same again for possible 1/lhs calculation */
1993 decNumber invbuff[D2N(DECBUFFER+9)];
1994
1995 #if DECCHECK
1996 if (decCheckOperands(res, lhs, rhs, set)) return res;
1997 #endif
1998
1999 do { /* protect allocated storage */
2000 #if DECSUBSET
2001 if (!set->extended) { /* reduce operands and set status, as needed */
2002 if (lhs->digits>reqdigits) {
2003 alloclhs=decRoundOperand(lhs, set, &status);
2004 if (alloclhs==NULL) break;
2005 lhs=alloclhs;
2006 }
2007 if (rhs->digits>reqdigits) {
2008 allocrhs=decRoundOperand(rhs, set, &status);
2009 if (allocrhs==NULL) break;
2010 rhs=allocrhs;
2011 }
2012 }
2013 #endif
2014 /* [following code does not require input rounding] */
2015
2016 /* handle NaNs and rhs Infinity (lhs infinity is harder) */
2017 if (SPECIALARGS) {
2018 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
2019 decNaNs(res, lhs, rhs, set, &status);
2020 break;}
2021 if (decNumberIsInfinite(rhs)) { /* rhs Infinity */
2022 Flag rhsneg=rhs->bits&DECNEG; /* save rhs sign */
2023 if (decNumberIsNegative(lhs) /* lhs<0 */
2024 && !decNumberIsZero(lhs)) /* .. */
2025 status|=DEC_Invalid_operation;
2026 else { /* lhs >=0 */
2027 decNumberZero(&dnOne); /* set up 1 */
2028 dnOne.lsu[0]=1;
2029 decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2030 decNumberZero(res); /* prepare for 0/1/Infinity */
2031 if (decNumberIsNegative(dac)) { /* lhs<1 */
2032 if (rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2033 }
2034 else if (dac->lsu[0]==0) { /* lhs=1 */
2035 /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2036 Int shift=set->digits-1;
2037 *res->lsu=1; /* was 0, make int 1 */
2038 res->digits=decShiftToMost(res->lsu, 1, shift);
2039 res->exponent=-shift; /* make 1.0000... */
2040 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2041 }
2042 else { /* lhs>1 */
2043 if (!rhsneg) res->bits|=DECINF; /* +Infinity [else is +0] */
2044 }
2045 } /* lhs>=0 */
2046 break;}
2047 /* [lhs infinity drops through] */
2048 } /* specials */
2049
2050 /* Original rhs may be an integer that fits and is in range */
2051 n=decGetInt(rhs);
2052 if (n!=BADINT) { /* it is an integer */
2053 rhsint=1; /* record the fact for 1**n */
2054 isoddint=(Flag)n&1; /* [works even if big] */
2055 if (n!=BIGEVEN && n!=BIGODD) /* can use integer path? */
2056 useint=1; /* looks good */
2057 }
2058
2059 if (decNumberIsNegative(lhs) /* -x .. */
2060 && isoddint) bits=DECNEG; /* .. to an odd power */
2061
2062 /* handle LHS infinity */
2063 if (decNumberIsInfinite(lhs)) { /* [NaNs already handled] */
2064 uByte rbits=rhs->bits; /* save */
2065 decNumberZero(res); /* prepare */
2066 if (n==0) *res->lsu=1; /* [-]Inf**0 => 1 */
2067 else {
2068 /* -Inf**nonint -> error */
2069 if (!rhsint && decNumberIsNegative(lhs)) {
2070 status|=DEC_Invalid_operation; /* -Inf**nonint is error */
2071 break;}
2072 if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2073 /* [otherwise will be 0 or -0] */
2074 res->bits=bits;
2075 }
2076 break;}
2077
2078 /* similarly handle LHS zero */
2079 if (decNumberIsZero(lhs)) {
2080 if (n==0) { /* 0**0 => Error */
2081 #if DECSUBSET
2082 if (!set->extended) { /* [unless subset] */
2083 decNumberZero(res);
2084 *res->lsu=1; /* return 1 */
2085 break;}
2086 #endif
2087 status|=DEC_Invalid_operation;
2088 }
2089 else { /* 0**x */
2090 uByte rbits=rhs->bits; /* save */
2091 if (rbits & DECNEG) { /* was a 0**(-n) */
2092 #if DECSUBSET
2093 if (!set->extended) { /* [bad if subset] */
2094 status|=DEC_Invalid_operation;
2095 break;}
2096 #endif
2097 bits|=DECINF;
2098 }
2099 decNumberZero(res); /* prepare */
2100 /* [otherwise will be 0 or -0] */
2101 res->bits=bits;
2102 }
2103 break;}
2104
2105 /* here both lhs and rhs are finite; rhs==0 is handled in the */
2106 /* integer path. Next handle the non-integer cases */
2107 if (!useint) { /* non-integral rhs */
2108 /* any -ve lhs is bad, as is either operand or context out of */
2109 /* bounds */
2110 if (decNumberIsNegative(lhs)) {
2111 status|=DEC_Invalid_operation;
2112 break;}
2113 if (decCheckMath(lhs, set, &status)
2114 || decCheckMath(rhs, set, &status)) break; /* variable status */
2115
2116 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2117 aset.emax=DEC_MAX_MATH; /* usual bounds */
2118 aset.emin=-DEC_MAX_MATH; /* .. */
2119 aset.clamp=0; /* and no concrete format */
2120
2121 /* calculate the result using exp(ln(lhs)*rhs), which can */
2122 /* all be done into the accumulator, dac. The precision needed */
2123 /* is enough to contain the full information in the lhs (which */
2124 /* is the total digits, including exponent), or the requested */
2125 /* precision, if larger, + 4; 6 is used for the exponent */
2126 /* maximum length, and this is also used when it is shorter */
2127 /* than the requested digits as it greatly reduces the >0.5 ulp */
2128 /* cases at little cost (because Ln doubles digits each */
2129 /* iteration so a few extra digits rarely causes an extra */
2130 /* iteration) */
2131 aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2132 } /* non-integer rhs */
2133
2134 else { /* rhs is in-range integer */
2135 if (n==0) { /* x**0 = 1 */
2136 /* (0**0 was handled above) */
2137 decNumberZero(res); /* result=1 */
2138 *res->lsu=1; /* .. */
2139 break;}
2140 /* rhs is a non-zero integer */
2141 if (n<0) n=-n; /* use abs(n) */
2142
2143 aset=*set; /* clone the context */
2144 aset.round=DEC_ROUND_HALF_EVEN; /* internally use balanced */
2145 /* calculate the working DIGITS */
2146 aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2147 #if DECSUBSET
2148 if (!set->extended) aset.digits--; /* use classic precision */
2149 #endif
2150 /* it's an error if this is more than can be handled */
2151 if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2152 } /* integer path */
2153
2154 /* aset.digits is the count of digits for the accumulator needed */
2155 /* if accumulator is too long for local storage, then allocate */
2156 needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2157 /* [needbytes also used below if 1/lhs needed] */
2158 if (needbytes>sizeof(dacbuff)) {
2159 allocdac=(decNumber *)malloc(needbytes);
2160 if (allocdac==NULL) { /* hopeless -- abandon */
2161 status|=DEC_Insufficient_storage;
2162 break;}
2163 dac=allocdac; /* use the allocated space */
2164 }
2165 /* here, aset is set up and accumulator is ready for use */
2166
2167 if (!useint) { /* non-integral rhs */
2168 /* x ** y; special-case x=1 here as it will otherwise always */
2169 /* reduce to integer 1; decLnOp has a fastpath which detects */
2170 /* the case of x=1 */
2171 decLnOp(dac, lhs, &aset, &status); /* dac=ln(lhs) */
2172 /* [no error possible, as lhs 0 already handled] */
2173 if (ISZERO(dac)) { /* x==1, 1.0, etc. */
2174 /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2175 *dac->lsu=1; /* was 0, make int 1 */
2176 if (!rhsint) { /* add padding */
2177 Int shift=set->digits-1;
2178 dac->digits=decShiftToMost(dac->lsu, 1, shift);
2179 dac->exponent=-shift; /* make 1.0000... */
2180 status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2181 }
2182 }
2183 else {
2184 decMultiplyOp(dac, dac, rhs, &aset, &status); /* dac=dac*rhs */
2185 decExpOp(dac, dac, &aset, &status); /* dac=exp(dac) */
2186 }
2187 /* and drop through for final rounding */
2188 } /* non-integer rhs */
2189
2190 else { /* carry on with integer */
2191 decNumberZero(dac); /* acc=1 */
2192 *dac->lsu=1; /* .. */
2193
2194 /* if a negative power the constant 1 is needed, and if not subset */
2195 /* invert the lhs now rather than inverting the result later */
2196 if (decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2197 decNumber *inv=invbuff; /* asssume use fixed buffer */
2198 decNumberCopy(&dnOne, dac); /* dnOne=1; [needed now or later] */
2199 #if DECSUBSET
2200 if (set->extended) { /* need to calculate 1/lhs */
2201 #endif
2202 /* divide lhs into 1, putting result in dac [dac=1/dac] */
2203 decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2204 /* now locate or allocate space for the inverted lhs */
2205 if (needbytes>sizeof(invbuff)) {
2206 allocinv=(decNumber *)malloc(needbytes);
2207 if (allocinv==NULL) { /* hopeless -- abandon */
2208 status|=DEC_Insufficient_storage;
2209 break;}
2210 inv=allocinv; /* use the allocated space */
2211 }
2212 /* [inv now points to big-enough buffer or allocated storage] */
2213 decNumberCopy(inv, dac); /* copy the 1/lhs */
2214 decNumberCopy(dac, &dnOne); /* restore acc=1 */
2215 lhs=inv; /* .. and go forward with new lhs */
2216 #if DECSUBSET
2217 }
2218 #endif
2219 }
2220
2221 /* Raise-to-the-power loop... */
2222 seenbit=0; /* set once a 1-bit is encountered */
2223 for (i=1;;i++){ /* for each bit [top bit ignored] */
2224 /* abandon if had overflow or terminal underflow */
2225 if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2226 if (status&DEC_Overflow || ISZERO(dac)) break;
2227 }
2228 /* [the following two lines revealed an optimizer bug in a C++ */
2229 /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2230 n=n<<1; /* move next bit to testable position */
2231 if (n<0) { /* top bit is set */
2232 seenbit=1; /* OK, significant bit seen */
2233 decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2234 }
2235 if (i==31) break; /* that was the last bit */
2236 if (!seenbit) continue; /* no need to square 1 */
2237 decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2238 } /*i*/ /* 32 bits */
2239
2240 /* complete internal overflow or underflow processing */
2241 if (status & (DEC_Overflow|DEC_Underflow)) {
2242 #if DECSUBSET
2243 /* If subset, and power was negative, reverse the kind of -erflow */
2244 /* [1/x not yet done] */
2245 if (!set->extended && decNumberIsNegative(rhs)) {
2246 if (status & DEC_Overflow)
2247 status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2248 else { /* trickier -- Underflow may or may not be set */
2249 status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2250 status|=DEC_Overflow;
2251 }
2252 }
2253 #endif
2254 dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2255 /* round subnormals [to set.digits rather than aset.digits] */
2256 /* or set overflow result similarly as required */
2257 decFinalize(dac, set, &residue, &status);
2258 decNumberCopy(res, dac); /* copy to result (is now OK length) */
2259 break;
2260 }
2261
2262 #if DECSUBSET
2263 if (!set->extended && /* subset math */
2264 decNumberIsNegative(rhs)) { /* was a **-n [hence digits>0] */
2265 /* so divide result into 1 [dac=1/dac] */
2266 decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2267 }
2268 #endif
2269 } /* rhs integer path */
2270
2271 /* reduce result to the requested length and copy to result */
2272 decCopyFit(res, dac, set, &residue, &status);
2273 decFinish(res, set, &residue, &status); /* final cleanup */
2274 #if DECSUBSET
2275 if (!set->extended) decTrim(res, set, 0, &dropped); /* trailing zeros */
2276 #endif
2277 } while(0); /* end protected */
2278
2279 if (allocdac!=NULL) free(allocdac); /* drop any storage used */
2280 if (allocinv!=NULL) free(allocinv); /* .. */
2281 #if DECSUBSET
2282 if (alloclhs!=NULL) free(alloclhs); /* .. */
2283 if (allocrhs!=NULL) free(allocrhs); /* .. */
2284 #endif
2285 if (status!=0) decStatus(res, status, set);
2286 #if DECCHECK
2287 decCheckInexact(res, set);
2288 #endif
2289 return res;
2290 } /* decNumberPower */
2291
2292/* ------------------------------------------------------------------ */
2293/* decNumberQuantize -- force exponent to requested value */
2294/* */
2295/* This computes C = op(A, B), where op adjusts the coefficient */
2296/* of C (by rounding or shifting) such that the exponent (-scale) */
2297/* of C has exponent of B. The numerical value of C will equal A, */
2298/* except for the effects of any rounding that occurred. */
2299/* */
2300/* res is C, the result. C may be A or B */
2301/* lhs is A, the number to adjust */
2302/* rhs is B, the number with exponent to match */
2303/* set is the context */
2304/* */
2305/* C must have space for set->digits digits. */
2306/* */
2307/* Unless there is an error or the result is infinite, the exponent */
2308/* after the operation is guaranteed to be equal to that of B. */
2309/* ------------------------------------------------------------------ */
2310decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2311 const decNumber *rhs, decContext *set) {
2312 uInt status=0; /* accumulator */
2313 decQuantizeOp(res, lhs, rhs, set, 1, &status);
2314 if (status!=0) decStatus(res, status, set);
2315 return res;
2316 } /* decNumberQuantize */
2317
2318/* ------------------------------------------------------------------ */
2319/* decNumberReduce -- remove trailing zeros */
2320/* */
2321/* This computes C = 0 + A, and normalizes the result */
2322/* */
2323/* res is C, the result. C may be A */
2324/* rhs is A */
2325/* set is the context */
2326/* */
2327/* C must have space for set->digits digits. */
2328/* ------------------------------------------------------------------ */
2329/* Previously known as Normalize */
2330decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2331 decContext *set) {
2332 return decNumberReduce(res, rhs, set);
2333 } /* decNumberNormalize */
2334
2335decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2336 decContext *set) {
2337 #if DECSUBSET
2338 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2339 #endif
2340 uInt status=0; /* as usual */
2341 Int residue=0; /* as usual */
2342 Int dropped; /* work */
2343
2344 #if DECCHECK
2345 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2346 #endif
2347
2348 do { /* protect allocated storage */
2349 #if DECSUBSET
2350 if (!set->extended) {
2351 /* reduce operand and set lostDigits status, as needed */
2352 if (rhs->digits>set->digits) {
2353 allocrhs=decRoundOperand(rhs, set, &status);
2354 if (allocrhs==NULL) break;
2355 rhs=allocrhs;
2356 }
2357 }
2358 #endif
2359 /* [following code does not require input rounding] */
2360
2361 /* Infinities copy through; NaNs need usual treatment */
2362 if (decNumberIsNaN(rhs)) {
2363 decNaNs(res, rhs, NULL, set, &status);
2364 break;
2365 }
2366
2367 /* reduce result to the requested length and copy to result */
2368 decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2369 decFinish(res, set, &residue, &status); /* cleanup/set flags */
2370 decTrim(res, set, 1, &dropped); /* normalize in place */
2371 } while(0); /* end protected */
2372
2373 #if DECSUBSET
2374 if (allocrhs !=NULL) free(allocrhs); /* .. */
2375 #endif
2376 if (status!=0) decStatus(res, status, set);/* then report status */
2377 return res;
2378 } /* decNumberReduce */
2379
2380/* ------------------------------------------------------------------ */
2381/* decNumberRescale -- force exponent to requested value */
2382/* */
2383/* This computes C = op(A, B), where op adjusts the coefficient */
2384/* of C (by rounding or shifting) such that the exponent (-scale) */
2385/* of C has the value B. The numerical value of C will equal A, */
2386/* except for the effects of any rounding that occurred. */
2387/* */
2388/* res is C, the result. C may be A or B */
2389/* lhs is A, the number to adjust */
2390/* rhs is B, the requested exponent */
2391/* set is the context */
2392/* */
2393/* C must have space for set->digits digits. */
2394/* */
2395/* Unless there is an error or the result is infinite, the exponent */
2396/* after the operation is guaranteed to be equal to B. */
2397/* ------------------------------------------------------------------ */
2398decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2399 const decNumber *rhs, decContext *set) {
2400 uInt status=0; /* accumulator */
2401 decQuantizeOp(res, lhs, rhs, set, 0, &status);
2402 if (status!=0) decStatus(res, status, set);
2403 return res;
2404 } /* decNumberRescale */
2405
2406/* ------------------------------------------------------------------ */
2407/* decNumberRemainder -- divide and return remainder */
2408/* */
2409/* This computes C = A % B */
2410/* */
2411/* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2412/* lhs is A */
2413/* rhs is B */
2414/* set is the context */
2415/* */
2416/* C must have space for set->digits digits. */
2417/* ------------------------------------------------------------------ */
2418decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2419 const decNumber *rhs, decContext *set) {
2420 uInt status=0; /* accumulator */
2421 decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2422 if (status!=0) decStatus(res, status, set);
2423 #if DECCHECK
2424 decCheckInexact(res, set);
2425 #endif
2426 return res;
2427 } /* decNumberRemainder */
2428
2429/* ------------------------------------------------------------------ */
2430/* decNumberRemainderNear -- divide and return remainder from nearest */
2431/* */
2432/* This computes C = A % B, where % is the IEEE remainder operator */
2433/* */
2434/* res is C, the result. C may be A and/or B (e.g., X=X%X) */
2435/* lhs is A */
2436/* rhs is B */
2437/* set is the context */
2438/* */
2439/* C must have space for set->digits digits. */
2440/* ------------------------------------------------------------------ */
2441decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2442 const decNumber *rhs, decContext *set) {
2443 uInt status=0; /* accumulator */
2444 decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2445 if (status!=0) decStatus(res, status, set);
2446 #if DECCHECK
2447 decCheckInexact(res, set);
2448 #endif
2449 return res;
2450 } /* decNumberRemainderNear */
2451
2452/* ------------------------------------------------------------------ */
2453/* decNumberRotate -- rotate the coefficient of a Number left/right */
2454/* */
2455/* This computes C = A rot B (in base ten and rotating set->digits */
2456/* digits). */
2457/* */
2458/* res is C, the result. C may be A and/or B (e.g., X=XrotX) */
2459/* lhs is A */
2460/* rhs is B, the number of digits to rotate (-ve to right) */
2461/* set is the context */
2462/* */
2463/* The digits of the coefficient of A are rotated to the left (if B */
2464/* is positive) or to the right (if B is negative) without adjusting */
2465/* the exponent or the sign of A. If lhs->digits is less than */
2466/* set->digits the coefficient is padded with zeros on the left */
2467/* before the rotate. Any leading zeros in the result are removed */
2468/* as usual. */
2469/* */
2470/* B must be an integer (q=0) and in the range -set->digits through */
2471/* +set->digits. */
2472/* C must have space for set->digits digits. */
2473/* NaNs are propagated as usual. Infinities are unaffected (but */
2474/* B must be valid). No status is set unless B is invalid or an */
2475/* operand is an sNaN. */
2476/* ------------------------------------------------------------------ */
2477decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2478 const decNumber *rhs, decContext *set) {
2479 uInt status=0; /* accumulator */
2480 Int rotate; /* rhs as an Int */
2481
2482 #if DECCHECK
2483 if (decCheckOperands(res, lhs, rhs, set)) return res;
2484 #endif
2485
2486 /* NaNs propagate as normal */
2487 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2488 decNaNs(res, lhs, rhs, set, &status);
2489 /* rhs must be an integer */
2490 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2491 status=DEC_Invalid_operation;
2492 else { /* both numeric, rhs is an integer */
2493 rotate=decGetInt(rhs); /* [cannot fail] */
2494 if (rotate==BADINT /* something bad .. */
2495 || rotate==BIGODD || rotate==BIGEVEN /* .. very big .. */
2496 || abs(rotate)>set->digits) /* .. or out of range */
2497 status=DEC_Invalid_operation;
2498 else { /* rhs is OK */
2499 decNumberCopy(res, lhs);
2500 /* convert -ve rotate to equivalent positive rotation */
2501 if (rotate<0) rotate=set->digits+rotate;
2502 if (rotate!=0 && rotate!=set->digits /* zero or full rotation */
2503 && !decNumberIsInfinite(res)) { /* lhs was infinite */
2504 /* left-rotate to do; 0 < rotate < set->digits */
2505 uInt units, shift; /* work */
2506 uInt msudigits; /* digits in result msu */
2507 Unit *msu=res->lsu+D2U(res->digits)-1; /* current msu */
2508 Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2509 for (msu++; msu<=msumax; msu++) *msu=0; /* ensure high units=0 */
2510 res->digits=set->digits; /* now full-length */
2511 msudigits=MSUDIGITS(res->digits); /* actual digits in msu */
2512
2513 /* rotation here is done in-place, in three steps */
2514 /* 1. shift all to least up to one unit to unit-align final */
2515 /* lsd [any digits shifted out are rotated to the left, */
2516 /* abutted to the original msd (which may require split)] */
2517 /* */
2518 /* [if there are no whole units left to rotate, the */
2519 /* rotation is now complete] */
2520 /* */
2521 /* 2. shift to least, from below the split point only, so that */
2522 /* the final msd is in the right place in its Unit [any */
2523 /* digits shifted out will fit exactly in the current msu, */
2524 /* left aligned, no split required] */
2525 /* */
2526 /* 3. rotate all the units by reversing left part, right */
2527 /* part, and then whole */
2528 /* */
2529 /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2530 /* */
2531 /* start: 00a bcd efg hij klm npq */
2532 /* */
2533 /* 1a 000 0ab cde fgh|ijk lmn [pq saved] */
2534 /* 1b 00p qab cde fgh|ijk lmn */
2535 /* */
2536 /* 2a 00p qab cde fgh|00i jkl [mn saved] */
2537 /* 2b mnp qab cde fgh|00i jkl */
2538 /* */
2539 /* 3a fgh cde qab mnp|00i jkl */
2540 /* 3b fgh cde qab mnp|jkl 00i */
2541 /* 3c 00i jkl mnp qab cde fgh */
2542
2543 /* Step 1: amount to shift is the partial right-rotate count */
2544 rotate=set->digits-rotate; /* make it right-rotate */
2545 units=rotate/DECDPUN; /* whole units to rotate */
2546 shift=rotate%DECDPUN; /* left-over digits count */
2547 if (shift>0) { /* not an exact number of units */
2548 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2549 decShiftToLeast(res->lsu, D2U(res->digits), shift);
2550 if (shift>msudigits) { /* msumax-1 needs >0 digits */
2551 uInt rem=save%powers[shift-msudigits];/* split save */
2552 *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2553 *(msumax-1)=*(msumax-1)
2554 +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2555 }
2556 else { /* all fits in msumax */
2557 *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2558 }
2559 } /* digits shift needed */
2560
2561 /* If whole units to rotate... */
2562 if (units>0) { /* some to do */
2563 /* Step 2: the units to touch are the whole ones in rotate, */
2564 /* if any, and the shift is DECDPUN-msudigits (which may be */
2565 /* 0, again) */
2566 shift=DECDPUN-msudigits;
2567 if (shift>0) { /* not an exact number of units */
2568 uInt save=res->lsu[0]%powers[shift]; /* save low digit(s) */
2569 decShiftToLeast(res->lsu, units, shift);
2570 *msumax=*msumax+(Unit)(save*powers[msudigits]);
2571 } /* partial shift needed */
2572
2573 /* Step 3: rotate the units array using triple reverse */
2574 /* (reversing is easy and fast) */
2575 decReverse(res->lsu+units, msumax); /* left part */
2576 decReverse(res->lsu, res->lsu+units-1); /* right part */
2577 decReverse(res->lsu, msumax); /* whole */
2578 } /* whole units to rotate */
2579 /* the rotation may have left an undetermined number of zeros */
2580 /* on the left, so true length needs to be calculated */
2581 res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2582 } /* rotate needed */
2583 } /* rhs OK */
2584 } /* numerics */
2585 if (status!=0) decStatus(res, status, set);
2586 return res;
2587 } /* decNumberRotate */
2588
2589/* ------------------------------------------------------------------ */
2590/* decNumberSameQuantum -- test for equal exponents */
2591/* */
2592/* res is the result number, which will contain either 0 or 1 */
2593/* lhs is a number to test */
2594/* rhs is the second (usually a pattern) */
2595/* */
2596/* No errors are possible and no context is needed. */
2597/* ------------------------------------------------------------------ */
2598decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2599 const decNumber *rhs) {
2600 Unit ret=0; /* return value */
2601
2602 #if DECCHECK
2603 if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2604 #endif
2605
2606 if (SPECIALARGS) {
2607 if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2608 else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2609 /* [anything else with a special gives 0] */
2610 }
2611 else if (lhs->exponent==rhs->exponent) ret=1;
2612
2613 decNumberZero(res); /* OK to overwrite an operand now */
2614 *res->lsu=ret;
2615 return res;
2616 } /* decNumberSameQuantum */
2617
2618/* ------------------------------------------------------------------ */
2619/* decNumberScaleB -- multiply by a power of 10 */
2620/* */
2621/* This computes C = A x 10**B where B is an integer (q=0) with */
2622/* maximum magnitude 2*(emax+digits) */
2623/* */
2624/* res is C, the result. C may be A or B */
2625/* lhs is A, the number to adjust */
2626/* rhs is B, the requested power of ten to use */
2627/* set is the context */
2628/* */
2629/* C must have space for set->digits digits. */
2630/* */
2631/* The result may underflow or overflow. */
2632/* ------------------------------------------------------------------ */
2633decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2634 const decNumber *rhs, decContext *set) {
2635 Int reqexp; /* requested exponent change [B] */
2636 uInt status=0; /* accumulator */
2637 Int residue; /* work */
2638
2639 #if DECCHECK
2640 if (decCheckOperands(res, lhs, rhs, set)) return res;
2641 #endif
2642
2643 /* Handle special values except lhs infinite */
2644 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2645 decNaNs(res, lhs, rhs, set, &status);
2646 /* rhs must be an integer */
2647 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2648 status=DEC_Invalid_operation;
2649 else {
2650 /* lhs is a number; rhs is a finite with q==0 */
2651 reqexp=decGetInt(rhs); /* [cannot fail] */
2652 if (reqexp==BADINT /* something bad .. */
2653 || reqexp==BIGODD || reqexp==BIGEVEN /* .. very big .. */
2654 || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2655 status=DEC_Invalid_operation;
2656 else { /* rhs is OK */
2657 decNumberCopy(res, lhs); /* all done if infinite lhs */
2658 if (!decNumberIsInfinite(res)) { /* prepare to scale */
2659 res->exponent+=reqexp; /* adjust the exponent */
2660 residue=0;
2661 decFinalize(res, set, &residue, &status); /* .. and check */
2662 } /* finite LHS */
2663 } /* rhs OK */
2664 } /* rhs finite */
2665 if (status!=0) decStatus(res, status, set);
2666 return res;
2667 } /* decNumberScaleB */
2668
2669/* ------------------------------------------------------------------ */
2670/* decNumberShift -- shift the coefficient of a Number left or right */
2671/* */
2672/* This computes C = A << B or C = A >> -B (in base ten). */
2673/* */
2674/* res is C, the result. C may be A and/or B (e.g., X=X<<X) */
2675/* lhs is A */
2676/* rhs is B, the number of digits to shift (-ve to right) */
2677/* set is the context */
2678/* */
2679/* The digits of the coefficient of A are shifted to the left (if B */
2680/* is positive) or to the right (if B is negative) without adjusting */
2681/* the exponent or the sign of A. */
2682/* */
2683/* B must be an integer (q=0) and in the range -set->digits through */
2684/* +set->digits. */
2685/* C must have space for set->digits digits. */
2686/* NaNs are propagated as usual. Infinities are unaffected (but */
2687/* B must be valid). No status is set unless B is invalid or an */
2688/* operand is an sNaN. */
2689/* ------------------------------------------------------------------ */
2690decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2691 const decNumber *rhs, decContext *set) {
2692 uInt status=0; /* accumulator */
2693 Int shift; /* rhs as an Int */
2694
2695 #if DECCHECK
2696 if (decCheckOperands(res, lhs, rhs, set)) return res;
2697 #endif
2698
2699 /* NaNs propagate as normal */
2700 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2701 decNaNs(res, lhs, rhs, set, &status);
2702 /* rhs must be an integer */
2703 else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2704 status=DEC_Invalid_operation;
2705 else { /* both numeric, rhs is an integer */
2706 shift=decGetInt(rhs); /* [cannot fail] */
2707 if (shift==BADINT /* something bad .. */
2708 || shift==BIGODD || shift==BIGEVEN /* .. very big .. */
2709 || abs(shift)>set->digits) /* .. or out of range */
2710 status=DEC_Invalid_operation;
2711 else { /* rhs is OK */
2712 decNumberCopy(res, lhs);
2713 if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2714 if (shift>0) { /* to left */
2715 if (shift==set->digits) { /* removing all */
2716 *res->lsu=0; /* so place 0 */
2717 res->digits=1; /* .. */
2718 }
2719 else { /* */
2720 /* first remove leading digits if necessary */
2721 if (res->digits+shift>set->digits) {
2722 decDecap(res, res->digits+shift-set->digits);
2723 /* that updated res->digits; may have gone to 1 (for a */
2724 /* single digit or for zero */
2725 }
2726 if (res->digits>1 || *res->lsu) /* if non-zero.. */
2727 res->digits=decShiftToMost(res->lsu, res->digits, shift);
2728 } /* partial left */
2729 } /* left */
2730 else { /* to right */
2731 if (-shift>=res->digits) { /* discarding all */
2732 *res->lsu=0; /* so place 0 */
2733 res->digits=1; /* .. */
2734 }
2735 else {
2736 decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2737 res->digits-=(-shift);
2738 }
2739 } /* to right */
2740 } /* non-0 non-Inf shift */
2741 } /* rhs OK */
2742 } /* numerics */
2743 if (status!=0) decStatus(res, status, set);
2744 return res;
2745 } /* decNumberShift */
2746
2747/* ------------------------------------------------------------------ */
2748/* decNumberSquareRoot -- square root operator */
2749/* */
2750/* This computes C = squareroot(A) */
2751/* */
2752/* res is C, the result. C may be A */
2753/* rhs is A */
2754/* set is the context; note that rounding mode has no effect */
2755/* */
2756/* C must have space for set->digits digits. */
2757/* ------------------------------------------------------------------ */
2758/* This uses the following varying-precision algorithm in: */
2759/* */
2760/* Properly Rounded Variable Precision Square Root, T. E. Hull and */
2761/* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2762/* pp229-237, ACM, September 1985. */
2763/* */
2764/* The square-root is calculated using Newton's method, after which */
2765/* a check is made to ensure the result is correctly rounded. */
2766/* */
2767/* % [Reformatted original Numerical Turing source code follows.] */
2768/* function sqrt(x : real) : real */
2769/* % sqrt(x) returns the properly rounded approximation to the square */
2770/* % root of x, in the precision of the calling environment, or it */
2771/* % fails if x < 0. */
2772/* % t e hull and a abrham, august, 1984 */
2773/* if x <= 0 then */
2774/* if x < 0 then */
2775/* assert false */
2776/* else */
2777/* result 0 */
2778/* end if */
2779/* end if */
2780/* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */
2781/* var e := getexp(x) % exponent part of x */
2782/* var approx : real */
2783/* if e mod 2 = 0 then */
2784/* approx := .259 + .819 * f % approx to root of f */
2785/* else */
2786/* f := f/l0 % adjustments */
2787/* e := e + 1 % for odd */
2788/* approx := .0819 + 2.59 * f % exponent */
2789/* end if */
2790/* */
2791/* var p:= 3 */
2792/* const maxp := currentprecision + 2 */
2793/* loop */
2794/* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */
2795/* precision p */
2796/* approx := .5 * (approx + f/approx) */
2797/* exit when p = maxp */
2798/* end loop */
2799/* */
2800/* % approx is now within 1 ulp of the properly rounded square root */
2801/* % of f; to ensure proper rounding, compare squares of (approx - */
2802/* % l/2 ulp) and (approx + l/2 ulp) with f. */
2803/* p := currentprecision */
2804/* begin */
2805/* precision p + 2 */
2806/* const approxsubhalf := approx - setexp(.5, -p) */
2807/* if mulru(approxsubhalf, approxsubhalf) > f then */
2808/* approx := approx - setexp(.l, -p + 1) */
2809/* else */
2810/* const approxaddhalf := approx + setexp(.5, -p) */
2811/* if mulrd(approxaddhalf, approxaddhalf) < f then */
2812/* approx := approx + setexp(.l, -p + 1) */
2813/* end if */
2814/* end if */
2815/* end */
2816/* result setexp(approx, e div 2) % fix exponent */
2817/* end sqrt */
2818/* ------------------------------------------------------------------ */
2819decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2820 decContext *set) {
2821 decContext workset, approxset; /* work contexts */
2822 decNumber dzero; /* used for constant zero */
2823 Int maxp; /* largest working precision */
2824 Int workp; /* working precision */
2825 Int residue=0; /* rounding residue */
2826 uInt status=0, ignore=0; /* status accumulators */
2827 uInt rstatus; /* .. */
2828 Int exp; /* working exponent */
2829 Int ideal; /* ideal (preferred) exponent */
2830 Int needbytes; /* work */
2831 Int dropped; /* .. */
2832
2833 #if DECSUBSET
2834 decNumber *allocrhs=NULL; /* non-NULL if rounded rhs allocated */
2835 #endif
2836 /* buffer for f [needs +1 in case DECBUFFER 0] */
2837 decNumber buff[D2N(DECBUFFER+1)];
2838 /* buffer for a [needs +2 to match likely maxp] */
2839 decNumber bufa[D2N(DECBUFFER+2)];
2840 /* buffer for temporary, b [must be same size as a] */
2841 decNumber bufb[D2N(DECBUFFER+2)];
2842 decNumber *allocbuff=NULL; /* -> allocated buff, iff allocated */
2843 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
2844 decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
2845 decNumber *f=buff; /* reduced fraction */
2846 decNumber *a=bufa; /* approximation to result */
2847 decNumber *b=bufb; /* intermediate result */
2848 /* buffer for temporary variable, up to 3 digits */
2849 decNumber buft[D2N(3)];
2850 decNumber *t=buft; /* up-to-3-digit constant or work */
2851
2852 #if DECCHECK
2853 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2854 #endif
2855
2856 do { /* protect allocated storage */
2857 #if DECSUBSET
2858 if (!set->extended) {
2859 /* reduce operand and set lostDigits status, as needed */
2860 if (rhs->digits>set->digits) {
2861 allocrhs=decRoundOperand(rhs, set, &status);
2862 if (allocrhs==NULL) break;
2863 /* [Note: 'f' allocation below could reuse this buffer if */
2864 /* used, but as this is rare they are kept separate for clarity.] */
2865 rhs=allocrhs;
2866 }
2867 }
2868 #endif
2869 /* [following code does not require input rounding] */
2870
2871 /* handle infinities and NaNs */
2872 if (SPECIALARG) {
2873 if (decNumberIsInfinite(rhs)) { /* an infinity */
2874 if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2875 else decNumberCopy(res, rhs); /* +Infinity */
2876 }
2877 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2878 break;
2879 }
2880
2881 /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2882 /* [We would like to write: ideal=rhs->exponent>>1, but this */
2883 /* generates a compiler warning. Generated code is the same.] */
2884 ideal=(rhs->exponent&~1)/2; /* target */
2885
2886 /* handle zeros */
2887 if (ISZERO(rhs)) {
2888 decNumberCopy(res, rhs); /* could be 0 or -0 */
2889 res->exponent=ideal; /* use the ideal [safe] */
2890 /* use decFinish to clamp any out-of-range exponent, etc. */
2891 decFinish(res, set, &residue, &status);
2892 break;
2893 }
2894
2895 /* any other -x is an oops */
2896 if (decNumberIsNegative(rhs)) {
2897 status|=DEC_Invalid_operation;
2898 break;
2899 }
2900
2901 /* space is needed for three working variables */
2902 /* f -- the same precision as the RHS, reduced to 0.01->0.99... */
2903 /* a -- Hull's approximation -- precision, when assigned, is */
2904 /* currentprecision+1 or the input argument precision, */
2905 /* whichever is larger (+2 for use as temporary) */
2906 /* b -- intermediate temporary result (same size as a) */
2907 /* if any is too long for local storage, then allocate */
2908 workp=MAXI(set->digits+1, rhs->digits); /* actual rounding precision */
2909 maxp=workp+2; /* largest working precision */
2910
2911 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2912 if (needbytes>(Int)sizeof(buff)) {
2913 allocbuff=(decNumber *)malloc(needbytes);
2914 if (allocbuff==NULL) { /* hopeless -- abandon */
2915 status|=DEC_Insufficient_storage;
2916 break;}
2917 f=allocbuff; /* use the allocated space */
2918 }
2919 /* a and b both need to be able to hold a maxp-length number */
2920 needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2921 if (needbytes>(Int)sizeof(bufa)) { /* [same applies to b] */
2922 allocbufa=(decNumber *)malloc(needbytes);
2923 allocbufb=(decNumber *)malloc(needbytes);
2924 if (allocbufa==NULL || allocbufb==NULL) { /* hopeless */
2925 status|=DEC_Insufficient_storage;
2926 break;}
2927 a=allocbufa; /* use the allocated spaces */
2928 b=allocbufb; /* .. */
2929 }
2930
2931 /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2932 decNumberCopy(f, rhs);
2933 exp=f->exponent+f->digits; /* adjusted to Hull rules */
2934 f->exponent=-(f->digits); /* to range */
2935
2936 /* set up working context */
2937 decContextDefault(&workset, DEC_INIT_DECIMAL64);
2938
2939 /* [Until further notice, no error is possible and status bits */
2940 /* (Rounded, etc.) should be ignored, not accumulated.] */
2941
2942 /* Calculate initial approximation, and allow for odd exponent */
2943 workset.digits=workp; /* p for initial calculation */
2944 t->bits=0; t->digits=3;
2945 a->bits=0; a->digits=3;
2946 if ((exp & 1)==0) { /* even exponent */
2947 /* Set t=0.259, a=0.819 */
2948 t->exponent=-3;
2949 a->exponent=-3;
2950 #if DECDPUN>=3
2951 t->lsu[0]=259;
2952 a->lsu[0]=819;
2953 #elif DECDPUN==2
2954 t->lsu[0]=59; t->lsu[1]=2;
2955 a->lsu[0]=19; a->lsu[1]=8;
2956 #else
2957 t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2958 a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2959 #endif
2960 }
2961 else { /* odd exponent */
2962 /* Set t=0.0819, a=2.59 */
2963 f->exponent--; /* f=f/10 */
2964 exp++; /* e=e+1 */
2965 t->exponent=-4;
2966 a->exponent=-2;
2967 #if DECDPUN>=3
2968 t->lsu[0]=819;
2969 a->lsu[0]=259;
2970 #elif DECDPUN==2
2971 t->lsu[0]=19; t->lsu[1]=8;
2972 a->lsu[0]=59; a->lsu[1]=2;
2973 #else
2974 t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2975 a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2976 #endif
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 decNumberZero(&dzero); /* make 0 */
2985 decNumberZero(t); /* set t = 0.5 */
2986 t->lsu[0]=5; /* .. */
2987 t->exponent=-1; /* .. */
2988 workset.digits=3; /* initial p */
2989 for (;;) {
2990 /* set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp] */
2991 workset.digits=workset.digits*2-2;
2992 if (workset.digits>maxp) workset.digits=maxp;
2993 /* a = 0.5 * (a + f/a) */
2994 /* [calculated at p then rounded to currentprecision] */
2995 decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
2996 decAddOp(b, b, a, &workset, 0, &ignore); /* b=b+a */
2997 decMultiplyOp(a, b, t, &workset, &ignore); /* a=b*0.5 */
2998 if (a->digits==maxp) break; /* have required digits */
2999 } /* loop */
3000
3001 /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
3002 /* now reduce to length, etc.; this needs to be done with a */
3003 /* having the correct exponent so as to handle subnormals */
3004 /* correctly */
3005 approxset=*set; /* get emin, emax, etc. */
3006 approxset.round=DEC_ROUND_HALF_EVEN;
3007 a->exponent+=exp/2; /* set correct exponent */
3008
3009 rstatus=0; /* clear status */
3010 residue=0; /* .. and accumulator */
3011 decCopyFit(a, a, &approxset, &residue, &rstatus); /* reduce (if needed) */
3012 decFinish(a, &approxset, &residue, &rstatus); /* clean and finalize */
3013
3014 /* Overflow was possible if the input exponent was out-of-range, */
3015 /* in which case quit */
3016 if (rstatus&DEC_Overflow) {
3017 status=rstatus; /* use the status as-is */
3018 decNumberCopy(res, a); /* copy to result */
3019 break;
3020 }
3021
3022 /* Preserve status except Inexact/Rounded */
3023 status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3024
3025 /* Carry out the Hull correction */
3026 a->exponent-=exp/2; /* back to 0.1->1 */
3027
3028 /* a is now at final precision and within 1 ulp of the properly */
3029 /* rounded square root of f; to ensure proper rounding, compare */
3030 /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3031 /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3032 /* the ulp */
3033 workset.digits--; /* maxp-1 is OK now */
3034 t->exponent=-a->digits-1; /* make 0.5 ulp */
3035 decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3036 workset.round=DEC_ROUND_UP;
3037 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulru(b, b) */
3038 decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3039 if (decNumberIsNegative(b)) { /* f < b [i.e., b > f] */
3040 /* this is the more common adjustment, though both are rare */
3041 t->exponent++; /* make 1.0 ulp */
3042 t->lsu[0]=1; /* .. */
3043 decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3044 /* assign to approx [round to length] */
3045 approxset.emin-=exp/2; /* adjust to match a */
3046 approxset.emax-=exp/2;
3047 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3048 }
3049 else {
3050 decAddOp(b, a, t, &workset, 0, &ignore); /* b = a + 0.5 ulp */
3051 workset.round=DEC_ROUND_DOWN;
3052 decMultiplyOp(b, b, b, &workset, &ignore); /* b = mulrd(b, b) */
3053 decCompareOp(b, b, f, &workset, COMPARE, &ignore); /* b ? f */
3054 if (decNumberIsNegative(b)) { /* b < f */
3055 t->exponent++; /* make 1.0 ulp */
3056 t->lsu[0]=1; /* .. */
3057 decAddOp(a, a, t, &workset, 0, &ignore); /* a = a + 1 ulp */
3058 /* assign to approx [round to length] */
3059 approxset.emin-=exp/2; /* adjust to match a */
3060 approxset.emax-=exp/2;
3061 decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3062 }
3063 }
3064 /* [no errors are possible in the above, and rounding/inexact during */
3065 /* estimation are irrelevant, so status was not accumulated] */
3066
3067 /* Here, 0.1 <= a < 1 (still), so adjust back */
3068 a->exponent+=exp/2; /* set correct exponent */
3069
3070 /* count droppable zeros [after any subnormal rounding] by */
3071 /* trimming a copy */
3072 decNumberCopy(b, a);
3073 decTrim(b, set, 1, &dropped); /* [drops trailing zeros] */
3074
3075 /* Set Inexact and Rounded. The answer can only be exact if */
3076 /* it is short enough so that squaring it could fit in workp digits, */
3077 /* and it cannot have trailing zeros due to clamping, so these are */
3078 /* the only (relatively rare) conditions a careful check is needed */
3079 if (b->digits*2-1 > workp && !set->clamp) { /* cannot fit */
3080 status|=DEC_Inexact|DEC_Rounded;
3081 }
3082 else { /* could be exact/unrounded */
3083 uInt mstatus=0; /* local status */
3084 decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3085 if (mstatus&DEC_Overflow) { /* result just won't fit */
3086 status|=DEC_Inexact|DEC_Rounded;
3087 }
3088 else { /* plausible */
3089 decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3090 if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3091 else { /* is Exact */
3092 /* here, dropped is the count of trailing zeros in 'a' */
3093 /* use closest exponent to ideal... */
3094 Int todrop=ideal-a->exponent; /* most that can be dropped */
3095 if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3096 else { /* unrounded */
3097 if (dropped<todrop) { /* clamp to those available */
3098 todrop=dropped;
3099 status|=DEC_Clamped;
3100 }
3101 if (todrop>0) { /* have some to drop */
3102 decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3103 a->exponent+=todrop; /* maintain numerical value */
3104 a->digits-=todrop; /* new length */
3105 }
3106 }
3107 }
3108 }
3109 }
3110
3111 /* double-check Underflow, as perhaps the result could not have */
3112 /* been subnormal (initial argument too big), or it is now Exact */
3113 if (status&DEC_Underflow) {
3114 Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
3115 /* check if truly subnormal */
3116 #if DECEXTFLAG /* DEC_Subnormal too */
3117 if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3118 #else
3119 if (ae>=set->emin*2) status&=~DEC_Underflow;
3120 #endif
3121 /* check if truly inexact */
3122 if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3123 }
3124
3125 decNumberCopy(res, a); /* a is now the result */
3126 } while(0); /* end protected */
3127
3128 if (allocbuff!=NULL) free(allocbuff); /* drop any storage used */
3129 if (allocbufa!=NULL) free(allocbufa); /* .. */
3130 if (allocbufb!=NULL) free(allocbufb); /* .. */
3131 #if DECSUBSET
3132 if (allocrhs !=NULL) free(allocrhs); /* .. */
3133 #endif
3134 if (status!=0) decStatus(res, status, set);/* then report status */
3135 #if DECCHECK
3136 decCheckInexact(res, set);
3137 #endif
3138 return res;
3139 } /* decNumberSquareRoot */
3140
3141/* ------------------------------------------------------------------ */
3142/* decNumberSubtract -- subtract two Numbers */
3143/* */
3144/* This computes C = A - B */
3145/* */
3146/* res is C, the result. C may be A and/or B (e.g., X=X-X) */
3147/* lhs is A */
3148/* rhs is B */
3149/* set is the context */
3150/* */
3151/* C must have space for set->digits digits. */
3152/* ------------------------------------------------------------------ */
3153decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3154 const decNumber *rhs, decContext *set) {
3155 uInt status=0; /* accumulator */
3156
3157 decAddOp(res, lhs, rhs, set, DECNEG, &status);
3158 if (status!=0) decStatus(res, status, set);
3159 #if DECCHECK
3160 decCheckInexact(res, set);
3161 #endif
3162 return res;
3163 } /* decNumberSubtract */
3164
3165/* ------------------------------------------------------------------ */
3166/* decNumberToIntegralExact -- round-to-integral-value with InExact */
3167/* decNumberToIntegralValue -- round-to-integral-value */
3168/* */
3169/* res is the result */
3170/* rhs is input number */
3171/* set is the context */
3172/* */
3173/* res must have space for any value of rhs. */
3174/* */
3175/* This implements the IEEE special operators and therefore treats */
3176/* special values as valid. For finite numbers it returns */
3177/* rescale(rhs, 0) if rhs->exponent is <0. */
3178/* Otherwise the result is rhs (so no error is possible, except for */
3179/* sNaN). */
3180/* */
3181/* The context is used for rounding mode and status after sNaN, but */
3182/* the digits setting is ignored. The Exact version will signal */
3183/* Inexact if the result differs numerically from rhs; the other */
3184/* never signals Inexact. */
3185/* ------------------------------------------------------------------ */
3186decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3187 decContext *set) {
3188 decNumber dn;
3189 decContext workset; /* working context */
3190 uInt status=0; /* accumulator */
3191
3192 #if DECCHECK
3193 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3194 #endif
3195
3196 /* handle infinities and NaNs */
3197 if (SPECIALARG) {
3198 if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */
3199 else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3200 }
3201 else { /* finite */
3202 /* have a finite number; no error possible (res must be big enough) */
3203 if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3204 /* that was easy, but if negative exponent there is work to do... */
3205 workset=*set; /* clone rounding, etc. */
3206 workset.digits=rhs->digits; /* no length rounding */
3207 workset.traps=0; /* no traps */
3208 decNumberZero(&dn); /* make a number with exponent 0 */
3209 decNumberQuantize(res, rhs, &dn, &workset);
3210 status|=workset.status;
3211 }
3212 if (status!=0) decStatus(res, status, set);
3213 return res;
3214 } /* decNumberToIntegralExact */
3215
3216decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3217 decContext *set) {
3218 decContext workset=*set; /* working context */
3219 workset.traps=0; /* no traps */
3220 decNumberToIntegralExact(res, rhs, &workset);
3221 /* this never affects set, except for sNaNs; NaN will have been set */
3222 /* or propagated already, so no need to call decStatus */
3223 set->status|=workset.status&DEC_Invalid_operation;
3224 return res;
3225 } /* decNumberToIntegralValue */
3226
3227/* ------------------------------------------------------------------ */
3228/* decNumberXor -- XOR two Numbers, digitwise */
3229/* */
3230/* This computes C = A ^ B */
3231/* */
3232/* res is C, the result. C may be A and/or B (e.g., X=X^X) */
3233/* lhs is A */
3234/* rhs is B */
3235/* set is the context (used for result length and error report) */
3236/* */
3237/* C must have space for set->digits digits. */
3238/* */
3239/* Logical function restrictions apply (see above); a NaN is */
3240/* returned with Invalid_operation if a restriction is violated. */
3241/* ------------------------------------------------------------------ */
3242decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3243 const decNumber *rhs, decContext *set) {
3244 const Unit *ua, *ub; /* -> operands */
3245 const Unit *msua, *msub; /* -> operand msus */
3246 Unit *uc, *msuc; /* -> result and its msu */
3247 Int msudigs; /* digits in res msu */
3248 #if DECCHECK
3249 if (decCheckOperands(res, lhs, rhs, set)) return res;
3250 #endif
3251
3252 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3253 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3254 decStatus(res, DEC_Invalid_operation, set);
3255 return res;
3256 }
3257 /* operands are valid */
3258 ua=lhs->lsu; /* bottom-up */
3259 ub=rhs->lsu; /* .. */
3260 uc=res->lsu; /* .. */
3261 msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
3262 msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
3263 msuc=uc+D2U(set->digits)-1; /* -> msu of result */
3264 msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
3265 for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
3266 Unit a, b; /* extract units */
3267 if (ua>msua) a=0;
3268 else a=*ua;
3269 if (ub>msub) b=0;
3270 else b=*ub;
3271 *uc=0; /* can now write back */
3272 if (a|b) { /* maybe 1 bits to examine */
3273 Int i, j;
3274 /* This loop could be unrolled and/or use BIN2BCD tables */
3275 for (i=0; i<DECDPUN; i++) {
3276 if ((a^b)&1) *uc=*uc+(Unit)powers[i]; /* effect XOR */
3277 j=a%10;
3278 a=a/10;
3279 j|=b%10;
3280 b=b/10;
3281 if (j>1) {
3282 decStatus(res, DEC_Invalid_operation, set);
3283 return res;
3284 }
3285 if (uc==msuc && i==msudigs-1) break; /* just did final digit */
3286 } /* each digit */
3287 } /* non-zero */
3288 } /* each unit */
3289 /* [here uc-1 is the msu of the result] */
3290 res->digits=decGetDigits(res->lsu, uc-res->lsu);
3291 res->exponent=0; /* integer */
3292 res->bits=0; /* sign=0 */
3293 return res; /* [no status to set] */
3294 } /* decNumberXor */
3295
3296
3297/* ================================================================== */
3298/* Utility routines */
3299/* ================================================================== */
3300
3301/* ------------------------------------------------------------------ */
3302/* decNumberClass -- return the decClass of a decNumber */
3303/* dn -- the decNumber to test */
3304/* set -- the context to use for Emin */
3305/* returns the decClass enum */
3306/* ------------------------------------------------------------------ */
3307enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3308 if (decNumberIsSpecial(dn)) {
3309 if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3310 if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3311 /* must be an infinity */
3312 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3313 return DEC_CLASS_POS_INF;
3314 }
3315 /* is finite */
3316 if (decNumberIsNormal(dn, set)) { /* most common */
3317 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3318 return DEC_CLASS_POS_NORMAL;
3319 }
3320 /* is subnormal or zero */
3321 if (decNumberIsZero(dn)) { /* most common */
3322 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3323 return DEC_CLASS_POS_ZERO;
3324 }
3325 if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3326 return DEC_CLASS_POS_SUBNORMAL;
3327 } /* decNumberClass */
3328
3329/* ------------------------------------------------------------------ */
3330/* decNumberClassToString -- convert decClass to a string */
3331/* */
3332/* eclass is a valid decClass */
3333/* returns a constant string describing the class (max 13+1 chars) */
3334/* ------------------------------------------------------------------ */
3335const char *decNumberClassToString(enum decClass eclass) {
3336 if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;
3337 if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;
3338 if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;
3339 if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;
3340 if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3341 if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3342 if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;
3343 if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;
3344 if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;
3345 if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;
3346 return DEC_ClassString_UN; /* Unknown */
3347 } /* decNumberClassToString */
3348
3349/* ------------------------------------------------------------------ */
3350/* decNumberCopy -- copy a number */
3351/* */
3352/* dest is the target decNumber */
3353/* src is the source decNumber */
3354/* returns dest */
3355/* */
3356/* (dest==src is allowed and is a no-op) */
3357/* All fields are updated as required. This is a utility operation, */
3358/* so special values are unchanged and no error is possible. */
3359/* ------------------------------------------------------------------ */
3360decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3361
3362 #if DECCHECK
3363 if (src==NULL) return decNumberZero(dest);
3364 #endif
3365
3366 if (dest==src) return dest; /* no copy required */
3367
3368 /* Use explicit assignments here as structure assignment could copy */
3369 /* more than just the lsu (for small DECDPUN). This would not affect */
3370 /* the value of the results, but could disturb test harness spill */
3371 /* checking. */
3372 dest->bits=src->bits;
3373 dest->exponent=src->exponent;
3374 dest->digits=src->digits;
3375 dest->lsu[0]=src->lsu[0];
3376 if (src->digits>DECDPUN) { /* more Units to come */
3377 const Unit *smsup, *s; /* work */
3378 Unit *d; /* .. */
3379 /* memcpy for the remaining Units would be safe as they cannot */
3380 /* overlap. However, this explicit loop is faster in short cases. */
3381 d=dest->lsu+1; /* -> first destination */
3382 smsup=src->lsu+D2U(src->digits); /* -> source msu+1 */
3383 for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3384 }
3385 return dest;
3386 } /* decNumberCopy */
3387
3388/* ------------------------------------------------------------------ */
3389/* decNumberCopyAbs -- quiet absolute value operator */
3390/* */
3391/* This sets C = abs(A) */
3392/* */
3393/* res is C, the result. C may be A */
3394/* rhs is A */
3395/* */
3396/* C must have space for set->digits digits. */
3397/* No exception or error can occur; this is a quiet bitwise operation.*/
3398/* See also decNumberAbs for a checking version of this. */
3399/* ------------------------------------------------------------------ */
3400decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3401 #if DECCHECK
3402 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3403 #endif
3404 decNumberCopy(res, rhs);
3405 res->bits&=~DECNEG; /* turn off sign */
3406 return res;
3407 } /* decNumberCopyAbs */
3408
3409/* ------------------------------------------------------------------ */
3410/* decNumberCopyNegate -- quiet negate value operator */
3411/* */
3412/* This sets C = negate(A) */
3413/* */
3414/* res is C, the result. C may be A */
3415/* rhs is A */
3416/* */
3417/* C must have space for set->digits digits. */
3418/* No exception or error can occur; this is a quiet bitwise operation.*/
3419/* See also decNumberMinus for a checking version of this. */
3420/* ------------------------------------------------------------------ */
3421decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3422 #if DECCHECK
3423 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3424 #endif
3425 decNumberCopy(res, rhs);
3426 res->bits^=DECNEG; /* invert the sign */
3427 return res;
3428 } /* decNumberCopyNegate */
3429
3430/* ------------------------------------------------------------------ */
3431/* decNumberCopySign -- quiet copy and set sign operator */
3432/* */
3433/* This sets C = A with the sign of B */
3434/* */
3435/* res is C, the result. C may be A */
3436/* lhs is A */
3437/* rhs is B */
3438/* */
3439/* C must have space for set->digits digits. */
3440/* No exception or error can occur; this is a quiet bitwise operation.*/
3441/* ------------------------------------------------------------------ */
3442decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3443 const decNumber *rhs) {
3444 uByte sign; /* rhs sign */
3445 #if DECCHECK
3446 if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3447 #endif
3448 sign=rhs->bits & DECNEG; /* save sign bit */
3449 decNumberCopy(res, lhs);
3450 res->bits&=~DECNEG; /* clear the sign */
3451 res->bits|=sign; /* set from rhs */
3452 return res;
3453 } /* decNumberCopySign */
3454
3455/* ------------------------------------------------------------------ */
3456/* decNumberGetBCD -- get the coefficient in BCD8 */
3457/* dn is the source decNumber */
3458/* bcd is the uInt array that will receive dn->digits BCD bytes, */
3459/* most-significant at offset 0 */
3460/* returns bcd */
3461/* */
3462/* bcd must have at least dn->digits bytes. No error is possible; if */
3463/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */
3464/* ------------------------------------------------------------------ */
3465uByte * decNumberGetBCD(const decNumber *dn, uint8_t *bcd) {
3466 uByte *ub=bcd+dn->digits-1; /* -> lsd */
3467 const Unit *up=dn->lsu; /* Unit pointer, -> lsu */
3468
3469 #if DECDPUN==1 /* trivial simple copy */
3470 for (; ub>=bcd; ub--, up++) *ub=*up;
3471 #else /* chopping needed */
3472 uInt u=*up; /* work */
3473 uInt cut=DECDPUN; /* downcounter through unit */
3474 for (; ub>=bcd; ub--) {
3475 *ub=(uByte)(u%10); /* [*6554 trick inhibits, here] */
3476 u=u/10;
3477 cut--;
3478 if (cut>0) continue; /* more in this unit */
3479 up++;
3480 u=*up;
3481 cut=DECDPUN;
3482 }
3483 #endif
3484 return bcd;
3485 } /* decNumberGetBCD */
3486
3487/* ------------------------------------------------------------------ */
3488/* decNumberSetBCD -- set (replace) the coefficient from BCD8 */
3489/* dn is the target decNumber */
3490/* bcd is the uInt array that will source n BCD bytes, most- */
3491/* significant at offset 0 */
3492/* n is the number of digits in the source BCD array (bcd) */
3493/* returns dn */
3494/* */
3495/* dn must have space for at least n digits. No error is possible; */
3496/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */
3497/* and bcd[0] zero. */
3498/* ------------------------------------------------------------------ */
3499decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3500 Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [target pointer] */
3501 const uByte *ub=bcd; /* -> source msd */
3502
3503 #if DECDPUN==1 /* trivial simple copy */
3504 for (; ub<bcd+n; ub++, up--) *up=*ub;
3505 #else /* some assembly needed */
3506 /* calculate how many digits in msu, and hence first cut */
3507 Int cut=MSUDIGITS(n); /* [faster than remainder] */
3508 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3509 *up=0; /* will take <=DECDPUN digits */
3510 for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3511 cut=DECDPUN; /* next Unit has all digits */
3512 }
3513 #endif
3514 dn->digits=n; /* set digit count */
3515 return dn;
3516 } /* decNumberSetBCD */
3517
3518/* ------------------------------------------------------------------ */
3519/* decNumberIsNormal -- test normality of a decNumber */
3520/* dn is the decNumber to test */
3521/* set is the context to use for Emin */
3522/* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */
3523/* ------------------------------------------------------------------ */
3524Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3525 Int ae; /* adjusted exponent */
3526 #if DECCHECK
3527 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3528 #endif
3529
3530 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3531 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3532
3533 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3534 if (ae<set->emin) return 0; /* is subnormal */
3535 return 1;
3536 } /* decNumberIsNormal */
3537
3538/* ------------------------------------------------------------------ */
3539/* decNumberIsSubnormal -- test subnormality of a decNumber */
3540/* dn is the decNumber to test */
3541/* set is the context to use for Emin */
3542/* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */
3543/* ------------------------------------------------------------------ */
3544Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3545 Int ae; /* adjusted exponent */
3546 #if DECCHECK
3547 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3548 #endif
3549
3550 if (decNumberIsSpecial(dn)) return 0; /* not finite */
3551 if (decNumberIsZero(dn)) return 0; /* not non-zero */
3552
3553 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
3554 if (ae<set->emin) return 1; /* is subnormal */
3555 return 0;
3556 } /* decNumberIsSubnormal */
3557
3558/* ------------------------------------------------------------------ */
3559/* decNumberTrim -- remove insignificant zeros */
3560/* */
3561/* dn is the number to trim */
3562/* returns dn */
3563/* */
3564/* All fields are updated as required. This is a utility operation, */
3565/* so special values are unchanged and no error is possible. */
3566/* ------------------------------------------------------------------ */
3567decNumber * decNumberTrim(decNumber *dn) {
3568 Int dropped; /* work */
3569 decContext set; /* .. */
3570 #if DECCHECK
3571 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3572 #endif
3573 decContextDefault(&set, DEC_INIT_BASE); /* clamp=0 */
3574 return decTrim(dn, &set, 0, &dropped);
3575 } /* decNumberTrim */
3576
3577/* ------------------------------------------------------------------ */
3578/* decNumberVersion -- return the name and version of this module */
3579/* */
3580/* No error is possible. */
3581/* ------------------------------------------------------------------ */
3582const char * decNumberVersion(void) {
3583 return DECVERSION;
3584 } /* decNumberVersion */
3585
3586/* ------------------------------------------------------------------ */
3587/* decNumberZero -- set a number to 0 */
3588/* */
3589/* dn is the number to set, with space for one digit */
3590/* returns dn */
3591/* */
3592/* No error is possible. */
3593/* ------------------------------------------------------------------ */
3594/* Memset is not used as it is much slower in some environments. */
3595decNumber * decNumberZero(decNumber *dn) {
3596
3597 #if DECCHECK
3598 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3599 #endif
3600
3601 dn->bits=0;
3602 dn->exponent=0;
3603 dn->digits=1;
3604 dn->lsu[0]=0;
3605 return dn;
3606 } /* decNumberZero */
3607
3608/* ================================================================== */
3609/* Local routines */
3610/* ================================================================== */
3611
3612/* ------------------------------------------------------------------ */
3613/* decToString -- lay out a number into a string */
3614/* */
3615/* dn is the number to lay out */
3616/* string is where to lay out the number */
3617/* eng is 1 if Engineering, 0 if Scientific */
3618/* */
3619/* string must be at least dn->digits+14 characters long */
3620/* No error is possible. */
3621/* */
3622/* Note that this routine can generate a -0 or 0.000. These are */
3623/* never generated in subset to-number or arithmetic, but can occur */
3624/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */
3625/* ------------------------------------------------------------------ */
3626/* If DECCHECK is enabled the string "?" is returned if a number is */
3627/* invalid. */
3628static void decToString(const decNumber *dn, char *string, Flag eng) {
3629 Int exp=dn->exponent; /* local copy */
3630 Int e; /* E-part value */
3631 Int pre; /* digits before the '.' */
3632 Int cut; /* for counting digits in a Unit */
3633 char *c=string; /* work [output pointer] */
3634 const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3635 uInt u, pow; /* work */
3636
3637 #if DECCHECK
3638 if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3639 strcpy(string, "?");
3640 return;}
3641 #endif
3642
3643 if (decNumberIsNegative(dn)) { /* Negatives get a minus */
3644 *c='-';
3645 c++;
3646 }
3647 if (dn->bits&DECSPECIAL) { /* Is a special value */
3648 if (decNumberIsInfinite(dn)) {
3649 strcpy(c, "Inf");
3650 strcpy(c+3, "inity");
3651 return;}
3652 /* a NaN */
3653 if (dn->bits&DECSNAN) { /* signalling NaN */
3654 *c='s';
3655 c++;
3656 }
3657 strcpy(c, "NaN");
3658 c+=3; /* step past */
3659 /* if not a clean non-zero coefficient, that's all there is in a */
3660 /* NaN string */
3661 if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3662 /* [drop through to add integer] */
3663 }
3664
3665 /* calculate how many digits in msu, and hence first cut */
3666 cut=MSUDIGITS(dn->digits); /* [faster than remainder] */
3667 cut--; /* power of ten for digit */
3668
3669 if (exp==0) { /* simple integer [common fastpath] */
3670 for (;up>=dn->lsu; up--) { /* each Unit from msu */
3671 u=*up; /* contains DECDPUN digits to lay out */
3672 for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3673 cut=DECDPUN-1; /* next Unit has all digits */
3674 }
3675 *c='\0'; /* terminate the string */
3676 return;}
3677
3678 /* non-0 exponent -- assume plain form */
3679 pre=dn->digits+exp; /* digits before '.' */
3680 e=0; /* no E */
3681 if ((exp>0) || (pre<-5)) { /* need exponential form */
3682 e=exp+dn->digits-1; /* calculate E value */
3683 pre=1; /* assume one digit before '.' */
3684 if (eng && (e!=0)) { /* engineering: may need to adjust */
3685 Int adj; /* adjustment */
3686 /* The C remainder operator is undefined for negative numbers, so */
3687 /* a positive remainder calculation must be used here */
3688 if (e<0) {
3689 adj=(-e)%3;
3690 if (adj!=0) adj=3-adj;
3691 }
3692 else { /* e>0 */
3693 adj=e%3;
3694 }
3695 e=e-adj;
3696 /* if dealing with zero still produce an exponent which is a */
3697 /* multiple of three, as expected, but there will only be the */
3698 /* one zero before the E, still. Otherwise note the padding. */
3699 if (!ISZERO(dn)) pre+=adj;
3700 else { /* is zero */
3701 if (adj!=0) { /* 0.00Esnn needed */
3702 e=e+3;
3703 pre=-(2-adj);
3704 }
3705 } /* zero */
3706 } /* eng */
3707 } /* need exponent */
3708
3709 /* lay out the digits of the coefficient, adding 0s and . as needed */
3710 u=*up;
3711 if (pre>0) { /* xxx.xxx or xx00 (engineering) form */
3712 Int n=pre;
3713 for (; pre>0; pre--, c++, cut--) {
3714 if (cut<0) { /* need new Unit */
3715 if (up==dn->lsu) break; /* out of input digits (pre>digits) */
3716 up--;
3717 cut=DECDPUN-1;
3718 u=*up;
3719 }
3720 TODIGIT(u, cut, c, pow);
3721 }
3722 if (n<dn->digits) { /* more to come, after '.' */
3723 *c='.'; c++;
3724 for (;; c++, cut--) {
3725 if (cut<0) { /* need new Unit */
3726 if (up==dn->lsu) break; /* out of input digits */
3727 up--;
3728 cut=DECDPUN-1;
3729 u=*up;
3730 }
3731 TODIGIT(u, cut, c, pow);
3732 }
3733 }
3734 else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3735 }
3736 else { /* 0.xxx or 0.000xxx form */
3737 *c='0'; c++;
3738 *c='.'; c++;
3739 for (; pre<0; pre++, c++) *c='0'; /* add any 0's after '.' */
3740 for (; ; c++, cut--) {
3741 if (cut<0) { /* need new Unit */
3742 if (up==dn->lsu) break; /* out of input digits */
3743 up--;
3744 cut=DECDPUN-1;
3745 u=*up;
3746 }
3747 TODIGIT(u, cut, c, pow);
3748 }
3749 }
3750
3751 /* Finally add the E-part, if needed. It will never be 0, has a
3752 base maximum and minimum of +999999999 through -999999999, but
3753 could range down to -1999999998 for anormal numbers */
3754 if (e!=0) {
3755 Flag had=0; /* 1=had non-zero */
3756 *c='E'; c++;
3757 *c='+'; c++; /* assume positive */
3758 u=e; /* .. */
3759 if (e<0) {
3760 *(c-1)='-'; /* oops, need - */
3761 u=-e; /* uInt, please */
3762 }
3763 /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3764 for (cut=9; cut>=0; cut--) {
3765 TODIGIT(u, cut, c, pow);
3766 if (*c=='0' && !had) continue; /* skip leading zeros */
3767 had=1; /* had non-0 */
3768 c++; /* step for next */
3769 } /* cut */
3770 }
3771 *c='\0'; /* terminate the string (all paths) */
3772 return;
3773 } /* decToString */
3774
3775/* ------------------------------------------------------------------ */
3776/* decAddOp -- add/subtract operation */
3777/* */
3778/* This computes C = A + B */
3779/* */
3780/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
3781/* lhs is A */
3782/* rhs is B */
3783/* set is the context */
3784/* negate is DECNEG if rhs should be negated, or 0 otherwise */
3785/* status accumulates status for the caller */
3786/* */
3787/* C must have space for set->digits digits. */
3788/* Inexact in status must be 0 for correct Exact zero sign in result */
3789/* ------------------------------------------------------------------ */
3790/* If possible, the coefficient is calculated directly into C. */
3791/* However, if: */
3792/* -- a digits+1 calculation is needed because the numbers are */
3793/* unaligned and span more than set->digits digits */
3794/* -- a carry to digits+1 digits looks possible */
3795/* -- C is the same as A or B, and the result would destructively */
3796/* overlap the A or B coefficient */
3797/* then the result must be calculated into a temporary buffer. In */
3798/* this case a local (stack) buffer is used if possible, and only if */
3799/* too long for that does malloc become the final resort. */
3800/* */
3801/* Misalignment is handled as follows: */
3802/* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */
3803/* BPad: Apply the padding by a combination of shifting (whole */
3804/* units) and multiplication (part units). */
3805/* */
3806/* Addition, especially x=x+1, is speed-critical. */
3807/* The static buffer is larger than might be expected to allow for */
3808/* calls from higher-level funtions (notable exp). */
3809/* ------------------------------------------------------------------ */
3810static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3811 const decNumber *rhs, decContext *set,
3812 uByte negate, uInt *status) {
3813 #if DECSUBSET
3814 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
3815 decNumber *allocrhs=NULL; /* .., rhs */
3816 #endif
3817 Int rhsshift; /* working shift (in Units) */
3818 Int maxdigits; /* longest logical length */
3819 Int mult; /* multiplier */
3820 Int residue; /* rounding accumulator */
3821 uByte bits; /* result bits */
3822 Flag diffsign; /* non-0 if arguments have different sign */
3823 Unit *acc; /* accumulator for result */
3824 Unit accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3825 /* allocations when called from */
3826 /* other operations, notable exp] */
3827 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
3828 Int reqdigits=set->digits; /* local copy; requested DIGITS */
3829 Int padding; /* work */
3830
3831 #if DECCHECK
3832 if (decCheckOperands(res, lhs, rhs, set)) return res;
3833 #endif
3834
3835 do { /* protect allocated storage */
3836 #if DECSUBSET
3837 if (!set->extended) {
3838 /* reduce operands and set lostDigits status, as needed */
3839 if (lhs->digits>reqdigits) {
3840 alloclhs=decRoundOperand(lhs, set, status);
3841 if (alloclhs==NULL) break;
3842 lhs=alloclhs;
3843 }
3844 if (rhs->digits>reqdigits) {
3845 allocrhs=decRoundOperand(rhs, set, status);
3846 if (allocrhs==NULL) break;
3847 rhs=allocrhs;
3848 }
3849 }
3850 #endif
3851 /* [following code does not require input rounding] */
3852
3853 /* note whether signs differ [used all paths] */
3854 diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3855
3856 /* handle infinities and NaNs */
3857 if (SPECIALARGS) { /* a special bit set */
3858 if (SPECIALARGS & (DECSNAN | DECNAN)) /* a NaN */
3859 decNaNs(res, lhs, rhs, set, status);
3860 else { /* one or two infinities */
3861 if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3862 /* two infinities with different signs is invalid */
3863 if (decNumberIsInfinite(rhs) && diffsign) {
3864 *status|=DEC_Invalid_operation;
3865 break;
3866 }
3867 bits=lhs->bits & DECNEG; /* get sign from LHS */
3868 }
3869 else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3870 bits|=DECINF;
3871 decNumberZero(res);
3872 res->bits=bits; /* set +/- infinity */
3873 } /* an infinity */
3874 break;
3875 }
3876
3877 /* Quick exit for add 0s; return the non-0, modified as need be */
3878 if (ISZERO(lhs)) {
3879 Int adjust; /* work */
3880 Int lexp=lhs->exponent; /* save in case LHS==RES */
3881 bits=lhs->bits; /* .. */
3882 residue=0; /* clear accumulator */
3883 decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3884 res->bits^=negate; /* flip if rhs was negated */
3885 #if DECSUBSET
3886 if (set->extended) { /* exponents on zeros count */
3887 #endif
3888 /* exponent will be the lower of the two */
3889 adjust=lexp-res->exponent; /* adjustment needed [if -ve] */
3890 if (ISZERO(res)) { /* both 0: special IEEE 854 rules */
3891 if (adjust<0) res->exponent=lexp; /* set exponent */
3892 /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3893 if (diffsign) {
3894 if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3895 else res->bits=DECNEG; /* preserve 0 sign */
3896 }
3897 }
3898 else { /* non-0 res */
3899 if (adjust<0) { /* 0-padding needed */
3900 if ((res->digits-adjust)>set->digits) {
3901 adjust=res->digits-set->digits; /* to fit exactly */
3902 *status|=DEC_Rounded; /* [but exact] */
3903 }
3904 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3905 res->exponent+=adjust; /* set the exponent. */
3906 }
3907 } /* non-0 res */
3908 #if DECSUBSET
3909 } /* extended */
3910 #endif
3911 decFinish(res, set, &residue, status); /* clean and finalize */
3912 break;}
3913
3914 if (ISZERO(rhs)) { /* [lhs is non-zero] */
3915 Int adjust; /* work */
3916 Int rexp=rhs->exponent; /* save in case RHS==RES */
3917 bits=rhs->bits; /* be clean */
3918 residue=0; /* clear accumulator */
3919 decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3920 #if DECSUBSET
3921 if (set->extended) { /* exponents on zeros count */
3922 #endif
3923 /* exponent will be the lower of the two */
3924 /* [0-0 case handled above] */
3925 adjust=rexp-res->exponent; /* adjustment needed [if -ve] */
3926 if (adjust<0) { /* 0-padding needed */
3927 if ((res->digits-adjust)>set->digits) {
3928 adjust=res->digits-set->digits; /* to fit exactly */
3929 *status|=DEC_Rounded; /* [but exact] */
3930 }
3931 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3932 res->exponent+=adjust; /* set the exponent. */
3933 }
3934 #if DECSUBSET
3935 } /* extended */
3936 #endif
3937 decFinish(res, set, &residue, status); /* clean and finalize */
3938 break;}
3939
3940 /* [NB: both fastpath and mainpath code below assume these cases */
3941 /* (notably 0-0) have already been handled] */
3942
3943 /* calculate the padding needed to align the operands */
3944 padding=rhs->exponent-lhs->exponent;
3945
3946 /* Fastpath cases where the numbers are aligned and normal, the RHS */
3947 /* is all in one unit, no operand rounding is needed, and no carry, */
3948 /* lengthening, or borrow is needed */
3949 if (padding==0
3950 && rhs->digits<=DECDPUN
3951 && rhs->exponent>=set->emin /* [some normals drop through] */
3952 && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3953 && rhs->digits<=reqdigits
3954 && lhs->digits<=reqdigits) {
3955 Int partial=*lhs->lsu;
3956 if (!diffsign) { /* adding */
3957 partial+=*rhs->lsu;
3958 if ((partial<=DECDPUNMAX) /* result fits in unit */
3959 && (lhs->digits>=DECDPUN || /* .. and no digits-count change */
3960 partial<(Int)powers[lhs->digits])) { /* .. */
3961 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
3962 *res->lsu=(Unit)partial; /* [copy could have overwritten RHS] */
3963 break;
3964 }
3965 /* else drop out for careful add */
3966 }
3967 else { /* signs differ */
3968 partial-=*rhs->lsu;
3969 if (partial>0) { /* no borrow needed, and non-0 result */
3970 if (res!=lhs) decNumberCopy(res, lhs); /* not in place */
3971 *res->lsu=(Unit)partial;
3972 /* this could have reduced digits [but result>0] */
3973 res->digits=decGetDigits(res->lsu, D2U(res->digits));
3974 break;
3975 }
3976 /* else drop out for careful subtract */
3977 }
3978 }
3979
3980 /* Now align (pad) the lhs or rhs so they can be added or */
3981 /* subtracted, as necessary. If one number is much larger than */
3982 /* the other (that is, if in plain form there is a least one */
3983 /* digit between the lowest digit of one and the highest of the */
3984 /* other) padding with up to DIGITS-1 trailing zeros may be */
3985 /* needed; then apply rounding (as exotic rounding modes may be */
3986 /* affected by the residue). */
3987 rhsshift=0; /* rhs shift to left (padding) in Units */
3988 bits=lhs->bits; /* assume sign is that of LHS */
3989 mult=1; /* likely multiplier */
3990
3991 /* [if padding==0 the operands are aligned; no padding is needed] */
3992 if (padding!=0) {
3993 /* some padding needed; always pad the RHS, as any required */
3994 /* padding can then be effected by a simple combination of */
3995 /* shifts and a multiply */
3996 Flag swapped=0;
3997 if (padding<0) { /* LHS needs the padding */
3998 const decNumber *t;
3999 padding=-padding; /* will be +ve */
4000 bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
4001 t=lhs; lhs=rhs; rhs=t;
4002 swapped=1;
4003 }
4004
4005 /* If, after pad, rhs would be longer than lhs by digits+1 or */
4006 /* more then lhs cannot affect the answer, except as a residue, */
4007 /* so only need to pad up to a length of DIGITS+1. */
4008 if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4009 /* The RHS is sufficient */
4010 /* for residue use the relative sign indication... */
4011 Int shift=reqdigits-rhs->digits; /* left shift needed */
4012 residue=1; /* residue for rounding */
4013 if (diffsign) residue=-residue; /* signs differ */
4014 /* copy, shortening if necessary */
4015 decCopyFit(res, rhs, set, &residue, status);
4016 /* if it was already shorter, then need to pad with zeros */
4017 if (shift>0) {
4018 res->digits=decShiftToMost(res->lsu, res->digits, shift);
4019 res->exponent-=shift; /* adjust the exponent. */
4020 }
4021 /* flip the result sign if unswapped and rhs was negated */
4022 if (!swapped) res->bits^=negate;
4023 decFinish(res, set, &residue, status); /* done */
4024 break;}
4025
4026 /* LHS digits may affect result */
4027 rhsshift=D2U(padding+1)-1; /* this much by Unit shift .. */
4028 mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
4029 } /* padding needed */
4030
4031 if (diffsign) mult=-mult; /* signs differ */
4032
4033 /* determine the longer operand */
4034 maxdigits=rhs->digits+padding; /* virtual length of RHS */
4035 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4036
4037 /* Decide on the result buffer to use; if possible place directly */
4038 /* into result. */
4039 acc=res->lsu; /* assume add direct to result */
4040 /* If destructive overlap, or the number is too long, or a carry or */
4041 /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4042 /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4043 if ((maxdigits>=reqdigits) /* is, or could be, too large */
4044 || (res==rhs && rhsshift>0)) { /* destructive overlap */
4045 /* buffer needed, choose it; units for maxdigits digits will be */
4046 /* needed, +1 Unit for carry or borrow */
4047 Int need=D2U(maxdigits)+1;
4048 acc=accbuff; /* assume use local buffer */
4049 if (need*sizeof(Unit)>sizeof(accbuff)) {
4050 /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4051 allocacc=(Unit *)malloc(need*sizeof(Unit));
4052 if (allocacc==NULL) { /* hopeless -- abandon */
4053 *status|=DEC_Insufficient_storage;
4054 break;}
4055 acc=allocacc;
4056 }
4057 }
4058
4059 res->bits=(uByte)(bits&DECNEG); /* it's now safe to overwrite.. */
4060 res->exponent=lhs->exponent; /* .. operands (even if aliased) */
4061
4062 #if DECTRACE
4063 decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4064 decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4065 printf(" :h: %ld %ld\n", rhsshift, mult);
4066 #endif
4067
4068 /* add [A+B*m] or subtract [A+B*(-m)] */
4069 res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4070 rhs->lsu, D2U(rhs->digits),
4071 rhsshift, acc, mult)
4072 *DECDPUN; /* [units -> digits] */
4073 if (res->digits<0) { /* borrowed... */
4074 res->digits=-res->digits;
4075 res->bits^=DECNEG; /* flip the sign */
4076 }
4077 #if DECTRACE
4078 decDumpAr('+', acc, D2U(res->digits));
4079 #endif
4080
4081 /* If a buffer was used the result must be copied back, possibly */
4082 /* shortening. (If no buffer was used then the result must have */
4083 /* fit, so can't need rounding and residue must be 0.) */
4084 residue=0; /* clear accumulator */
4085 if (acc!=res->lsu) {
4086 #if DECSUBSET
4087 if (set->extended) { /* round from first significant digit */
4088 #endif
4089 /* remove leading zeros that were added due to rounding up to */
4090 /* integral Units -- before the test for rounding. */
4091 if (res->digits>reqdigits)
4092 res->digits=decGetDigits(acc, D2U(res->digits));
4093 decSetCoeff(res, set, acc, res->digits, &residue, status);
4094 #if DECSUBSET
4095 }
4096 else { /* subset arithmetic rounds from original significant digit */
4097 /* May have an underestimate. This only occurs when both */
4098 /* numbers fit in DECDPUN digits and are padding with a */
4099 /* negative multiple (-10, -100...) and the top digit(s) become */
4100 /* 0. (This only matters when using X3.274 rules where the */
4101 /* leading zero could be included in the rounding.) */
4102 if (res->digits<maxdigits) {
4103 *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4104 res->digits=maxdigits;
4105 }
4106 else {
4107 /* remove leading zeros that added due to rounding up to */
4108 /* integral Units (but only those in excess of the original */
4109 /* maxdigits length, unless extended) before test for rounding. */
4110 if (res->digits>reqdigits) {
4111 res->digits=decGetDigits(acc, D2U(res->digits));
4112 if (res->digits<maxdigits) res->digits=maxdigits;
4113 }
4114 }
4115 decSetCoeff(res, set, acc, res->digits, &residue, status);
4116 /* Now apply rounding if needed before removing leading zeros. */
4117 /* This is safe because subnormals are not a possibility */
4118 if (residue!=0) {
4119 decApplyRound(res, set, residue, status);
4120 residue=0; /* did what needed to be done */
4121 }
4122 } /* subset */
4123 #endif
4124 } /* used buffer */
4125
4126 /* strip leading zeros [these were left on in case of subset subtract] */
4127 res->digits=decGetDigits(res->lsu, D2U(res->digits));
4128
4129 /* apply checks and rounding */
4130 decFinish(res, set, &residue, status);
4131
4132 /* "When the sum of two operands with opposite signs is exactly */
4133 /* zero, the sign of that sum shall be '+' in all rounding modes */
4134 /* except round toward -Infinity, in which mode that sign shall be */
4135 /* '-'." [Subset zeros also never have '-', set by decFinish.] */
4136 if (ISZERO(res) && diffsign
4137 #if DECSUBSET
4138 && set->extended
4139 #endif
4140 && (*status&DEC_Inexact)==0) {
4141 if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; /* sign - */
4142 else res->bits&=~DECNEG; /* sign + */
4143 }
4144 } while(0); /* end protected */
4145
4146 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
4147 #if DECSUBSET
4148 if (allocrhs!=NULL) free(allocrhs); /* .. */
4149 if (alloclhs!=NULL) free(alloclhs); /* .. */
4150 #endif
4151 return res;
4152 } /* decAddOp */
4153
4154/* ------------------------------------------------------------------ */
4155/* decDivideOp -- division operation */
4156/* */
4157/* This routine performs the calculations for all four division */
4158/* operators (divide, divideInteger, remainder, remainderNear). */
4159/* */
4160/* C=A op B */
4161/* */
4162/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
4163/* lhs is A */
4164/* rhs is B */
4165/* set is the context */
4166/* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */
4167/* status is the usual accumulator */
4168/* */
4169/* C must have space for set->digits digits. */
4170/* */
4171/* ------------------------------------------------------------------ */
4172/* The underlying algorithm of this routine is the same as in the */
4173/* 1981 S/370 implementation, that is, non-restoring long division */
4174/* with bi-unit (rather than bi-digit) estimation for each unit */
4175/* multiplier. In this pseudocode overview, complications for the */
4176/* Remainder operators and division residues for exact rounding are */
4177/* omitted for clarity. */
4178/* */
4179/* Prepare operands and handle special values */
4180/* Test for x/0 and then 0/x */
4181/* Exp =Exp1 - Exp2 */
4182/* Exp =Exp +len(var1) -len(var2) */
4183/* Sign=Sign1 * Sign2 */
4184/* Pad accumulator (Var1) to double-length with 0's (pad1) */
4185/* Pad Var2 to same length as Var1 */
4186/* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */
4187/* have=0 */
4188/* Do until (have=digits+1 OR residue=0) */
4189/* if exp<0 then if integer divide/residue then leave */
4190/* this_unit=0 */
4191/* Do forever */
4192/* compare numbers */
4193/* if <0 then leave inner_loop */
4194/* if =0 then (* quick exit without subtract *) do */
4195/* this_unit=this_unit+1; output this_unit */
4196/* leave outer_loop; end */
4197/* Compare lengths of numbers (mantissae): */
4198/* If same then tops2=msu2pair -- {units 1&2 of var2} */
4199/* else tops2=msu2plus -- {0, unit 1 of var2} */
4200/* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4201/* mult=tops1/tops2 -- Good and safe guess at divisor */
4202/* if mult=0 then mult=1 */
4203/* this_unit=this_unit+mult */
4204/* subtract */
4205/* end inner_loop */
4206/* if have\=0 | this_unit\=0 then do */
4207/* output this_unit */
4208/* have=have+1; end */
4209/* var2=var2/10 */
4210/* exp=exp-1 */
4211/* end outer_loop */
4212/* exp=exp+1 -- set the proper exponent */
4213/* if have=0 then generate answer=0 */
4214/* Return (Result is defined by Var1) */
4215/* */
4216/* ------------------------------------------------------------------ */
4217/* Two working buffers are needed during the division; one (digits+ */
4218/* 1) to accumulate the result, and the other (up to 2*digits+1) for */
4219/* long subtractions. These are acc and var1 respectively. */
4220/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4221/* The static buffers may be larger than might be expected to allow */
4222/* for calls from higher-level funtions (notable exp). */
4223/* ------------------------------------------------------------------ */
4224static decNumber * decDivideOp(decNumber *res,
4225 const decNumber *lhs, const decNumber *rhs,
4226 decContext *set, Flag op, uInt *status) {
4227 #if DECSUBSET
4228 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
4229 decNumber *allocrhs=NULL; /* .., rhs */
4230 #endif
4231 Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4232 Unit *acc=accbuff; /* -> accumulator array for result */
4233 Unit *allocacc=NULL; /* -> allocated buffer, iff allocated */
4234 Unit *accnext; /* -> where next digit will go */
4235 Int acclength; /* length of acc needed [Units] */
4236 Int accunits; /* count of units accumulated */
4237 Int accdigits; /* count of digits accumulated */
4238
4239 Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)*sizeof(Unit)]; /* buffer for var1 */
4240 Unit *var1=varbuff; /* -> var1 array for long subtraction */
4241 Unit *varalloc=NULL; /* -> allocated buffer, iff used */
4242 Unit *msu1; /* -> msu of var1 */
4243
4244 const Unit *var2; /* -> var2 array */
4245 const Unit *msu2; /* -> msu of var2 */
4246 Int msu2plus; /* msu2 plus one [does not vary] */
4247 eInt msu2pair; /* msu2 pair plus one [does not vary] */
4248
4249 Int var1units, var2units; /* actual lengths */
4250 Int var2ulen; /* logical length (units) */
4251 Int var1initpad=0; /* var1 initial padding (digits) */
4252 Int maxdigits; /* longest LHS or required acc length */
4253 Int mult; /* multiplier for subtraction */
4254 Unit thisunit; /* current unit being accumulated */
4255 Int residue; /* for rounding */
4256 Int reqdigits=set->digits; /* requested DIGITS */
4257 Int exponent; /* working exponent */
4258 Int maxexponent=0; /* DIVIDE maximum exponent if unrounded */
4259 uByte bits; /* working sign */
4260 Unit *target; /* work */
4261 const Unit *source; /* .. */
4262 uInt const *pow; /* .. */
4263 Int shift, cut; /* .. */
4264 #if DECSUBSET
4265 Int dropped; /* work */
4266 #endif
4267
4268 #if DECCHECK
4269 if (decCheckOperands(res, lhs, rhs, set)) return res;
4270 #endif
4271
4272 do { /* protect allocated storage */
4273 #if DECSUBSET
4274 if (!set->extended) {
4275 /* reduce operands and set lostDigits status, as needed */
4276 if (lhs->digits>reqdigits) {
4277 alloclhs=decRoundOperand(lhs, set, status);
4278 if (alloclhs==NULL) break;
4279 lhs=alloclhs;
4280 }
4281 if (rhs->digits>reqdigits) {
4282 allocrhs=decRoundOperand(rhs, set, status);
4283 if (allocrhs==NULL) break;
4284 rhs=allocrhs;
4285 }
4286 }
4287 #endif
4288 /* [following code does not require input rounding] */
4289
4290 bits=(lhs->bits^rhs->bits)&DECNEG; /* assumed sign for divisions */
4291
4292 /* handle infinities and NaNs */
4293 if (SPECIALARGS) { /* a special bit set */
4294 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4295 decNaNs(res, lhs, rhs, set, status);
4296 break;
4297 }
4298 /* one or two infinities */
4299 if (decNumberIsInfinite(lhs)) { /* LHS (dividend) is infinite */
4300 if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4301 op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4302 *status|=DEC_Invalid_operation;
4303 break;
4304 }
4305 /* [Note that infinity/0 raises no exceptions] */
4306 decNumberZero(res);
4307 res->bits=bits|DECINF; /* set +/- infinity */
4308 break;
4309 }
4310 else { /* RHS (divisor) is infinite */
4311 residue=0;
4312 if (op&(REMAINDER|REMNEAR)) {
4313 /* result is [finished clone of] lhs */
4314 decCopyFit(res, lhs, set, &residue, status);
4315 }
4316 else { /* a division */
4317 decNumberZero(res);
4318 res->bits=bits; /* set +/- zero */
4319 /* for DIVIDEINT the exponent is always 0. For DIVIDE, result */
4320 /* is a 0 with infinitely negative exponent, clamped to minimum */
4321 if (op&DIVIDE) {
4322 res->exponent=set->emin-set->digits+1;
4323 *status|=DEC_Clamped;
4324 }
4325 }
4326 decFinish(res, set, &residue, status);
4327 break;
4328 }
4329 }
4330
4331 /* handle 0 rhs (x/0) */
4332 if (ISZERO(rhs)) { /* x/0 is always exceptional */
4333 if (ISZERO(lhs)) {
4334 decNumberZero(res); /* [after lhs test] */
4335 *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4336 }
4337 else {
4338 decNumberZero(res);
4339 if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4340 else {
4341 *status|=DEC_Division_by_zero; /* x/0 */
4342 res->bits=bits|DECINF; /* .. is +/- Infinity */
4343 }
4344 }
4345 break;}
4346
4347 /* handle 0 lhs (0/x) */
4348 if (ISZERO(lhs)) { /* 0/x [x!=0] */
4349 #if DECSUBSET
4350 if (!set->extended) decNumberZero(res);
4351 else {
4352 #endif
4353 if (op&DIVIDE) {
4354 residue=0;
4355 exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4356 decNumberCopy(res, lhs); /* [zeros always fit] */
4357 res->bits=bits; /* sign as computed */
4358 res->exponent=exponent; /* exponent, too */
4359 decFinalize(res, set, &residue, status); /* check exponent */
4360 }
4361 else if (op&DIVIDEINT) {
4362 decNumberZero(res); /* integer 0 */
4363 res->bits=bits; /* sign as computed */
4364 }
4365 else { /* a remainder */
4366 exponent=rhs->exponent; /* [save in case overwrite] */
4367 decNumberCopy(res, lhs); /* [zeros always fit] */
4368 if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4369 }
4370 #if DECSUBSET
4371 }
4372 #endif
4373 break;}
4374
4375 /* Precalculate exponent. This starts off adjusted (and hence fits */
4376 /* in 31 bits) and becomes the usual unadjusted exponent as the */
4377 /* division proceeds. The order of evaluation is important, here, */
4378 /* to avoid wrap. */
4379 exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4380
4381 /* If the working exponent is -ve, then some quick exits are */
4382 /* possible because the quotient is known to be <1 */
4383 /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4384 if (exponent<0 && !(op==DIVIDE)) {
4385 if (op&DIVIDEINT) {
4386 decNumberZero(res); /* integer part is 0 */
4387 #if DECSUBSET
4388 if (set->extended)
4389 #endif
4390 res->bits=bits; /* set +/- zero */
4391 break;}
4392 /* fastpath remainders so long as the lhs has the smaller */
4393 /* (or equal) exponent */
4394 if (lhs->exponent<=rhs->exponent) {
4395 if (op&REMAINDER || exponent<-1) {
4396 /* It is REMAINDER or safe REMNEAR; result is [finished */
4397 /* clone of] lhs (r = x - 0*y) */
4398 residue=0;
4399 decCopyFit(res, lhs, set, &residue, status);
4400 decFinish(res, set, &residue, status);
4401 break;
4402 }
4403 /* [unsafe REMNEAR drops through] */
4404 }
4405 } /* fastpaths */
4406
4407 /* Long (slow) division is needed; roll up the sleeves... */
4408
4409 /* The accumulator will hold the quotient of the division. */
4410 /* If it needs to be too long for stack storage, then allocate. */
4411 acclength=D2U(reqdigits+DECDPUN); /* in Units */
4412 if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4413 /* printf("malloc dvacc %ld units\n", acclength); */
4414 allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4415 if (allocacc==NULL) { /* hopeless -- abandon */
4416 *status|=DEC_Insufficient_storage;
4417 break;}
4418 acc=allocacc; /* use the allocated space */
4419 }
4420
4421 /* var1 is the padded LHS ready for subtractions. */
4422 /* If it needs to be too long for stack storage, then allocate. */
4423 /* The maximum units needed for var1 (long subtraction) is: */
4424 /* Enough for */
4425 /* (rhs->digits+reqdigits-1) -- to allow full slide to right */
4426 /* or (lhs->digits) -- to allow for long lhs */
4427 /* whichever is larger */
4428 /* +1 -- for rounding of slide to right */
4429 /* +1 -- for leading 0s */
4430 /* +1 -- for pre-adjust if a remainder or DIVIDEINT */
4431 /* [Note: unused units do not participate in decUnitAddSub data] */
4432 maxdigits=rhs->digits+reqdigits-1;
4433 if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4434 var1units=D2U(maxdigits)+2;
4435 /* allocate a guard unit above msu1 for REMAINDERNEAR */
4436 if (!(op&DIVIDE)) var1units++;
4437 if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4438 /* printf("malloc dvvar %ld units\n", var1units+1); */
4439 varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4440 if (varalloc==NULL) { /* hopeless -- abandon */
4441 *status|=DEC_Insufficient_storage;
4442 break;}
4443 var1=varalloc; /* use the allocated space */
4444 }
4445
4446 /* Extend the lhs and rhs to full long subtraction length. The lhs */
4447 /* is truly extended into the var1 buffer, with 0 padding, so a */
4448 /* subtract in place is always possible. The rhs (var2) has */
4449 /* virtual padding (implemented by decUnitAddSub). */
4450 /* One guard unit was allocated above msu1 for rem=rem+rem in */
4451 /* REMAINDERNEAR. */
4452 msu1=var1+var1units-1; /* msu of var1 */
4453 source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4454 for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4455 for (; target>=var1; target--) *target=0;
4456
4457 /* rhs (var2) is left-aligned with var1 at the start */
4458 var2ulen=var1units; /* rhs logical length (units) */
4459 var2units=D2U(rhs->digits); /* rhs actual length (units) */
4460 var2=rhs->lsu; /* -> rhs array */
4461 msu2=var2+var2units-1; /* -> msu of var2 [never changes] */
4462 /* now set up the variables which will be used for estimating the */
4463 /* multiplication factor. If these variables are not exact, add */
4464 /* 1 to make sure that the multiplier is never overestimated. */
4465 msu2plus=*msu2; /* it's value .. */
4466 if (var2units>1) msu2plus++; /* .. +1 if any more */
4467 msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4468 if (var2units>1) { /* .. [else treat 2nd as 0] */
4469 msu2pair+=*(msu2-1); /* .. */
4470 if (var2units>2) msu2pair++; /* .. +1 if any more */
4471 }
4472
4473 /* The calculation is working in units, which may have leading zeros, */
4474 /* but the exponent was calculated on the assumption that they are */
4475 /* both left-aligned. Adjust the exponent to compensate: add the */
4476 /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4477 /* [This is actually done by counting the digits and negating, as */
4478 /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4479 for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4480 for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4481
4482 /* Now, if doing an integer divide or remainder, ensure that */
4483 /* the result will be Unit-aligned. To do this, shift the var1 */
4484 /* accumulator towards least if need be. (It's much easier to */
4485 /* do this now than to reassemble the residue afterwards, if */
4486 /* doing a remainder.) Also ensure the exponent is not negative. */
4487 if (!(op&DIVIDE)) {
4488 Unit *u; /* work */
4489 /* save the initial 'false' padding of var1, in digits */
4490 var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4491 /* Determine the shift to do. */
4492 if (exponent<0) cut=-exponent;
4493 else cut=DECDPUN-exponent%DECDPUN;
4494 decShiftToLeast(var1, var1units, cut);
4495 exponent+=cut; /* maintain numerical value */
4496 var1initpad-=cut; /* .. and reduce padding */
4497 /* clean any most-significant units which were just emptied */
4498 for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4499 } /* align */
4500 else { /* is DIVIDE */
4501 maxexponent=lhs->exponent-rhs->exponent; /* save */
4502 /* optimization: if the first iteration will just produce 0, */
4503 /* preadjust to skip it [valid for DIVIDE only] */
4504 if (*msu1<*msu2) {
4505 var2ulen--; /* shift down */
4506 exponent-=DECDPUN; /* update the exponent */
4507 }
4508 }
4509
4510 /* ---- start the long-division loops ------------------------------ */
4511 accunits=0; /* no units accumulated yet */
4512 accdigits=0; /* .. or digits */
4513 accnext=acc+acclength-1; /* -> msu of acc [NB: allows digits+1] */
4514 for (;;) { /* outer forever loop */
4515 thisunit=0; /* current unit assumed 0 */
4516 /* find the next unit */
4517 for (;;) { /* inner forever loop */
4518 /* strip leading zero units [from either pre-adjust or from */
4519 /* subtract last time around]. Leave at least one unit. */
4520 for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4521
4522 if (var1units<var2ulen) break; /* var1 too low for subtract */
4523 if (var1units==var2ulen) { /* unit-by-unit compare needed */
4524 /* compare the two numbers, from msu */
4525 const Unit *pv1, *pv2;
4526 Unit v2; /* units to compare */
4527 pv2=msu2; /* -> msu */
4528 for (pv1=msu1; ; pv1--, pv2--) {
4529 /* v1=*pv1 -- always OK */
4530 v2=0; /* assume in padding */
4531 if (pv2>=var2) v2=*pv2; /* in range */
4532 if (*pv1!=v2) break; /* no longer the same */
4533 if (pv1==var1) break; /* done; leave pv1 as is */
4534 }
4535 /* here when all inspected or a difference seen */
4536 if (*pv1<v2) break; /* var1 too low to subtract */
4537 if (*pv1==v2) { /* var1 == var2 */
4538 /* reach here if var1 and var2 are identical; subtraction */
4539 /* would increase digit by one, and the residue will be 0 so */
4540 /* the calculation is done; leave the loop with residue=0. */
4541 thisunit++; /* as though subtracted */
4542 *var1=0; /* set var1 to 0 */
4543 var1units=1; /* .. */
4544 break; /* from inner */
4545 } /* var1 == var2 */
4546 /* *pv1>v2. Prepare for real subtraction; the lengths are equal */
4547 /* Estimate the multiplier (there's always a msu1-1)... */
4548 /* Bring in two units of var2 to provide a good estimate. */
4549 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4550 } /* lengths the same */
4551 else { /* var1units > var2ulen, so subtraction is safe */
4552 /* The var2 msu is one unit towards the lsu of the var1 msu, */
4553 /* so only one unit for var2 can be used. */
4554 mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4555 }
4556 if (mult==0) mult=1; /* must always be at least 1 */
4557 /* subtraction needed; var1 is > var2 */
4558 thisunit=(Unit)(thisunit+mult); /* accumulate */
4559 /* subtract var1-var2, into var1; only the overlap needs */
4560 /* processing, as this is an in-place calculation */
4561 shift=var2ulen-var2units;
4562 #if DECTRACE
4563 decDumpAr('1', &var1[shift], var1units-shift);
4564 decDumpAr('2', var2, var2units);
4565 printf("m=%ld\n", -mult);
4566 #endif
4567 decUnitAddSub(&var1[shift], var1units-shift,
4568 var2, var2units, 0,
4569 &var1[shift], -mult);
4570 #if DECTRACE
4571 decDumpAr('#', &var1[shift], var1units-shift);
4572 #endif
4573 /* var1 now probably has leading zeros; these are removed at the */
4574 /* top of the inner loop. */
4575 } /* inner loop */
4576
4577 /* The next unit has been calculated in full; unless it's a */
4578 /* leading zero, add to acc */
4579 if (accunits!=0 || thisunit!=0) { /* is first or non-zero */
4580 *accnext=thisunit; /* store in accumulator */
4581 /* account exactly for the new digits */
4582 if (accunits==0) {
4583 accdigits++; /* at least one */
4584 for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4585 }
4586 else accdigits+=DECDPUN;
4587 accunits++; /* update count */
4588 accnext--; /* ready for next */
4589 if (accdigits>reqdigits) break; /* have enough digits */
4590 }
4591
4592 /* if the residue is zero, the operation is done (unless divide */
4593 /* or divideInteger and still not enough digits yet) */
4594 if (*var1==0 && var1units==1) { /* residue is 0 */
4595 if (op&(REMAINDER|REMNEAR)) break;
4596 if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4597 /* [drop through if divideInteger] */
4598 }
4599 /* also done enough if calculating remainder or integer */
4600 /* divide and just did the last ('units') unit */
4601 if (exponent==0 && !(op&DIVIDE)) break;
4602
4603 /* to get here, var1 is less than var2, so divide var2 by the per- */
4604 /* Unit power of ten and go for the next digit */
4605 var2ulen--; /* shift down */
4606 exponent-=DECDPUN; /* update the exponent */
4607 } /* outer loop */
4608
4609 /* ---- division is complete --------------------------------------- */
4610 /* here: acc has at least reqdigits+1 of good results (or fewer */
4611 /* if early stop), starting at accnext+1 (its lsu) */
4612 /* var1 has any residue at the stopping point */
4613 /* accunits is the number of digits collected in acc */
4614 if (accunits==0) { /* acc is 0 */
4615 accunits=1; /* show have a unit .. */
4616 accdigits=1; /* .. */
4617 *accnext=0; /* .. whose value is 0 */
4618 }
4619 else accnext++; /* back to last placed */
4620 /* accnext now -> lowest unit of result */
4621
4622 residue=0; /* assume no residue */
4623 if (op&DIVIDE) {
4624 /* record the presence of any residue, for rounding */
4625 if (*var1!=0 || var1units>1) residue=1;
4626 else { /* no residue */
4627 /* Had an exact division; clean up spurious trailing 0s. */
4628 /* There will be at most DECDPUN-1, from the final multiply, */
4629 /* and then only if the result is non-0 (and even) and the */
4630 /* exponent is 'loose'. */
4631 #if DECDPUN>1
4632 Unit lsu=*accnext;
4633 if (!(lsu&0x01) && (lsu!=0)) {
4634 /* count the trailing zeros */
4635 Int drop=0;
4636 for (;; drop++) { /* [will terminate because lsu!=0] */
4637 if (exponent>=maxexponent) break; /* don't chop real 0s */
4638 #if DECDPUN<=4
4639 if ((lsu-QUOT10(lsu, drop+1)
4640 *powers[drop+1])!=0) break; /* found non-0 digit */
4641 #else
4642 if (lsu%powers[drop+1]!=0) break; /* found non-0 digit */
4643 #endif
4644 exponent++;
4645 }
4646 if (drop>0) {
4647 accunits=decShiftToLeast(accnext, accunits, drop);
4648 accdigits=decGetDigits(accnext, accunits);
4649 accunits=D2U(accdigits);
4650 /* [exponent was adjusted in the loop] */
4651 }
4652 } /* neither odd nor 0 */
4653 #endif
4654 } /* exact divide */
4655 } /* divide */
4656 else /* op!=DIVIDE */ {
4657 /* check for coefficient overflow */
4658 if (accdigits+exponent>reqdigits) {
4659 *status|=DEC_Division_impossible;
4660 break;
4661 }
4662 if (op & (REMAINDER|REMNEAR)) {
4663 /* [Here, the exponent will be 0, because var1 was adjusted */
4664 /* appropriately.] */
4665 Int postshift; /* work */
4666 Flag wasodd=0; /* integer was odd */
4667 Unit *quotlsu; /* for save */
4668 Int quotdigits; /* .. */
4669
4670 bits=lhs->bits; /* remainder sign is always as lhs */
4671
4672 /* Fastpath when residue is truly 0 is worthwhile [and */
4673 /* simplifies the code below] */
4674 if (*var1==0 && var1units==1) { /* residue is 0 */
4675 Int exp=lhs->exponent; /* save min(exponents) */
4676 if (rhs->exponent<exp) exp=rhs->exponent;
4677 decNumberZero(res); /* 0 coefficient */
4678 #if DECSUBSET
4679 if (set->extended)
4680 #endif
4681 res->exponent=exp; /* .. with proper exponent */
4682 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4683 decFinish(res, set, &residue, status); /* might clamp */
4684 break;
4685 }
4686 /* note if the quotient was odd */
4687 if (*accnext & 0x01) wasodd=1; /* acc is odd */
4688 quotlsu=accnext; /* save in case need to reinspect */
4689 quotdigits=accdigits; /* .. */
4690
4691 /* treat the residue, in var1, as the value to return, via acc */
4692 /* calculate the unused zero digits. This is the smaller of: */
4693 /* var1 initial padding (saved above) */
4694 /* var2 residual padding, which happens to be given by: */
4695 postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4696 /* [the 'exponent' term accounts for the shifts during divide] */
4697 if (var1initpad<postshift) postshift=var1initpad;
4698
4699 /* shift var1 the requested amount, and adjust its digits */
4700 var1units=decShiftToLeast(var1, var1units, postshift);
4701 accnext=var1;
4702 accdigits=decGetDigits(var1, var1units);
4703 accunits=D2U(accdigits);
4704
4705 exponent=lhs->exponent; /* exponent is smaller of lhs & rhs */
4706 if (rhs->exponent<exponent) exponent=rhs->exponent;
4707
4708 /* Now correct the result if doing remainderNear; if it */
4709 /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4710 /* the integer was odd then the result should be rem-rhs. */
4711 if (op&REMNEAR) {
4712 Int compare, tarunits; /* work */
4713 Unit *up; /* .. */
4714 /* calculate remainder*2 into the var1 buffer (which has */
4715 /* 'headroom' of an extra unit and hence enough space) */
4716 /* [a dedicated 'double' loop would be faster, here] */
4717 tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4718 0, accnext, 1);
4719 /* decDumpAr('r', accnext, tarunits); */
4720
4721 /* Here, accnext (var1) holds tarunits Units with twice the */
4722 /* remainder's coefficient, which must now be compared to the */
4723 /* RHS. The remainder's exponent may be smaller than the RHS's. */
4724 compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4725 rhs->exponent-exponent);
4726 if (compare==BADINT) { /* deep trouble */
4727 *status|=DEC_Insufficient_storage;
4728 break;}
4729
4730 /* now restore the remainder by dividing by two; the lsu */
4731 /* is known to be even. */
4732 for (up=accnext; up<accnext+tarunits; up++) {
4733 Int half; /* half to add to lower unit */
4734 half=*up & 0x01;
4735 *up/=2; /* [shift] */
4736 if (!half) continue;
4737 *(up-1)+=(DECDPUNMAX+1)/2;
4738 }
4739 /* [accunits still describes the original remainder length] */
4740
4741 if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4742 Int exp, expunits, exprem; /* work */
4743 /* This is effectively causing round-up of the quotient, */
4744 /* so if it was the rare case where it was full and all */
4745 /* nines, it would overflow and hence division-impossible */
4746 /* should be raised */
4747 Flag allnines=0; /* 1 if quotient all nines */
4748 if (quotdigits==reqdigits) { /* could be borderline */
4749 for (up=quotlsu; ; up++) {
4750 if (quotdigits>DECDPUN) {
4751 if (*up!=DECDPUNMAX) break;/* non-nines */
4752 }
4753 else { /* this is the last Unit */
4754 if (*up==powers[quotdigits]-1) allnines=1;
4755 break;
4756 }
4757 quotdigits-=DECDPUN; /* checked those digits */
4758 } /* up */
4759 } /* borderline check */
4760 if (allnines) {
4761 *status|=DEC_Division_impossible;
4762 break;}
4763
4764 /* rem-rhs is needed; the sign will invert. Again, var1 */
4765 /* can safely be used for the working Units array. */
4766 exp=rhs->exponent-exponent; /* RHS padding needed */
4767 /* Calculate units and remainder from exponent. */
4768 expunits=exp/DECDPUN;
4769 exprem=exp%DECDPUN;
4770 /* subtract [A+B*(-m)]; the result will always be negative */
4771 accunits=-decUnitAddSub(accnext, accunits,
4772 rhs->lsu, D2U(rhs->digits),
4773 expunits, accnext, -(Int)powers[exprem]);
4774 accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4775 accunits=D2U(accdigits); /* and recalculate the units for copy */
4776 /* [exponent is as for original remainder] */
4777 bits^=DECNEG; /* flip the sign */
4778 }
4779 } /* REMNEAR */
4780 } /* REMAINDER or REMNEAR */
4781 } /* not DIVIDE */
4782
4783 /* Set exponent and bits */
4784 res->exponent=exponent;
4785 res->bits=(uByte)(bits&DECNEG); /* [cleaned] */
4786
4787 /* Now the coefficient. */
4788 decSetCoeff(res, set, accnext, accdigits, &residue, status);
4789
4790 decFinish(res, set, &residue, status); /* final cleanup */
4791
4792 #if DECSUBSET
4793 /* If a divide then strip trailing zeros if subset [after round] */
4794 if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, &dropped);
4795 #endif
4796 } while(0); /* end protected */
4797
4798 if (varalloc!=NULL) free(varalloc); /* drop any storage used */
4799 if (allocacc!=NULL) free(allocacc); /* .. */
4800 #if DECSUBSET
4801 if (allocrhs!=NULL) free(allocrhs); /* .. */
4802 if (alloclhs!=NULL) free(alloclhs); /* .. */
4803 #endif
4804 return res;
4805 } /* decDivideOp */
4806
4807/* ------------------------------------------------------------------ */
4808/* decMultiplyOp -- multiplication operation */
4809/* */
4810/* This routine performs the multiplication C=A x B. */
4811/* */
4812/* res is C, the result. C may be A and/or B (e.g., X=X*X) */
4813/* lhs is A */
4814/* rhs is B */
4815/* set is the context */
4816/* status is the usual accumulator */
4817/* */
4818/* C must have space for set->digits digits. */
4819/* */
4820/* ------------------------------------------------------------------ */
4821/* 'Classic' multiplication is used rather than Karatsuba, as the */
4822/* latter would give only a minor improvement for the short numbers */
4823/* expected to be handled most (and uses much more memory). */
4824/* */
4825/* There are two major paths here: the general-purpose ('old code') */
4826/* path which handles all DECDPUN values, and a fastpath version */
4827/* which is used if 64-bit ints are available, DECDPUN<=4, and more */
4828/* than two calls to decUnitAddSub would be made. */
4829/* */
4830/* The fastpath version lumps units together into 8-digit or 9-digit */
4831/* chunks, and also uses a lazy carry strategy to minimise expensive */
4832/* 64-bit divisions. The chunks are then broken apart again into */
4833/* units for continuing processing. Despite this overhead, the */
4834/* fastpath can speed up some 16-digit operations by 10x (and much */
4835/* more for higher-precision calculations). */
4836/* */
4837/* A buffer always has to be used for the accumulator; in the */
4838/* fastpath, buffers are also always needed for the chunked copies of */
4839/* of the operand coefficients. */
4840/* Static buffers are larger than needed just for multiply, to allow */
4841/* for calls from other operations (notably exp). */
4842/* ------------------------------------------------------------------ */
4843#define FASTMUL (DECUSE64 && DECDPUN<5)
4844static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4845 const decNumber *rhs, decContext *set,
4846 uInt *status) {
4847 Int accunits; /* Units of accumulator in use */
4848 Int exponent; /* work */
4849 Int residue=0; /* rounding residue */
4850 uByte bits; /* result sign */
4851 Unit *acc; /* -> accumulator Unit array */
4852 Int needbytes; /* size calculator */
4853 void *allocacc=NULL; /* -> allocated accumulator, iff allocated */
4854 Unit accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4855 /* *4 for calls from other operations) */
4856 const Unit *mer, *mermsup; /* work */
4857 Int madlength; /* Units in multiplicand */
4858 Int shift; /* Units to shift multiplicand by */
4859
4860 #if FASTMUL
4861 /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4862 /* (DECDPUN is 2 or 4) then work in base 10**8 */
4863 #if DECDPUN & 1 /* odd */
4864 #define FASTBASE 1000000000 /* base */
4865 #define FASTDIGS 9 /* digits in base */
4866 #define FASTLAZY 18 /* carry resolution point [1->18] */
4867 #else
4868 #define FASTBASE 100000000
4869 #define FASTDIGS 8
4870 #define FASTLAZY 1844 /* carry resolution point [1->1844] */
4871 #endif
4872 /* three buffers are used, two for chunked copies of the operands */
4873 /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4874 /* lazy carry evaluation */
4875 uInt zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4876 uInt *zlhi=zlhibuff; /* -> lhs array */
4877 uInt *alloclhi=NULL; /* -> allocated buffer, iff allocated */
4878 uInt zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4879 uInt *zrhi=zrhibuff; /* -> rhs array */
4880 uInt *allocrhi=NULL; /* -> allocated buffer, iff allocated */
4881 uLong zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4882 /* [allocacc is shared for both paths, as only one will run] */
4883 uLong *zacc=zaccbuff; /* -> accumulator array for exact result */
4884 #if DECDPUN==1
4885 Int zoff; /* accumulator offset */
4886 #endif
4887 uInt *lip, *rip; /* item pointers */
4888 uInt *lmsi, *rmsi; /* most significant items */
4889 Int ilhs, irhs, iacc; /* item counts in the arrays */
4890 Int lazy; /* lazy carry counter */
4891 uLong lcarry; /* uLong carry */
4892 uInt carry; /* carry (NB not uLong) */
4893 Int count; /* work */
4894 const Unit *cup; /* .. */
4895 Unit *up; /* .. */
4896 uLong *lp; /* .. */
4897 Int p; /* .. */
4898 #endif
4899
4900 #if DECSUBSET
4901 decNumber *alloclhs=NULL; /* -> allocated buffer, iff allocated */
4902 decNumber *allocrhs=NULL; /* -> allocated buffer, iff allocated */
4903 #endif
4904
4905 #if DECCHECK
4906 if (decCheckOperands(res, lhs, rhs, set)) return res;
4907 #endif
4908
4909 /* precalculate result sign */
4910 bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4911
4912 /* handle infinities and NaNs */
4913 if (SPECIALARGS) { /* a special bit set */
4914 if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4915 decNaNs(res, lhs, rhs, set, status);
4916 return res;}
4917 /* one or two infinities; Infinity * 0 is invalid */
4918 if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4919 ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4920 *status|=DEC_Invalid_operation;
4921 return res;}
4922 decNumberZero(res);
4923 res->bits=bits|DECINF; /* infinity */
4924 return res;}
4925
4926 /* For best speed, as in DMSRCN [the original Rexx numerics */
4927 /* module], use the shorter number as the multiplier (rhs) and */
4928 /* the longer as the multiplicand (lhs) to minimise the number of */
4929 /* adds (partial products) */
4930 if (lhs->digits<rhs->digits) { /* swap... */
4931 const decNumber *hold=lhs;
4932 lhs=rhs;
4933 rhs=hold;
4934 }
4935
4936 do { /* protect allocated storage */
4937 #if DECSUBSET
4938 if (!set->extended) {
4939 /* reduce operands and set lostDigits status, as needed */
4940 if (lhs->digits>set->digits) {
4941 alloclhs=decRoundOperand(lhs, set, status);
4942 if (alloclhs==NULL) break;
4943 lhs=alloclhs;
4944 }
4945 if (rhs->digits>set->digits) {
4946 allocrhs=decRoundOperand(rhs, set, status);
4947 if (allocrhs==NULL) break;
4948 rhs=allocrhs;
4949 }
4950 }
4951 #endif
4952 /* [following code does not require input rounding] */
4953
4954 #if FASTMUL /* fastpath can be used */
4955 /* use the fast path if there are enough digits in the shorter */
4956 /* operand to make the setup and takedown worthwhile */
4957 #define NEEDTWO (DECDPUN*2) /* within two decUnitAddSub calls */
4958 if (rhs->digits>NEEDTWO) { /* use fastpath... */
4959 /* calculate the number of elements in each array */
4960 ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4961 irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4962 iacc=ilhs+irhs;
4963
4964 /* allocate buffers if required, as usual */
4965 needbytes=ilhs*sizeof(uInt);
4966 if (needbytes>(Int)sizeof(zlhibuff)) {
4967 alloclhi=(uInt *)malloc(needbytes);
4968 zlhi=alloclhi;}
4969 needbytes=irhs*sizeof(uInt);
4970 if (needbytes>(Int)sizeof(zrhibuff)) {
4971 allocrhi=(uInt *)malloc(needbytes);
4972 zrhi=allocrhi;}
4973
4974 /* Allocating the accumulator space needs a special case when */
4975 /* DECDPUN=1 because when converting the accumulator to Units */
4976 /* after the multiplication each 8-byte item becomes 9 1-byte */
4977 /* units. Therefore iacc extra bytes are needed at the front */
4978 /* (rounded up to a multiple of 8 bytes), and the uLong */
4979 /* accumulator starts offset the appropriate number of units */
4980 /* to the right to avoid overwrite during the unchunking. */
4981 needbytes=iacc*sizeof(uLong);
4982 #if DECDPUN==1
4983 zoff=(iacc+7)/8; /* items to offset by */
4984 needbytes+=zoff*8;
4985 #endif
4986 if (needbytes>(Int)sizeof(zaccbuff)) {
4987 allocacc=(uLong *)malloc(needbytes);
4988 zacc=(uLong *)allocacc;}
4989 if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4990 *status|=DEC_Insufficient_storage;
4991 break;}
4992
4993 acc=(Unit *)zacc; /* -> target Unit array */
4994 #if DECDPUN==1
4995 zacc+=zoff; /* start uLong accumulator to right */
4996 #endif
4997
4998 /* assemble the chunked copies of the left and right sides */
4999 for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5000 for (p=0, *lip=0; p<FASTDIGS && count>0;
5001 p+=DECDPUN, cup++, count-=DECDPUN)
5002 *lip+=*cup*powers[p];
5003 lmsi=lip-1; /* save -> msi */
5004 for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5005 for (p=0, *rip=0; p<FASTDIGS && count>0;
5006 p+=DECDPUN, cup++, count-=DECDPUN)
5007 *rip+=*cup*powers[p];
5008 rmsi=rip-1; /* save -> msi */
5009
5010 /* zero the accumulator */
5011 for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5012
5013 /* Start the multiplication */
5014 /* Resolving carries can dominate the cost of accumulating the */
5015 /* partial products, so this is only done when necessary. */
5016 /* Each uLong item in the accumulator can hold values up to */
5017 /* 2**64-1, and each partial product can be as large as */
5018 /* (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to */
5019 /* itself 18.4 times in a uLong without overflowing, so during */
5020 /* the main calculation resolution is carried out every 18th */
5021 /* add -- every 162 digits. Similarly, when FASTDIGS=8, the */
5022 /* partial products can be added to themselves 1844.6 times in */
5023 /* a uLong without overflowing, so intermediate carry */
5024 /* resolution occurs only every 14752 digits. Hence for common */
5025 /* short numbers usually only the one final carry resolution */
5026 /* occurs. */
5027 /* (The count is set via FASTLAZY to simplify experiments to */
5028 /* measure the value of this approach: a 35% improvement on a */
5029 /* [34x34] multiply.) */
5030 lazy=FASTLAZY; /* carry delay count */
5031 for (rip=zrhi; rip<=rmsi; rip++) { /* over each item in rhs */
5032 lp=zacc+(rip-zrhi); /* where to add the lhs */
5033 for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5034 *lp+=(uLong)(*lip)*(*rip); /* [this should in-line] */
5035 } /* lip loop */
5036 lazy--;
5037 if (lazy>0 && rip!=rmsi) continue;
5038 lazy=FASTLAZY; /* reset delay count */
5039 /* spin up the accumulator resolving overflows */
5040 for (lp=zacc; lp<zacc+iacc; lp++) {
5041 if (*lp<FASTBASE) continue; /* it fits */
5042 lcarry=*lp/FASTBASE; /* top part [slow divide] */
5043 /* lcarry can exceed 2**32-1, so check again; this check */
5044 /* and occasional extra divide (slow) is well worth it, as */
5045 /* it allows FASTLAZY to be increased to 18 rather than 4 */
5046 /* in the FASTDIGS=9 case */
5047 if (lcarry<FASTBASE) carry=(uInt)lcarry; /* [usual] */
5048 else { /* two-place carry [fairly rare] */
5049 uInt carry2=(uInt)(lcarry/FASTBASE); /* top top part */
5050 *(lp+2)+=carry2; /* add to item+2 */
5051 *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5052 carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5053 }
5054 *(lp+1)+=carry; /* add to item above [inline] */
5055 *lp-=((uLong)FASTBASE*carry); /* [inline] */
5056 } /* carry resolution */
5057 } /* rip loop */
5058
5059 /* The multiplication is complete; time to convert back into */
5060 /* units. This can be done in-place in the accumulator and in */
5061 /* 32-bit operations, because carries were resolved after the */
5062 /* final add. This needs N-1 divides and multiplies for */
5063 /* each item in the accumulator (which will become up to N */
5064 /* units, where 2<=N<=9). */
5065 for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5066 uInt item=(uInt)*lp; /* decapitate to uInt */
5067 for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5068 uInt part=item/(DECDPUNMAX+1);
5069 *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5070 item=part;
5071 } /* p */
5072 *up=(Unit)item; up++; /* [final needs no division] */
5073 } /* lp */
5074 accunits=up-acc; /* count of units */
5075 }
5076 else { /* here to use units directly, without chunking ['old code'] */
5077 #endif
5078
5079 /* if accumulator will be too long for local storage, then allocate */
5080 acc=accbuff; /* -> assume buffer for accumulator */
5081 needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5082 if (needbytes>(Int)sizeof(accbuff)) {
5083 allocacc=(Unit *)malloc(needbytes);
5084 if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5085 acc=(Unit *)allocacc; /* use the allocated space */
5086 }
5087
5088 /* Now the main long multiplication loop */
5089 /* Unlike the equivalent in the IBM Java implementation, there */
5090 /* is no advantage in calculating from msu to lsu. So, do it */
5091 /* by the book, as it were. */
5092 /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5093 accunits=1; /* accumulator starts at '0' */
5094 *acc=0; /* .. (lsu=0) */
5095 shift=0; /* no multiplicand shift at first */
5096 madlength=D2U(lhs->digits); /* this won't change */
5097 mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5098
5099 for (mer=rhs->lsu; mer<mermsup; mer++) {
5100 /* Here, *mer is the next Unit in the multiplier to use */
5101 /* If non-zero [optimization] add it... */
5102 if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5103 lhs->lsu, madlength, 0,
5104 &acc[shift], *mer)
5105 + shift;
5106 else { /* extend acc with a 0; it will be used shortly */
5107 *(acc+accunits)=0; /* [this avoids length of <=0 later] */
5108 accunits++;
5109 }
5110 /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5111 shift++; /* add this for 'logical length' */
5112 } /* n */
5113 #if FASTMUL
5114 } /* unchunked units */
5115 #endif
5116 /* common end-path */
5117 #if DECTRACE
5118 decDumpAr('*', acc, accunits); /* Show exact result */
5119 #endif
5120
5121 /* acc now contains the exact result of the multiplication, */
5122 /* possibly with a leading zero unit; build the decNumber from */
5123 /* it, noting if any residue */
5124 res->bits=bits; /* set sign */
5125 res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5126
5127 /* There can be a 31-bit wrap in calculating the exponent. */
5128 /* This can only happen if both input exponents are negative and */
5129 /* both their magnitudes are large. If there was a wrap, set a */
5130 /* safe very negative exponent, from which decFinalize() will */
5131 /* raise a hard underflow shortly. */
5132 exponent=lhs->exponent+rhs->exponent; /* calculate exponent */
5133 if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5134 exponent=-2*DECNUMMAXE; /* force underflow */
5135 res->exponent=exponent; /* OK to overwrite now */
5136
5137
5138 /* Set the coefficient. If any rounding, residue records */
5139 decSetCoeff(res, set, acc, res->digits, &residue, status);
5140 decFinish(res, set, &residue, status); /* final cleanup */
5141 } while(0); /* end protected */
5142
5143 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
5144 #if DECSUBSET
5145 if (allocrhs!=NULL) free(allocrhs); /* .. */
5146 if (alloclhs!=NULL) free(alloclhs); /* .. */
5147 #endif
5148 #if FASTMUL
5149 if (allocrhi!=NULL) free(allocrhi); /* .. */
5150 if (alloclhi!=NULL) free(alloclhi); /* .. */
5151 #endif
5152 return res;
5153 } /* decMultiplyOp */
5154
5155/* ------------------------------------------------------------------ */
5156/* decExpOp -- effect exponentiation */
5157/* */
5158/* This computes C = exp(A) */
5159/* */
5160/* res is C, the result. C may be A */
5161/* rhs is A */
5162/* set is the context; note that rounding mode has no effect */
5163/* */
5164/* C must have space for set->digits digits. status is updated but */
5165/* not set. */
5166/* */
5167/* Restrictions: */
5168/* */
5169/* digits, emax, and -emin in the context must be less than */
5170/* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */
5171/* bounds or a zero. This is an internal routine, so these */
5172/* restrictions are contractual and not enforced. */
5173/* */
5174/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5175/* almost always be correctly rounded, but may be up to 1 ulp in */
5176/* error in rare cases. */
5177/* */
5178/* Finite results will always be full precision and Inexact, except */
5179/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
5180/* ------------------------------------------------------------------ */
5181/* This approach used here is similar to the algorithm described in */
5182/* */
5183/* Variable Precision Exponential Function, T. E. Hull and */
5184/* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5185/* pp79-91, ACM, June 1986. */
5186/* */
5187/* with the main difference being that the iterations in the series */
5188/* evaluation are terminated dynamically (which does not require the */
5189/* extra variable-precision variables which are expensive in this */
5190/* context). */
5191/* */
5192/* The error analysis in Hull & Abrham's paper applies except for the */
5193/* round-off error accumulation during the series evaluation. This */
5194/* code does not precalculate the number of iterations and so cannot */
5195/* use Horner's scheme. Instead, the accumulation is done at double- */
5196/* precision, which ensures that the additions of the terms are exact */
5197/* and do not accumulate round-off (and any round-off errors in the */
5198/* terms themselves move 'to the right' faster than they can */
5199/* accumulate). This code also extends the calculation by allowing, */
5200/* in the spirit of other decNumber operators, the input to be more */
5201/* precise than the result (the precision used is based on the more */
5202/* precise of the input or requested result). */
5203/* */
5204/* Implementation notes: */
5205/* */
5206/* 1. This is separated out as decExpOp so it can be called from */
5207/* other Mathematical functions (notably Ln) with a wider range */
5208/* than normal. In particular, it can handle the slightly wider */
5209/* (double) range needed by Ln (which has to be able to calculate */
5210/* exp(-x) where x can be the tiniest number (Ntiny). */
5211/* */
5212/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */
5213/* iterations by appoximately a third with additional (although */
5214/* diminishing) returns as the range is reduced to even smaller */
5215/* fractions. However, h (the power of 10 used to correct the */
5216/* result at the end, see below) must be kept <=8 as otherwise */
5217/* the final result cannot be computed. Hence the leverage is a */
5218/* sliding value (8-h), where potentially the range is reduced */
5219/* more for smaller values. */
5220/* */
5221/* The leverage that can be applied in this way is severely */
5222/* limited by the cost of the raise-to-the power at the end, */
5223/* which dominates when the number of iterations is small (less */
5224/* than ten) or when rhs is short. As an example, the adjustment */
5225/* x**10,000,000 needs 31 multiplications, all but one full-width. */
5226/* */
5227/* 3. The restrictions (especially precision) could be raised with */
5228/* care, but the full decNumber range seems very hard within the */
5229/* 32-bit limits. */
5230/* */
5231/* 4. The working precisions for the static buffers are twice the */
5232/* obvious size to allow for calls from decNumberPower. */
5233/* ------------------------------------------------------------------ */
5234decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5235 decContext *set, uInt *status) {
5236 uInt ignore=0; /* working status */
5237 Int h; /* adjusted exponent for 0.xxxx */
5238 Int p; /* working precision */
5239 Int residue; /* rounding residue */
5240 uInt needbytes; /* for space calculations */
5241 const decNumber *x=rhs; /* (may point to safe copy later) */
5242 decContext aset, tset, dset; /* working contexts */
5243 Int comp; /* work */
5244
5245 /* the argument is often copied to normalize it, so (unusually) it */
5246 /* is treated like other buffers, using DECBUFFER, +1 in case */
5247 /* DECBUFFER is 0 */
5248 decNumber bufr[D2N(DECBUFFER*2+1)];
5249 decNumber *allocrhs=NULL; /* non-NULL if rhs buffer allocated */
5250
5251 /* the working precision will be no more than set->digits+8+1 */
5252 /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5253 /* is 0 (and twice that for the accumulator) */
5254
5255 /* buffer for t, term (working precision plus) */
5256 decNumber buft[D2N(DECBUFFER*2+9+1)];
5257 decNumber *allocbuft=NULL; /* -> allocated buft, iff allocated */
5258 decNumber *t=buft; /* term */
5259 /* buffer for a, accumulator (working precision * 2), at least 9 */
5260 decNumber bufa[D2N(DECBUFFER*4+18+1)];
5261 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5262 decNumber *a=bufa; /* accumulator */
5263 /* decNumber for the divisor term; this needs at most 9 digits */
5264 /* and so can be fixed size [16 so can use standard context] */
5265 decNumber bufd[D2N(16)];
5266 decNumber *d=bufd; /* divisor */
5267 decNumber numone; /* constant 1 */
5268
5269 #if DECCHECK
5270 Int iterations=0; /* for later sanity check */
5271 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5272 #endif
5273
5274 do { /* protect allocated storage */
5275 if (SPECIALARG) { /* handle infinities and NaNs */
5276 if (decNumberIsInfinite(rhs)) { /* an infinity */
5277 if (decNumberIsNegative(rhs)) /* -Infinity -> +0 */
5278 decNumberZero(res);
5279 else decNumberCopy(res, rhs); /* +Infinity -> self */
5280 }
5281 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5282 break;}
5283
5284 if (ISZERO(rhs)) { /* zeros -> exact 1 */
5285 decNumberZero(res); /* make clean 1 */
5286 *res->lsu=1; /* .. */
5287 break;} /* [no status to set] */
5288
5289 /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5290 /* positive and negative tiny cases which will result in inexact */
5291 /* 1. This also allows the later add-accumulate to always be */
5292 /* exact (because its length will never be more than twice the */
5293 /* working precision). */
5294 /* The comparator (tiny) needs just one digit, so use the */
5295 /* decNumber d for it (reused as the divisor, etc., below); its */
5296 /* exponent is such that if x is positive it will have */
5297 /* set->digits-1 zeros between the decimal point and the digit, */
5298 /* which is 4, and if x is negative one more zero there as the */
5299 /* more precise result will be of the form 0.9999999 rather than */
5300 /* 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>0 */
5301 /* or 0.00000004 if digits=7 and x<0. If RHS not larger than */
5302 /* this then the result will be 1.000000 */
5303 decNumberZero(d); /* clean */
5304 *d->lsu=4; /* set 4 .. */
5305 d->exponent=-set->digits; /* * 10**(-d) */
5306 if (decNumberIsNegative(rhs)) d->exponent--; /* negative case */
5307 comp=decCompare(d, rhs, 1); /* signless compare */
5308 if (comp==BADINT) {
5309 *status|=DEC_Insufficient_storage;
5310 break;}
5311 if (comp>=0) { /* rhs < d */
5312 Int shift=set->digits-1;
5313 decNumberZero(res); /* set 1 */
5314 *res->lsu=1; /* .. */
5315 res->digits=decShiftToMost(res->lsu, 1, shift);
5316 res->exponent=-shift; /* make 1.0000... */
5317 *status|=DEC_Inexact | DEC_Rounded; /* .. inexactly */
5318 break;} /* tiny */
5319
5320 /* set up the context to be used for calculating a, as this is */
5321 /* used on both paths below */
5322 decContextDefault(&aset, DEC_INIT_DECIMAL64);
5323 /* accumulator bounds are as requested (could underflow) */
5324 aset.emax=set->emax; /* usual bounds */
5325 aset.emin=set->emin; /* .. */
5326 aset.clamp=0; /* and no concrete format */
5327
5328 /* calculate the adjusted (Hull & Abrham) exponent (where the */
5329 /* decimal point is just to the left of the coefficient msd) */
5330 h=rhs->exponent+rhs->digits;
5331 /* if h>8 then 10**h cannot be calculated safely; however, when */
5332 /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5333 /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5334 /* overflow (or underflow to 0) is guaranteed -- so this case can */
5335 /* be handled by simply forcing the appropriate excess */
5336 if (h>8) { /* overflow/underflow */
5337 /* set up here so Power call below will over or underflow to */
5338 /* zero; set accumulator to either 2 or 0.02 */
5339 /* [stack buffer for a is always big enough for this] */
5340 decNumberZero(a);
5341 *a->lsu=2; /* not 1 but < exp(1) */
5342 if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5343 h=8; /* clamp so 10**h computable */
5344 p=9; /* set a working precision */
5345 }
5346 else { /* h<=8 */
5347 Int maxlever=(rhs->digits>8?1:0);
5348 /* [could/should increase this for precisions >40 or so, too] */
5349
5350 /* if h is 8, cannot normalize to a lower upper limit because */
5351 /* the final result will not be computable (see notes above), */
5352 /* but leverage can be applied whenever h is less than 8. */
5353 /* Apply as much as possible, up to a MAXLEVER digits, which */
5354 /* sets the tradeoff against the cost of the later a**(10**h). */
5355 /* As h is increased, the working precision below also */
5356 /* increases to compensate for the "constant digits at the */
5357 /* front" effect. */
5358 Int lever=MINI(8-h, maxlever); /* leverage attainable */
5359 Int use=-rhs->digits-lever; /* exponent to use for RHS */
5360 h+=lever; /* apply leverage selected */
5361 if (h<0) { /* clamp */
5362 use+=h; /* [may end up subnormal] */
5363 h=0;
5364 }
5365 /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5366 if (rhs->exponent!=use) {
5367 decNumber *newrhs=bufr; /* assume will fit on stack */
5368 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5369 if (needbytes>sizeof(bufr)) { /* need malloc space */
5370 allocrhs=(decNumber *)malloc(needbytes);
5371 if (allocrhs==NULL) { /* hopeless -- abandon */
5372 *status|=DEC_Insufficient_storage;
5373 break;}
5374 newrhs=allocrhs; /* use the allocated space */
5375 }
5376 decNumberCopy(newrhs, rhs); /* copy to safe space */
5377 newrhs->exponent=use; /* normalize; now <1 */
5378 x=newrhs; /* ready for use */
5379 /* decNumberShow(x); */
5380 }
5381
5382 /* Now use the usual power series to evaluate exp(x). The */
5383 /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5384 /* third term by setting the term variable t=x, the accumulator */
5385 /* a=1, and the divisor d=2. */
5386
5387 /* First determine the working precision. From Hull & Abrham */
5388 /* this is set->digits+h+2. However, if x is 'over-precise' we */
5389 /* need to allow for all its digits to potentially participate */
5390 /* (consider an x where all the excess digits are 9s) so in */
5391 /* this case use x->digits+h+2 */
5392 p=MAXI(x->digits, set->digits)+h+2; /* [h<=8] */
5393
5394 /* a and t are variable precision, and depend on p, so space */
5395 /* must be allocated for them if necessary */
5396
5397 /* the accumulator needs to be able to hold 2p digits so that */
5398 /* the additions on the second and subsequent iterations are */
5399 /* sufficiently exact. */
5400 needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5401 if (needbytes>sizeof(bufa)) { /* need malloc space */
5402 allocbufa=(decNumber *)malloc(needbytes);
5403 if (allocbufa==NULL) { /* hopeless -- abandon */
5404 *status|=DEC_Insufficient_storage;
5405 break;}
5406 a=allocbufa; /* use the allocated space */
5407 }
5408 /* the term needs to be able to hold p digits (which is */
5409 /* guaranteed to be larger than x->digits, so the initial copy */
5410 /* is safe); it may also be used for the raise-to-power */
5411 /* calculation below, which needs an extra two digits */
5412 needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5413 if (needbytes>sizeof(buft)) { /* need malloc space */
5414 allocbuft=(decNumber *)malloc(needbytes);
5415 if (allocbuft==NULL) { /* hopeless -- abandon */
5416 *status|=DEC_Insufficient_storage;
5417 break;}
5418 t=allocbuft; /* use the allocated space */
5419 }
5420
5421 decNumberCopy(t, x); /* term=x */
5422 decNumberZero(a); *a->lsu=1; /* accumulator=1 */
5423 decNumberZero(d); *d->lsu=2; /* divisor=2 */
5424 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5425
5426 /* set up the contexts for calculating a, t, and d */
5427 decContextDefault(&tset, DEC_INIT_DECIMAL64);
5428 dset=tset;
5429 /* accumulator bounds are set above, set precision now */
5430 aset.digits=p*2; /* double */
5431 /* term bounds avoid any underflow or overflow */
5432 tset.digits=p;
5433 tset.emin=DEC_MIN_EMIN; /* [emax is plenty] */
5434 /* [dset.digits=16, etc., are sufficient] */
5435
5436 /* finally ready to roll */
5437 for (;;) {
5438 #if DECCHECK
5439 iterations++;
5440 #endif
5441 /* only the status from the accumulation is interesting */
5442 /* [but it should remain unchanged after first add] */
5443 decAddOp(a, a, t, &aset, 0, status); /* a=a+t */
5444 decMultiplyOp(t, t, x, &tset, &ignore); /* t=t*x */
5445 decDivideOp(t, t, d, &tset, DIVIDE, &ignore); /* t=t/d */
5446 /* the iteration ends when the term cannot affect the result, */
5447 /* if rounded to p digits, which is when its value is smaller */
5448 /* than the accumulator by p+1 digits. There must also be */
5449 /* full precision in a. */
5450 if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5451 && (a->digits>=p)) break;
5452 decAddOp(d, d, &numone, &dset, 0, &ignore); /* d=d+1 */
5453 } /* iterate */
5454
5455 #if DECCHECK
5456 /* just a sanity check; comment out test to show always */
5457 if (iterations>p+3)
5458 printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5459 iterations, *status, p, x->digits);
5460 #endif
5461 } /* h<=8 */
5462
5463 /* apply postconditioning: a=a**(10**h) -- this is calculated */
5464 /* at a slightly higher precision than Hull & Abrham suggest */
5465 if (h>0) {
5466 Int seenbit=0; /* set once a 1-bit is seen */
5467 Int i; /* counter */
5468 Int n=powers[h]; /* always positive */
5469 aset.digits=p+2; /* sufficient precision */
5470 /* avoid the overhead and many extra digits of decNumberPower */
5471 /* as all that is needed is the short 'multipliers' loop; here */
5472 /* accumulate the answer into t */
5473 decNumberZero(t); *t->lsu=1; /* acc=1 */
5474 for (i=1;;i++){ /* for each bit [top bit ignored] */
5475 /* abandon if have had overflow or terminal underflow */
5476 if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5477 if (*status&DEC_Overflow || ISZERO(t)) break;}
5478 n=n<<1; /* move next bit to testable position */
5479 if (n<0) { /* top bit is set */
5480 seenbit=1; /* OK, have a significant bit */
5481 decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5482 }
5483 if (i==31) break; /* that was the last bit */
5484 if (!seenbit) continue; /* no need to square 1 */
5485 decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5486 } /*i*/ /* 32 bits */
5487 /* decNumberShow(t); */
5488 a=t; /* and carry on using t instead of a */
5489 }
5490
5491 /* Copy and round the result to res */
5492 residue=1; /* indicate dirt to right .. */
5493 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5494 aset.digits=set->digits; /* [use default rounding] */
5495 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5496 decFinish(res, set, &residue, status); /* cleanup/set flags */
5497 } while(0); /* end protected */
5498
5499 if (allocrhs !=NULL) free(allocrhs); /* drop any storage used */
5500 if (allocbufa!=NULL) free(allocbufa); /* .. */
5501 if (allocbuft!=NULL) free(allocbuft); /* .. */
5502 /* [status is handled by caller] */
5503 return res;
5504 } /* decExpOp */
5505
5506/* ------------------------------------------------------------------ */
5507/* Initial-estimate natural logarithm table */
5508/* */
5509/* LNnn -- 90-entry 16-bit table for values from .10 through .99. */
5510/* The result is a 4-digit encode of the coefficient (c=the */
5511/* top 14 bits encoding 0-9999) and a 2-digit encode of the */
5512/* exponent (e=the bottom 2 bits encoding 0-3) */
5513/* */
5514/* The resulting value is given by: */
5515/* */
5516/* v = -c * 10**(-e-3) */
5517/* */
5518/* where e and c are extracted from entry k = LNnn[x-10] */
5519/* where x is truncated (NB) into the range 10 through 99, */
5520/* and then c = k>>2 and e = k&3. */
5521/* ------------------------------------------------------------------ */
5522const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,
5523 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,
5524 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,
5525 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5526 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5527 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5528 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5529 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,
5530 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5531 10130, 6046, 20055};
5532
5533/* ------------------------------------------------------------------ */
5534/* decLnOp -- effect natural logarithm */
5535/* */
5536/* This computes C = ln(A) */
5537/* */
5538/* res is C, the result. C may be A */
5539/* rhs is A */
5540/* set is the context; note that rounding mode has no effect */
5541/* */
5542/* C must have space for set->digits digits. */
5543/* */
5544/* Notable cases: */
5545/* A<0 -> Invalid */
5546/* A=0 -> -Infinity (Exact) */
5547/* A=+Infinity -> +Infinity (Exact) */
5548/* A=1 exactly -> 0 (Exact) */
5549/* */
5550/* Restrictions (as for Exp): */
5551/* */
5552/* digits, emax, and -emin in the context must be less than */
5553/* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */
5554/* bounds or a zero. This is an internal routine, so these */
5555/* restrictions are contractual and not enforced. */
5556/* */
5557/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */
5558/* almost always be correctly rounded, but may be up to 1 ulp in */
5559/* error in rare cases. */
5560/* ------------------------------------------------------------------ */
5561/* The result is calculated using Newton's method, with each */
5562/* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */
5563/* Epperson 1989. */
5564/* */
5565/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5566/* This has to be calculated at the sum of the precision of x and the */
5567/* working precision. */
5568/* */
5569/* Implementation notes: */
5570/* */
5571/* 1. This is separated out as decLnOp so it can be called from */
5572/* other Mathematical functions (e.g., Log 10) with a wider range */
5573/* than normal. In particular, it can handle the slightly wider */
5574/* (+9+2) range needed by a power function. */
5575/* */
5576/* 2. The speed of this function is about 10x slower than exp, as */
5577/* it typically needs 4-6 iterations for short numbers, and the */
5578/* extra precision needed adds a squaring effect, twice. */
5579/* */
5580/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */
5581/* as these are common requests. ln(10) is used by log10(x). */
5582/* */
5583/* 4. An iteration might be saved by widening the LNnn table, and */
5584/* would certainly save at least one if it were made ten times */
5585/* bigger, too (for truncated fractions 0.100 through 0.999). */
5586/* However, for most practical evaluations, at least four or five */
5587/* iterations will be neede -- so this would only speed up by */
5588/* 20-25% and that probably does not justify increasing the table */
5589/* size. */
5590/* */
5591/* 5. The static buffers are larger than might be expected to allow */
5592/* for calls from decNumberPower. */
5593/* ------------------------------------------------------------------ */
5594decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5595 decContext *set, uInt *status) {
5596 uInt ignore=0; /* working status accumulator */
5597 uInt needbytes; /* for space calculations */
5598 Int residue; /* rounding residue */
5599 Int r; /* rhs=f*10**r [see below] */
5600 Int p; /* working precision */
5601 Int pp; /* precision for iteration */
5602 Int t; /* work */
5603
5604 /* buffers for a (accumulator, typically precision+2) and b */
5605 /* (adjustment calculator, same size) */
5606 decNumber bufa[D2N(DECBUFFER+12)];
5607 decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
5608 decNumber *a=bufa; /* accumulator/work */
5609 decNumber bufb[D2N(DECBUFFER*2+2)];
5610 decNumber *allocbufb=NULL; /* -> allocated bufa, iff allocated */
5611 decNumber *b=bufb; /* adjustment/work */
5612
5613 decNumber numone; /* constant 1 */
5614 decNumber cmp; /* work */
5615 decContext aset, bset; /* working contexts */
5616
5617 #if DECCHECK
5618 Int iterations=0; /* for later sanity check */
5619 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5620 #endif
5621
5622 do { /* protect allocated storage */
5623 if (SPECIALARG) { /* handle infinities and NaNs */
5624 if (decNumberIsInfinite(rhs)) { /* an infinity */
5625 if (decNumberIsNegative(rhs)) /* -Infinity -> error */
5626 *status|=DEC_Invalid_operation;
5627 else decNumberCopy(res, rhs); /* +Infinity -> self */
5628 }
5629 else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5630 break;}
5631
5632 if (ISZERO(rhs)) { /* +/- zeros -> -Infinity */
5633 decNumberZero(res); /* make clean */
5634 res->bits=DECINF|DECNEG; /* set - infinity */
5635 break;} /* [no status to set] */
5636
5637 /* Non-zero negatives are bad... */
5638 if (decNumberIsNegative(rhs)) { /* -x -> error */
5639 *status|=DEC_Invalid_operation;
5640 break;}
5641
5642 /* Here, rhs is positive, finite, and in range */
5643
5644 /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5645 if (rhs->exponent==0 && set->digits<=40) {
5646 #if DECDPUN==1
5647 if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5648 #else
5649 if (rhs->lsu[0]==10 && rhs->digits==2) { /* ln(10) */
5650 #endif
5651 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5652 #define LN10 "2.302585092994045684017991454684364207601"
5653 decNumberFromString(res, LN10, &aset);
5654 *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5655 break;}
5656 if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5657 aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5658 #define LN2 "0.6931471805599453094172321214581765680755"
5659 decNumberFromString(res, LN2, &aset);
5660 *status|=(DEC_Inexact | DEC_Rounded);
5661 break;}
5662 } /* integer and short */
5663
5664 /* Determine the working precision. This is normally the */
5665 /* requested precision + 2, with a minimum of 9. However, if */
5666 /* the rhs is 'over-precise' then allow for all its digits to */
5667 /* potentially participate (consider an rhs where all the excess */
5668 /* digits are 9s) so in this case use rhs->digits+2. */
5669 p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5670
5671 /* Allocate space for the accumulator and the high-precision */
5672 /* adjustment calculator, if necessary. The accumulator must */
5673 /* be able to hold p digits, and the adjustment up to */
5674 /* rhs->digits+p digits. They are also made big enough for 16 */
5675 /* digits so that they can be used for calculating the initial */
5676 /* estimate. */
5677 needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5678 if (needbytes>sizeof(bufa)) { /* need malloc space */
5679 allocbufa=(decNumber *)malloc(needbytes);
5680 if (allocbufa==NULL) { /* hopeless -- abandon */
5681 *status|=DEC_Insufficient_storage;
5682 break;}
5683 a=allocbufa; /* use the allocated space */
5684 }
5685 pp=p+rhs->digits;
5686 needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5687 if (needbytes>sizeof(bufb)) { /* need malloc space */
5688 allocbufb=(decNumber *)malloc(needbytes);
5689 if (allocbufb==NULL) { /* hopeless -- abandon */
5690 *status|=DEC_Insufficient_storage;
5691 break;}
5692 b=allocbufb; /* use the allocated space */
5693 }
5694
5695 /* Prepare an initial estimate in acc. Calculate this by */
5696 /* considering the coefficient of x to be a normalized fraction, */
5697 /* f, with the decimal point at far left and multiplied by */
5698 /* 10**r. Then, rhs=f*10**r and 0.1<=f<1, and */
5699 /* ln(x) = ln(f) + ln(10)*r */
5700 /* Get the initial estimate for ln(f) from a small lookup */
5701 /* table (see above) indexed by the first two digits of f, */
5702 /* truncated. */
5703
5704 decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5705 r=rhs->exponent+rhs->digits; /* 'normalised' exponent */
5706 decNumberFromInt32(a, r); /* a=r */
5707 decNumberFromInt32(b, 2302585); /* b=ln(10) (2.302585) */
5708 b->exponent=-6; /* .. */
5709 decMultiplyOp(a, a, b, &aset, &ignore); /* a=a*b */
5710 /* now get top two digits of rhs into b by simple truncate and */
5711 /* force to integer */
5712 residue=0; /* (no residue) */
5713 aset.digits=2; aset.round=DEC_ROUND_DOWN;
5714 decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5715 b->exponent=0; /* make integer */
5716 t=decGetInt(b); /* [cannot fail] */
5717 if (t<10) t=X10(t); /* adjust single-digit b */
5718 t=LNnn[t-10]; /* look up ln(b) */
5719 decNumberFromInt32(b, t>>2); /* b=ln(b) coefficient */
5720 b->exponent=-(t&3)-3; /* set exponent */
5721 b->bits=DECNEG; /* ln(0.10)->ln(0.99) always -ve */
5722 aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5723 decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5724 /* the initial estimate is now in a, with up to 4 digits correct. */
5725 /* When rhs is at or near Nmax the estimate will be low, so we */
5726 /* will approach it from below, avoiding overflow when calling exp. */
5727
5728 decNumberZero(&numone); *numone.lsu=1; /* constant 1 for adjustment */
5729
5730 /* accumulator bounds are as requested (could underflow, but */
5731 /* cannot overflow) */
5732 aset.emax=set->emax;
5733 aset.emin=set->emin;
5734 aset.clamp=0; /* no concrete format */
5735 /* set up a context to be used for the multiply and subtract */
5736 bset=aset;
5737 bset.emax=DEC_MAX_MATH*2; /* use double bounds for the */
5738 bset.emin=-DEC_MAX_MATH*2; /* adjustment calculation */
5739 /* [see decExpOp call below] */
5740 /* for each iteration double the number of digits to calculate, */
5741 /* up to a maximum of p */
5742 pp=9; /* initial precision */
5743 /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5744 /* 34+2, which is ideal for standard-sized numbers] */
5745 aset.digits=pp; /* working context */
5746 bset.digits=pp+rhs->digits; /* wider context */
5747 for (;;) { /* iterate */
5748 #if DECCHECK
5749 iterations++;
5750 if (iterations>24) break; /* consider 9 * 2**24 */
5751 #endif
5752 /* calculate the adjustment (exp(-a)*x-1) into b. This is a */
5753 /* catastrophic subtraction but it really is the difference */
5754 /* from 1 that is of interest. */
5755 /* Use the internal entry point to Exp as it allows the double */
5756 /* range for calculating exp(-a) when a is the tiniest subnormal. */
5757 a->bits^=DECNEG; /* make -a */
5758 decExpOp(b, a, &bset, &ignore); /* b=exp(-a) */
5759 a->bits^=DECNEG; /* restore sign of a */
5760 /* now multiply by rhs and subtract 1, at the wider precision */
5761 decMultiplyOp(b, b, rhs, &bset, &ignore); /* b=b*rhs */
5762 decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5763
5764 /* the iteration ends when the adjustment cannot affect the */
5765 /* result by >=0.5 ulp (at the requested digits), which */
5766 /* is when its value is smaller than the accumulator by */
5767 /* set->digits+1 digits (or it is zero) -- this is a looser */
5768 /* requirement than for Exp because all that happens to the */
5769 /* accumulator after this is the final rounding (but note that */
5770 /* there must also be full precision in a, or a=0). */
5771
5772 if (decNumberIsZero(b) ||
5773 (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5774 if (a->digits==p) break;
5775 if (decNumberIsZero(a)) {
5776 decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5777 if (cmp.lsu[0]==0) a->exponent=0; /* yes, exact 0 */
5778 else *status|=(DEC_Inexact | DEC_Rounded); /* no, inexact */
5779 break;
5780 }
5781 /* force padding if adjustment has gone to 0 before full length */
5782 if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5783 }
5784
5785 /* not done yet ... */
5786 decAddOp(a, a, b, &aset, 0, &ignore); /* a=a+b for next estimate */
5787 if (pp==p) continue; /* precision is at maximum */
5788 /* lengthen the next calculation */
5789 pp=pp*2; /* double precision */
5790 if (pp>p) pp=p; /* clamp to maximum */
5791 aset.digits=pp; /* working context */
5792 bset.digits=pp+rhs->digits; /* wider context */
5793 } /* Newton's iteration */
5794
5795 #if DECCHECK
5796 /* just a sanity check; remove the test to show always */
5797 if (iterations>24)
5798 printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5799 iterations, *status, p, rhs->digits);
5800 #endif
5801
5802 /* Copy and round the result to res */
5803 residue=1; /* indicate dirt to right */
5804 if (ISZERO(a)) residue=0; /* .. unless underflowed to 0 */
5805 aset.digits=set->digits; /* [use default rounding] */
5806 decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5807 decFinish(res, set, &residue, status); /* cleanup/set flags */
5808 } while(0); /* end protected */
5809
5810 if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5811 if (allocbufb!=NULL) free(allocbufb); /* .. */
5812 /* [status is handled by caller] */
5813 return res;
5814 } /* decLnOp */
5815
5816/* ------------------------------------------------------------------ */
5817/* decQuantizeOp -- force exponent to requested value */
5818/* */
5819/* This computes C = op(A, B), where op adjusts the coefficient */
5820/* of C (by rounding or shifting) such that the exponent (-scale) */
5821/* of C has the value B or matches the exponent of B. */
5822/* The numerical value of C will equal A, except for the effects of */
5823/* any rounding that occurred. */
5824/* */
5825/* res is C, the result. C may be A or B */
5826/* lhs is A, the number to adjust */
5827/* rhs is B, the requested exponent */
5828/* set is the context */
5829/* quant is 1 for quantize or 0 for rescale */
5830/* status is the status accumulator (this can be called without */
5831/* risk of control loss) */
5832/* */
5833/* C must have space for set->digits digits. */
5834/* */
5835/* Unless there is an error or the result is infinite, the exponent */
5836/* after the operation is guaranteed to be that requested. */
5837/* ------------------------------------------------------------------ */
5838static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5839 const decNumber *rhs, decContext *set,
5840 Flag quant, uInt *status) {
5841 #if DECSUBSET
5842 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
5843 decNumber *allocrhs=NULL; /* .., rhs */
5844 #endif
5845 const decNumber *inrhs=rhs; /* save original rhs */
5846 Int reqdigits=set->digits; /* requested DIGITS */
5847 Int reqexp; /* requested exponent [-scale] */
5848 Int residue=0; /* rounding residue */
5849 Int etiny=set->emin-(reqdigits-1);
5850
5851 #if DECCHECK
5852 if (decCheckOperands(res, lhs, rhs, set)) return res;
5853 #endif
5854
5855 do { /* protect allocated storage */
5856 #if DECSUBSET
5857 if (!set->extended) {
5858 /* reduce operands and set lostDigits status, as needed */
5859 if (lhs->digits>reqdigits) {
5860 alloclhs=decRoundOperand(lhs, set, status);
5861 if (alloclhs==NULL) break;
5862 lhs=alloclhs;
5863 }
5864 if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5865 allocrhs=decRoundOperand(rhs, set, status);
5866 if (allocrhs==NULL) break;
5867 rhs=allocrhs;
5868 }
5869 }
5870 #endif
5871 /* [following code does not require input rounding] */
5872
5873 /* Handle special values */
5874 if (SPECIALARGS) {
5875 /* NaNs get usual processing */
5876 if (SPECIALARGS & (DECSNAN | DECNAN))
5877 decNaNs(res, lhs, rhs, set, status);
5878 /* one infinity but not both is bad */
5879 else if ((lhs->bits ^ rhs->bits) & DECINF)
5880 *status|=DEC_Invalid_operation;
5881 /* both infinity: return lhs */
5882 else decNumberCopy(res, lhs); /* [nop if in place] */
5883 break;
5884 }
5885
5886 /* set requested exponent */
5887 if (quant) reqexp=inrhs->exponent; /* quantize -- match exponents */
5888 else { /* rescale -- use value of rhs */
5889 /* Original rhs must be an integer that fits and is in range, */
5890 /* which could be from -1999999997 to +999999999, thanks to */
5891 /* subnormals */
5892 reqexp=decGetInt(inrhs); /* [cannot fail] */
5893 }
5894
5895 #if DECSUBSET
5896 if (!set->extended) etiny=set->emin; /* no subnormals */
5897 #endif
5898
5899 if (reqexp==BADINT /* bad (rescale only) or .. */
5900 || reqexp==BIGODD || reqexp==BIGEVEN /* very big (ditto) or .. */
5901 || (reqexp<etiny) /* < lowest */
5902 || (reqexp>set->emax)) { /* > emax */
5903 *status|=DEC_Invalid_operation;
5904 break;}
5905
5906 /* the RHS has been processed, so it can be overwritten now if necessary */
5907 if (ISZERO(lhs)) { /* zero coefficient unchanged */
5908 decNumberCopy(res, lhs); /* [nop if in place] */
5909 res->exponent=reqexp; /* .. just set exponent */
5910 #if DECSUBSET
5911 if (!set->extended) res->bits=0; /* subset specification; no -0 */
5912 #endif
5913 }
5914 else { /* non-zero lhs */
5915 Int adjust=reqexp-lhs->exponent; /* digit adjustment needed */
5916 /* if adjusted coefficient will definitely not fit, give up now */
5917 if ((lhs->digits-adjust)>reqdigits) {
5918 *status|=DEC_Invalid_operation;
5919 break;
5920 }
5921
5922 if (adjust>0) { /* increasing exponent */
5923 /* this will decrease the length of the coefficient by adjust */
5924 /* digits, and must round as it does so */
5925 decContext workset; /* work */
5926 workset=*set; /* clone rounding, etc. */
5927 workset.digits=lhs->digits-adjust; /* set requested length */
5928 /* [note that the latter can be <1, here] */
5929 decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5930 decApplyRound(res, &workset, residue, status); /* .. and round */
5931 residue=0; /* [used] */
5932 /* If just rounded a 999s case, exponent will be off by one; */
5933 /* adjust back (after checking space), if so. */
5934 if (res->exponent>reqexp) {
5935 /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5936 /* set->digits==3 */
5937 if (res->digits==reqdigits) { /* cannot shift by 1 */
5938 *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5939 *status|=DEC_Invalid_operation;
5940 break;
5941 }
5942 res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5943 res->exponent--; /* (re)adjust the exponent. */
5944 }
5945 #if DECSUBSET
5946 if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5947 #endif
5948 } /* increase */
5949 else /* adjust<=0 */ { /* decreasing or = exponent */
5950 /* this will increase the length of the coefficient by -adjust */
5951 /* digits, by adding zero or more trailing zeros; this is */
5952 /* already checked for fit, above */
5953 decNumberCopy(res, lhs); /* [it will fit] */
5954 /* if padding needed (adjust<0), add it now... */
5955 if (adjust<0) {
5956 res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5957 res->exponent+=adjust; /* adjust the exponent */
5958 }
5959 } /* decrease */
5960 } /* non-zero */
5961
5962 /* Check for overflow [do not use Finalize in this case, as an */
5963 /* overflow here is a "don't fit" situation] */
5964 if (res->exponent>set->emax-res->digits+1) { /* too big */
5965 *status|=DEC_Invalid_operation;
5966 break;
5967 }
5968 else {
5969 decFinalize(res, set, &residue, status); /* set subnormal flags */
5970 *status&=~DEC_Underflow; /* suppress Underflow [754r] */
5971 }
5972 } while(0); /* end protected */
5973
5974 #if DECSUBSET
5975 if (allocrhs!=NULL) free(allocrhs); /* drop any storage used */
5976 if (alloclhs!=NULL) free(alloclhs); /* .. */
5977 #endif
5978 return res;
5979 } /* decQuantizeOp */
5980
5981/* ------------------------------------------------------------------ */
5982/* decCompareOp -- compare, min, or max two Numbers */
5983/* */
5984/* This computes C = A ? B and carries out one of four operations: */
5985/* COMPARE -- returns the signum (as a number) giving the */
5986/* result of a comparison unless one or both */
5987/* operands is a NaN (in which case a NaN results) */
5988/* COMPSIG -- as COMPARE except that a quiet NaN raises */
5989/* Invalid operation. */
5990/* COMPMAX -- returns the larger of the operands, using the */
5991/* 754r maxnum operation */
5992/* COMPMAXMAG -- ditto, comparing absolute values */
5993/* COMPMIN -- the 754r minnum operation */
5994/* COMPMINMAG -- ditto, comparing absolute values */
5995/* COMTOTAL -- returns the signum (as a number) giving the */
5996/* result of a comparison using 754r total ordering */
5997/* */
5998/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
5999/* lhs is A */
6000/* rhs is B */
6001/* set is the context */
6002/* op is the operation flag */
6003/* status is the usual accumulator */
6004/* */
6005/* C must have space for one digit for COMPARE or set->digits for */
6006/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */
6007/* ------------------------------------------------------------------ */
6008/* The emphasis here is on speed for common cases, and avoiding */
6009/* coefficient comparison if possible. */
6010/* ------------------------------------------------------------------ */
6011decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6012 const decNumber *rhs, decContext *set,
6013 Flag op, uInt *status) {
6014 #if DECSUBSET
6015 decNumber *alloclhs=NULL; /* non-NULL if rounded lhs allocated */
6016 decNumber *allocrhs=NULL; /* .., rhs */
6017 #endif
6018 Int result=0; /* default result value */
6019 uByte merged; /* work */
6020
6021 #if DECCHECK
6022 if (decCheckOperands(res, lhs, rhs, set)) return res;
6023 #endif
6024
6025 do { /* protect allocated storage */
6026 #if DECSUBSET
6027 if (!set->extended) {
6028 /* reduce operands and set lostDigits status, as needed */
6029 if (lhs->digits>set->digits) {
6030 alloclhs=decRoundOperand(lhs, set, status);
6031 if (alloclhs==NULL) {result=BADINT; break;}
6032 lhs=alloclhs;
6033 }
6034 if (rhs->digits>set->digits) {
6035 allocrhs=decRoundOperand(rhs, set, status);
6036 if (allocrhs==NULL) {result=BADINT; break;}
6037 rhs=allocrhs;
6038 }
6039 }
6040 #endif
6041 /* [following code does not require input rounding] */
6042
6043 /* If total ordering then handle differing signs 'up front' */
6044 if (op==COMPTOTAL) { /* total ordering */
6045 if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6046 result=-1;
6047 break;
6048 }
6049 if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6050 result=+1;
6051 break;
6052 }
6053 }
6054
6055 /* handle NaNs specially; let infinities drop through */
6056 /* This assumes sNaN (even just one) leads to NaN. */
6057 merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6058 if (merged) { /* a NaN bit set */
6059 if (op==COMPARE); /* result will be NaN */
6060 else if (op==COMPSIG) /* treat qNaN as sNaN */
6061 *status|=DEC_Invalid_operation | DEC_sNaN;
6062 else if (op==COMPTOTAL) { /* total ordering, always finite */
6063 /* signs are known to be the same; compute the ordering here */
6064 /* as if the signs are both positive, then invert for negatives */
6065 if (!decNumberIsNaN(lhs)) result=-1;
6066 else if (!decNumberIsNaN(rhs)) result=+1;
6067 /* here if both NaNs */
6068 else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6069 else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6070 else { /* both NaN or both sNaN */
6071 /* now it just depends on the payload */
6072 result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6073 rhs->lsu, D2U(rhs->digits), 0);
6074 /* [Error not possible, as these are 'aligned'] */
6075 } /* both same NaNs */
6076 if (decNumberIsNegative(lhs)) result=-result;
6077 break;
6078 } /* total order */
6079
6080 else if (merged & DECSNAN); /* sNaN -> qNaN */
6081 else { /* here if MIN or MAX and one or two quiet NaNs */
6082 /* min or max -- 754r rules ignore single NaN */
6083 if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6084 /* just one NaN; force choice to be the non-NaN operand */
6085 op=COMPMAX;
6086 if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6087 else result=+1; /* pick lhs */
6088 break;
6089 }
6090 } /* max or min */
6091 op=COMPNAN; /* use special path */
6092 decNaNs(res, lhs, rhs, set, status); /* propagate NaN */
6093 break;
6094 }
6095 /* have numbers */
6096 if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6097 else result=decCompare(lhs, rhs, 0); /* sign matters */
6098 } while(0); /* end protected */
6099
6100 if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6101 else {
6102 if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6103 if (op==COMPTOTAL && result==0) {
6104 /* operands are numerically equal or same NaN (and same sign, */
6105 /* tested first); if identical, leave result 0 */
6106 if (lhs->exponent!=rhs->exponent) {
6107 if (lhs->exponent<rhs->exponent) result=-1;
6108 else result=+1;
6109 if (decNumberIsNegative(lhs)) result=-result;
6110 } /* lexp!=rexp */
6111 } /* total-order by exponent */
6112 decNumberZero(res); /* [always a valid result] */
6113 if (result!=0) { /* must be -1 or +1 */
6114 *res->lsu=1;
6115 if (result<0) res->bits=DECNEG;
6116 }
6117 }
6118 else if (op==COMPNAN); /* special, drop through */
6119 else { /* MAX or MIN, non-NaN result */
6120 Int residue=0; /* rounding accumulator */
6121 /* choose the operand for the result */
6122 const decNumber *choice;
6123 if (result==0) { /* operands are numerically equal */
6124 /* choose according to sign then exponent (see 754r) */
6125 uByte slhs=(lhs->bits & DECNEG);
6126 uByte srhs=(rhs->bits & DECNEG);
6127 #if DECSUBSET
6128 if (!set->extended) { /* subset: force left-hand */
6129 op=COMPMAX;
6130 result=+1;
6131 }
6132 else
6133 #endif
6134 if (slhs!=srhs) { /* signs differ */
6135 if (slhs) result=-1; /* rhs is max */
6136 else result=+1; /* lhs is max */
6137 }
6138 else if (slhs && srhs) { /* both negative */
6139 if (lhs->exponent<rhs->exponent) result=+1;
6140 else result=-1;
6141 /* [if equal, use lhs, technically identical] */
6142 }
6143 else { /* both positive */
6144 if (lhs->exponent>rhs->exponent) result=+1;
6145 else result=-1;
6146 /* [ditto] */
6147 }
6148 } /* numerically equal */
6149 /* here result will be non-0; reverse if looking for MIN */
6150 if (op==COMPMIN || op==COMPMINMAG) result=-result;
6151 choice=(result>0 ? lhs : rhs); /* choose */
6152 /* copy chosen to result, rounding if need be */
6153 decCopyFit(res, choice, set, &residue, status);
6154 decFinish(res, set, &residue, status);
6155 }
6156 }
6157 #if DECSUBSET
6158 if (allocrhs!=NULL) free(allocrhs); /* free any storage used */
6159 if (alloclhs!=NULL) free(alloclhs); /* .. */
6160 #endif
6161 return res;
6162 } /* decCompareOp */
6163
6164/* ------------------------------------------------------------------ */
6165/* decCompare -- compare two decNumbers by numerical value */
6166/* */
6167/* This routine compares A ? B without altering them. */
6168/* */
6169/* Arg1 is A, a decNumber which is not a NaN */
6170/* Arg2 is B, a decNumber which is not a NaN */
6171/* Arg3 is 1 for a sign-independent compare, 0 otherwise */
6172/* */
6173/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6174/* (the only possible failure is an allocation error) */
6175/* ------------------------------------------------------------------ */
6176static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6177 Flag abs) {
6178 Int result; /* result value */
6179 Int sigr; /* rhs signum */
6180 Int compare; /* work */
6181
6182 result=1; /* assume signum(lhs) */
6183 if (ISZERO(lhs)) result=0;
6184 if (abs) {
6185 if (ISZERO(rhs)) return result; /* LHS wins or both 0 */
6186 /* RHS is non-zero */
6187 if (result==0) return -1; /* LHS is 0; RHS wins */
6188 /* [here, both non-zero, result=1] */
6189 }
6190 else { /* signs matter */
6191 if (result && decNumberIsNegative(lhs)) result=-1;
6192 sigr=1; /* compute signum(rhs) */
6193 if (ISZERO(rhs)) sigr=0;
6194 else if (decNumberIsNegative(rhs)) sigr=-1;
6195 if (result > sigr) return +1; /* L > R, return 1 */
6196 if (result < sigr) return -1; /* L < R, return -1 */
6197 if (result==0) return 0; /* both 0 */
6198 }
6199
6200 /* signums are the same; both are non-zero */
6201 if ((lhs->bits | rhs->bits) & DECINF) { /* one or more infinities */
6202 if (decNumberIsInfinite(rhs)) {
6203 if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6204 else result=-result; /* only rhs infinite */
6205 }
6206 return result;
6207 }
6208 /* must compare the coefficients, allowing for exponents */
6209 if (lhs->exponent>rhs->exponent) { /* LHS exponent larger */
6210 /* swap sides, and sign */
6211 const decNumber *temp=lhs;
6212 lhs=rhs;
6213 rhs=temp;
6214 result=-result;
6215 }
6216 compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6217 rhs->lsu, D2U(rhs->digits),
6218 rhs->exponent-lhs->exponent);
6219 if (compare!=BADINT) compare*=result; /* comparison succeeded */
6220 return compare;
6221 } /* decCompare */
6222
6223/* ------------------------------------------------------------------ */
6224/* decUnitCompare -- compare two >=0 integers in Unit arrays */
6225/* */
6226/* This routine compares A ? B*10**E where A and B are unit arrays */
6227/* A is a plain integer */
6228/* B has an exponent of E (which must be non-negative) */
6229/* */
6230/* Arg1 is A first Unit (lsu) */
6231/* Arg2 is A length in Units */
6232/* Arg3 is B first Unit (lsu) */
6233/* Arg4 is B length in Units */
6234/* Arg5 is E (0 if the units are aligned) */
6235/* */
6236/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */
6237/* (the only possible failure is an allocation error, which can */
6238/* only occur if E!=0) */
6239/* ------------------------------------------------------------------ */
6240static Int decUnitCompare(const Unit *a, Int alength,
6241 const Unit *b, Int blength, Int exp) {
6242 Unit *acc; /* accumulator for result */
6243 Unit accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6244 Unit *allocacc=NULL; /* -> allocated acc buffer, iff allocated */
6245 Int accunits, need; /* units in use or needed for acc */
6246 const Unit *l, *r, *u; /* work */
6247 Int expunits, exprem, result; /* .. */
6248
6249 if (exp==0) { /* aligned; fastpath */
6250 if (alength>blength) return 1;
6251 if (alength<blength) return -1;
6252 /* same number of units in both -- need unit-by-unit compare */
6253 l=a+alength-1;
6254 r=b+alength-1;
6255 for (;l>=a; l--, r--) {
6256 if (*l>*r) return 1;
6257 if (*l<*r) return -1;
6258 }
6259 return 0; /* all units match */
6260 } /* aligned */
6261
6262 /* Unaligned. If one is >1 unit longer than the other, padded */
6263 /* approximately, then can return easily */
6264 if (alength>blength+(Int)D2U(exp)) return 1;
6265 if (alength+1<blength+(Int)D2U(exp)) return -1;
6266
6267 /* Need to do a real subtract. For this, a result buffer is needed */
6268 /* even though only the sign is of interest. Its length needs */
6269 /* to be the larger of alength and padded blength, +2 */
6270 need=blength+D2U(exp); /* maximum real length of B */
6271 if (need<alength) need=alength;
6272 need+=2;
6273 acc=accbuff; /* assume use local buffer */
6274 if (need*sizeof(Unit)>sizeof(accbuff)) {
6275 allocacc=(Unit *)malloc(need*sizeof(Unit));
6276 if (allocacc==NULL) return BADINT; /* hopeless -- abandon */
6277 acc=allocacc;
6278 }
6279 /* Calculate units and remainder from exponent. */
6280 expunits=exp/DECDPUN;
6281 exprem=exp%DECDPUN;
6282 /* subtract [A+B*(-m)] */
6283 accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6284 -(Int)powers[exprem]);
6285 /* [UnitAddSub result may have leading zeros, even on zero] */
6286 if (accunits<0) result=-1; /* negative result */
6287 else { /* non-negative result */
6288 /* check units of the result before freeing any storage */
6289 for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6290 result=(*u==0 ? 0 : +1);
6291 }
6292 /* clean up and return the result */
6293 if (allocacc!=NULL) free(allocacc); /* drop any storage used */
6294 return result;
6295 } /* decUnitCompare */
6296
6297/* ------------------------------------------------------------------ */
6298/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */
6299/* */
6300/* This routine performs the calculation: */
6301/* */
6302/* C=A+(B*M) */
6303/* */
6304/* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */
6305/* */
6306/* A may be shorter or longer than B. */
6307/* */
6308/* Leading zeros are not removed after a calculation. The result is */
6309/* either the same length as the longer of A and B (adding any */
6310/* shift), or one Unit longer than that (if a Unit carry occurred). */
6311/* */
6312/* A and B content are not altered unless C is also A or B. */
6313/* C may be the same array as A or B, but only if no zero padding is */
6314/* requested (that is, C may be B only if bshift==0). */
6315/* C is filled from the lsu; only those units necessary to complete */
6316/* the calculation are referenced. */
6317/* */
6318/* Arg1 is A first Unit (lsu) */
6319/* Arg2 is A length in Units */
6320/* Arg3 is B first Unit (lsu) */
6321/* Arg4 is B length in Units */
6322/* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */
6323/* Arg6 is C first Unit (lsu) */
6324/* Arg7 is M, the multiplier */
6325/* */
6326/* returns the count of Units written to C, which will be non-zero */
6327/* and negated if the result is negative. That is, the sign of the */
6328/* returned Int is the sign of the result (positive for zero) and */
6329/* the absolute value of the Int is the count of Units. */
6330/* */
6331/* It is the caller's responsibility to make sure that C size is */
6332/* safe, allowing space if necessary for a one-Unit carry. */
6333/* */
6334/* This routine is severely performance-critical; *any* change here */
6335/* must be measured (timed) to assure no performance degradation. */
6336/* In particular, trickery here tends to be counter-productive, as */
6337/* increased complexity of code hurts register optimizations on */
6338/* register-poor architectures. Avoiding divisions is nearly */
6339/* always a Good Idea, however. */
6340/* */
6341/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */
6342/* (IBM Warwick, UK) for some of the ideas used in this routine. */
6343/* ------------------------------------------------------------------ */
6344static Int decUnitAddSub(const Unit *a, Int alength,
6345 const Unit *b, Int blength, Int bshift,
6346 Unit *c, Int m) {
6347 const Unit *alsu=a; /* A lsu [need to remember it] */
6348 Unit *clsu=c; /* C ditto */
6349 Unit *minC; /* low water mark for C */
6350 Unit *maxC; /* high water mark for C */
6351 eInt carry=0; /* carry integer (could be Long) */
6352 Int add; /* work */
6353 #if DECDPUN<=4 /* myriadal, millenary, etc. */
6354 Int est; /* estimated quotient */
6355 #endif
6356
6357 #if DECTRACE
6358 if (alength<1 || blength<1)
6359 printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6360 #endif
6361
6362 maxC=c+alength; /* A is usually the longer */
6363 minC=c+blength; /* .. and B the shorter */
6364 if (bshift!=0) { /* B is shifted; low As copy across */
6365 minC+=bshift;
6366 /* if in place [common], skip copy unless there's a gap [rare] */
6367 if (a==c && bshift<=alength) {
6368 c+=bshift;
6369 a+=bshift;
6370 }
6371 else for (; c<clsu+bshift; a++, c++) { /* copy needed */
6372 if (a<alsu+alength) *c=*a;
6373 else *c=0;
6374 }
6375 }
6376 if (minC>maxC) { /* swap */
6377 Unit *hold=minC;
6378 minC=maxC;
6379 maxC=hold;
6380 }
6381
6382 /* For speed, do the addition as two loops; the first where both A */
6383 /* and B contribute, and the second (if necessary) where only one or */
6384 /* other of the numbers contribute. */
6385 /* Carry handling is the same (i.e., duplicated) in each case. */
6386 for (; c<minC; c++) {
6387 carry+=*a;
6388 a++;
6389 carry+=((eInt)*b)*m; /* [special-casing m=1/-1 */
6390 b++; /* here is not a win] */
6391 /* here carry is new Unit of digits; it could be +ve or -ve */
6392 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6393 *c=(Unit)carry;
6394 carry=0;
6395 continue;
6396 }
6397 #if DECDPUN==4 /* use divide-by-multiply */
6398 if (carry>=0) {
6399 est=(((ueInt)carry>>11)*53687)>>18;
6400 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6401 carry=est; /* likely quotient [89%] */
6402 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6403 carry++;
6404 *c-=DECDPUNMAX+1;
6405 continue;
6406 }
6407 /* negative case */
6408 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6409 est=(((ueInt)carry>>11)*53687)>>18;
6410 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6411 carry=est-(DECDPUNMAX+1); /* correctly negative */
6412 if (*c<DECDPUNMAX+1) continue; /* was OK */
6413 carry++;
6414 *c-=DECDPUNMAX+1;
6415 #elif DECDPUN==3
6416 if (carry>=0) {
6417 est=(((ueInt)carry>>3)*16777)>>21;
6418 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6419 carry=est; /* likely quotient [99%] */
6420 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6421 carry++;
6422 *c-=DECDPUNMAX+1;
6423 continue;
6424 }
6425 /* negative case */
6426 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6427 est=(((ueInt)carry>>3)*16777)>>21;
6428 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6429 carry=est-(DECDPUNMAX+1); /* correctly negative */
6430 if (*c<DECDPUNMAX+1) continue; /* was OK */
6431 carry++;
6432 *c-=DECDPUNMAX+1;
6433 #elif DECDPUN<=2
6434 /* Can use QUOT10 as carry <= 4 digits */
6435 if (carry>=0) {
6436 est=QUOT10(carry, DECDPUN);
6437 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6438 carry=est; /* quotient */
6439 continue;
6440 }
6441 /* negative case */
6442 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6443 est=QUOT10(carry, DECDPUN);
6444 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6445 carry=est-(DECDPUNMAX+1); /* correctly negative */
6446 #else
6447 /* remainder operator is undefined if negative, so must test */
6448 if ((ueInt)carry<(DECDPUNMAX+1)*2) { /* fastpath carry +1 */
6449 *c=(Unit)(carry-(DECDPUNMAX+1)); /* [helps additions] */
6450 carry=1;
6451 continue;
6452 }
6453 if (carry>=0) {
6454 *c=(Unit)(carry%(DECDPUNMAX+1));
6455 carry=carry/(DECDPUNMAX+1);
6456 continue;
6457 }
6458 /* negative case */
6459 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6460 *c=(Unit)(carry%(DECDPUNMAX+1));
6461 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6462 #endif
6463 } /* c */
6464
6465 /* now may have one or other to complete */
6466 /* [pretest to avoid loop setup/shutdown] */
6467 if (c<maxC) for (; c<maxC; c++) {
6468 if (a<alsu+alength) { /* still in A */
6469 carry+=*a;
6470 a++;
6471 }
6472 else { /* inside B */
6473 carry+=((eInt)*b)*m;
6474 b++;
6475 }
6476 /* here carry is new Unit of digits; it could be +ve or -ve and */
6477 /* magnitude up to DECDPUNMAX squared */
6478 if ((ueInt)carry<=DECDPUNMAX) { /* fastpath 0-DECDPUNMAX */
6479 *c=(Unit)carry;
6480 carry=0;
6481 continue;
6482 }
6483 /* result for this unit is negative or >DECDPUNMAX */
6484 #if DECDPUN==4 /* use divide-by-multiply */
6485 if (carry>=0) {
6486 est=(((ueInt)carry>>11)*53687)>>18;
6487 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6488 carry=est; /* likely quotient [79.7%] */
6489 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6490 carry++;
6491 *c-=DECDPUNMAX+1;
6492 continue;
6493 }
6494 /* negative case */
6495 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6496 est=(((ueInt)carry>>11)*53687)>>18;
6497 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6498 carry=est-(DECDPUNMAX+1); /* correctly negative */
6499 if (*c<DECDPUNMAX+1) continue; /* was OK */
6500 carry++;
6501 *c-=DECDPUNMAX+1;
6502 #elif DECDPUN==3
6503 if (carry>=0) {
6504 est=(((ueInt)carry>>3)*16777)>>21;
6505 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6506 carry=est; /* likely quotient [99%] */
6507 if (*c<DECDPUNMAX+1) continue; /* estimate was correct */
6508 carry++;
6509 *c-=DECDPUNMAX+1;
6510 continue;
6511 }
6512 /* negative case */
6513 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6514 est=(((ueInt)carry>>3)*16777)>>21;
6515 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6516 carry=est-(DECDPUNMAX+1); /* correctly negative */
6517 if (*c<DECDPUNMAX+1) continue; /* was OK */
6518 carry++;
6519 *c-=DECDPUNMAX+1;
6520 #elif DECDPUN<=2
6521 if (carry>=0) {
6522 est=QUOT10(carry, DECDPUN);
6523 *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6524 carry=est; /* quotient */
6525 continue;
6526 }
6527 /* negative case */
6528 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6529 est=QUOT10(carry, DECDPUN);
6530 *c=(Unit)(carry-est*(DECDPUNMAX+1));
6531 carry=est-(DECDPUNMAX+1); /* correctly negative */
6532 #else
6533 if ((ueInt)carry<(DECDPUNMAX+1)*2){ /* fastpath carry 1 */
6534 *c=(Unit)(carry-(DECDPUNMAX+1));
6535 carry=1;
6536 continue;
6537 }
6538 /* remainder operator is undefined if negative, so must test */
6539 if (carry>=0) {
6540 *c=(Unit)(carry%(DECDPUNMAX+1));
6541 carry=carry/(DECDPUNMAX+1);
6542 continue;
6543 }
6544 /* negative case */
6545 carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6546 *c=(Unit)(carry%(DECDPUNMAX+1));
6547 carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6548 #endif
6549 } /* c */
6550
6551 /* OK, all A and B processed; might still have carry or borrow */
6552 /* return number of Units in the result, negated if a borrow */
6553 if (carry==0) return c-clsu; /* no carry, so no more to do */
6554 if (carry>0) { /* positive carry */
6555 *c=(Unit)carry; /* place as new unit */
6556 c++; /* .. */
6557 return c-clsu;
6558 }
6559 /* -ve carry: it's a borrow; complement needed */
6560 add=1; /* temporary carry... */
6561 for (c=clsu; c<maxC; c++) {
6562 add=DECDPUNMAX+add-*c;
6563 if (add<=DECDPUNMAX) {
6564 *c=(Unit)add;
6565 add=0;
6566 }
6567 else {
6568 *c=0;
6569 add=1;
6570 }
6571 }
6572 /* add an extra unit iff it would be non-zero */
6573 #if DECTRACE
6574 printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6575 #endif
6576 if ((add-carry-1)!=0) {
6577 *c=(Unit)(add-carry-1);
6578 c++; /* interesting, include it */
6579 }
6580 return clsu-c; /* -ve result indicates borrowed */
6581 } /* decUnitAddSub */
6582
6583/* ------------------------------------------------------------------ */
6584/* decTrim -- trim trailing zeros or normalize */
6585/* */
6586/* dn is the number to trim or normalize */
6587/* set is the context to use to check for clamp */
6588/* all is 1 to remove all trailing zeros, 0 for just fraction ones */
6589/* dropped returns the number of discarded trailing zeros */
6590/* returns dn */
6591/* */
6592/* If clamp is set in the context then the number of zeros trimmed */
6593/* may be limited if the exponent is high. */
6594/* All fields are updated as required. This is a utility operation, */
6595/* so special values are unchanged and no error is possible. */
6596/* ------------------------------------------------------------------ */
6597static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6598 Int *dropped) {
6599 Int d, exp; /* work */
6600 uInt cut; /* .. */
6601 Unit *up; /* -> current Unit */
6602
6603 #if DECCHECK
6604 if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6605 #endif
6606
6607 *dropped=0; /* assume no zeros dropped */
6608 if ((dn->bits & DECSPECIAL) /* fast exit if special .. */
6609 || (*dn->lsu & 0x01)) return dn; /* .. or odd */
6610 if (ISZERO(dn)) { /* .. or 0 */
6611 dn->exponent=0; /* (sign is preserved) */
6612 return dn;
6613 }
6614
6615 /* have a finite number which is even */
6616 exp=dn->exponent;
6617 cut=1; /* digit (1-DECDPUN) in Unit */
6618 up=dn->lsu; /* -> current Unit */
6619 for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6620 /* slice by powers */
6621 #if DECDPUN<=4
6622 uInt quot=QUOT10(*up, cut);
6623 if ((*up-quot*powers[cut])!=0) break; /* found non-0 digit */
6624 #else
6625 if (*up%powers[cut]!=0) break; /* found non-0 digit */
6626 #endif
6627 /* have a trailing 0 */
6628 if (!all) { /* trimming */
6629 /* [if exp>0 then all trailing 0s are significant for trim] */
6630 if (exp<=0) { /* if digit might be significant */
6631 if (exp==0) break; /* then quit */
6632 exp++; /* next digit might be significant */
6633 }
6634 }
6635 cut++; /* next power */
6636 if (cut>DECDPUN) { /* need new Unit */
6637 up++;
6638 cut=1;
6639 }
6640 } /* d */
6641 if (d==0) return dn; /* none to drop */
6642
6643 /* may need to limit drop if clamping */
6644 if (set->clamp) {
6645 Int maxd=set->emax-set->digits+1-dn->exponent;
6646 if (maxd<=0) return dn; /* nothing possible */
6647 if (d>maxd) d=maxd;
6648 }
6649
6650 /* effect the drop */
6651 decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6652 dn->exponent+=d; /* maintain numerical value */
6653 dn->digits-=d; /* new length */
6654 *dropped=d; /* report the count */
6655 return dn;
6656 } /* decTrim */
6657
6658/* ------------------------------------------------------------------ */
6659/* decReverse -- reverse a Unit array in place */
6660/* */
6661/* ulo is the start of the array */
6662/* uhi is the end of the array (highest Unit to include) */
6663/* */
6664/* The units ulo through uhi are reversed in place (if the number */
6665/* of units is odd, the middle one is untouched). Note that the */
6666/* digit(s) in each unit are unaffected. */
6667/* ------------------------------------------------------------------ */
6668static void decReverse(Unit *ulo, Unit *uhi) {
6669 Unit temp;
6670 for (; ulo<uhi; ulo++, uhi--) {
6671 temp=*ulo;
6672 *ulo=*uhi;
6673 *uhi=temp;
6674 }
6675 return;
6676 } /* decReverse */
6677
6678/* ------------------------------------------------------------------ */
6679/* decShiftToMost -- shift digits in array towards most significant */
6680/* */
6681/* uar is the array */
6682/* digits is the count of digits in use in the array */
6683/* shift is the number of zeros to pad with (least significant); */
6684/* it must be zero or positive */
6685/* */
6686/* returns the new length of the integer in the array, in digits */
6687/* */
6688/* No overflow is permitted (that is, the uar array must be known to */
6689/* be large enough to hold the result, after shifting). */
6690/* ------------------------------------------------------------------ */
6691static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6692 Unit *target, *source, *first; /* work */
6693 Int cut; /* odd 0's to add */
6694 uInt next; /* work */
6695
6696 if (shift==0) return digits; /* [fastpath] nothing to do */
6697 if ((digits+shift)<=DECDPUN) { /* [fastpath] single-unit case */
6698 *uar=(Unit)(*uar*powers[shift]);
6699 return digits+shift;
6700 }
6701
6702 next=0; /* all paths */
6703 source=uar+D2U(digits)-1; /* where msu comes from */
6704 target=source+D2U(shift); /* where upper part of first cut goes */
6705 cut=DECDPUN-MSUDIGITS(shift); /* where to slice */
6706 if (cut==0) { /* unit-boundary case */
6707 for (; source>=uar; source--, target--) *target=*source;
6708 }
6709 else {
6710 first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6711 for (; source>=uar; source--, target--) {
6712 /* split the source Unit and accumulate remainder for next */
6713 #if DECDPUN<=4
6714 uInt quot=QUOT10(*source, cut);
6715 uInt rem=*source-quot*powers[cut];
6716 next+=quot;
6717 #else
6718 uInt rem=*source%powers[cut];
6719 next+=*source/powers[cut];
6720 #endif
6721 if (target<=first) *target=(Unit)next; /* write to target iff valid */
6722 next=rem*powers[DECDPUN-cut]; /* save remainder for next Unit */
6723 }
6724 } /* shift-move */
6725
6726 /* propagate any partial unit to one below and clear the rest */
6727 for (; target>=uar; target--) {
6728 *target=(Unit)next;
6729 next=0;
6730 }
6731 return digits+shift;
6732 } /* decShiftToMost */
6733
6734/* ------------------------------------------------------------------ */
6735/* decShiftToLeast -- shift digits in array towards least significant */
6736/* */
6737/* uar is the array */
6738/* units is length of the array, in units */
6739/* shift is the number of digits to remove from the lsu end; it */
6740/* must be zero or positive and <= than units*DECDPUN. */
6741/* */
6742/* returns the new length of the integer in the array, in units */
6743/* */
6744/* Removed digits are discarded (lost). Units not required to hold */
6745/* the final result are unchanged. */
6746/* ------------------------------------------------------------------ */
6747static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6748 Unit *target, *up; /* work */
6749 Int cut, count; /* work */
6750 Int quot, rem; /* for division */
6751
6752 if (shift==0) return units; /* [fastpath] nothing to do */
6753 if (shift==units*DECDPUN) { /* [fastpath] little to do */
6754 *uar=0; /* all digits cleared gives zero */
6755 return 1; /* leaves just the one */
6756 }
6757
6758 target=uar; /* both paths */
6759 cut=MSUDIGITS(shift);
6760 if (cut==DECDPUN) { /* unit-boundary case; easy */
6761 up=uar+D2U(shift);
6762 for (; up<uar+units; target++, up++) *target=*up;
6763 return target-uar;
6764 }
6765
6766 /* messier */
6767 up=uar+D2U(shift-cut); /* source; correct to whole Units */
6768 count=units*DECDPUN-shift; /* the maximum new length */
6769 #if DECDPUN<=4
6770 quot=QUOT10(*up, cut);
6771 #else
6772 quot=*up/powers[cut];
6773 #endif
6774 for (; ; target++) {
6775 *target=(Unit)quot;
6776 count-=(DECDPUN-cut);
6777 if (count<=0) break;
6778 up++;
6779 quot=*up;
6780 #if DECDPUN<=4
6781 quot=QUOT10(quot, cut);
6782 rem=*up-quot*powers[cut];
6783 #else
6784 rem=quot%powers[cut];
6785 quot=quot/powers[cut];
6786 #endif
6787 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6788 count-=cut;
6789 if (count<=0) break;
6790 }
6791 return target-uar+1;
6792 } /* decShiftToLeast */
6793
6794#if DECSUBSET
6795/* ------------------------------------------------------------------ */
6796/* decRoundOperand -- round an operand [used for subset only] */
6797/* */
6798/* dn is the number to round (dn->digits is > set->digits) */
6799/* set is the relevant context */
6800/* status is the status accumulator */
6801/* */
6802/* returns an allocated decNumber with the rounded result. */
6803/* */
6804/* lostDigits and other status may be set by this. */
6805/* */
6806/* Since the input is an operand, it must not be modified. */
6807/* Instead, return an allocated decNumber, rounded as required. */
6808/* It is the caller's responsibility to free the allocated storage. */
6809/* */
6810/* If no storage is available then the result cannot be used, so NULL */
6811/* is returned. */
6812/* ------------------------------------------------------------------ */
6813static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6814 uInt *status) {
6815 decNumber *res; /* result structure */
6816 uInt newstatus=0; /* status from round */
6817 Int residue=0; /* rounding accumulator */
6818
6819 /* Allocate storage for the returned decNumber, big enough for the */
6820 /* length specified by the context */
6821 res=(decNumber *)malloc(sizeof(decNumber)
6822 +(D2U(set->digits)-1)*sizeof(Unit));
6823 if (res==NULL) {
6824 *status|=DEC_Insufficient_storage;
6825 return NULL;
6826 }
6827 decCopyFit(res, dn, set, &residue, &newstatus);
6828 decApplyRound(res, set, residue, &newstatus);
6829
6830 /* If that set Inexact then "lost digits" is raised... */
6831 if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6832 *status|=newstatus;
6833 return res;
6834 } /* decRoundOperand */
6835#endif
6836
6837/* ------------------------------------------------------------------ */
6838/* decCopyFit -- copy a number, truncating the coefficient if needed */
6839/* */
6840/* dest is the target decNumber */
6841/* src is the source decNumber */
6842/* set is the context [used for length (digits) and rounding mode] */
6843/* residue is the residue accumulator */
6844/* status contains the current status to be updated */
6845/* */
6846/* (dest==src is allowed and will be a no-op if fits) */
6847/* All fields are updated as required. */
6848/* ------------------------------------------------------------------ */
6849static void decCopyFit(decNumber *dest, const decNumber *src,
6850 decContext *set, Int *residue, uInt *status) {
6851 dest->bits=src->bits;
6852 dest->exponent=src->exponent;
6853 decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6854 } /* decCopyFit */
6855
6856/* ------------------------------------------------------------------ */
6857/* decSetCoeff -- set the coefficient of a number */
6858/* */
6859/* dn is the number whose coefficient array is to be set. */
6860/* It must have space for set->digits digits */
6861/* set is the context [for size] */
6862/* lsu -> lsu of the source coefficient [may be dn->lsu] */
6863/* len is digits in the source coefficient [may be dn->digits] */
6864/* residue is the residue accumulator. This has values as in */
6865/* decApplyRound, and will be unchanged unless the */
6866/* target size is less than len. In this case, the */
6867/* coefficient is truncated and the residue is updated to */
6868/* reflect the previous residue and the dropped digits. */
6869/* status is the status accumulator, as usual */
6870/* */
6871/* The coefficient may already be in the number, or it can be an */
6872/* external intermediate array. If it is in the number, lsu must == */
6873/* dn->lsu and len must == dn->digits. */
6874/* */
6875/* Note that the coefficient length (len) may be < set->digits, and */
6876/* in this case this merely copies the coefficient (or is a no-op */
6877/* if dn->lsu==lsu). */
6878/* */
6879/* Note also that (only internally, from decQuantizeOp and */
6880/* decSetSubnormal) the value of set->digits may be less than one, */
6881/* indicating a round to left. This routine handles that case */
6882/* correctly; caller ensures space. */
6883/* */
6884/* dn->digits, dn->lsu (and as required), and dn->exponent are */
6885/* updated as necessary. dn->bits (sign) is unchanged. */
6886/* */
6887/* DEC_Rounded status is set if any digits are discarded. */
6888/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6889/* incoming residue was non-0 (implies rounded) */
6890/* ------------------------------------------------------------------ */
6891/* mapping array: maps 0-9 to canonical residues, so that a residue */
6892/* can be adjusted in the range [-1, +1] and achieve correct rounding */
6893/* 0 1 2 3 4 5 6 7 8 9 */
6894static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6895static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6896 Int len, Int *residue, uInt *status) {
6897 Int discard; /* number of digits to discard */
6898 uInt cut; /* cut point in Unit */
6899 const Unit *up; /* work */
6900 Unit *target; /* .. */
6901 Int count; /* .. */
6902 #if DECDPUN<=4
6903 uInt temp; /* .. */
6904 #endif
6905
6906 discard=len-set->digits; /* digits to discard */
6907 if (discard<=0) { /* no digits are being discarded */
6908 if (dn->lsu!=lsu) { /* copy needed */
6909 /* copy the coefficient array to the result number; no shift needed */
6910 count=len; /* avoids D2U */
6911 up=lsu;
6912 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6913 *target=*up;
6914 dn->digits=len; /* set the new length */
6915 }
6916 /* dn->exponent and residue are unchanged, record any inexactitude */
6917 if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6918 return;
6919 }
6920
6921 /* some digits must be discarded ... */
6922 dn->exponent+=discard; /* maintain numerical value */
6923 *status|=DEC_Rounded; /* accumulate Rounded status */
6924 if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6925
6926 if (discard>len) { /* everything, +1, is being discarded */
6927 /* guard digit is 0 */
6928 /* residue is all the number [NB could be all 0s] */
6929 if (*residue<=0) { /* not already positive */
6930 count=len; /* avoids D2U */
6931 for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6932 *residue=1;
6933 break; /* no need to check any others */
6934 }
6935 }
6936 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6937 *dn->lsu=0; /* coefficient will now be 0 */
6938 dn->digits=1; /* .. */
6939 return;
6940 } /* total discard */
6941
6942 /* partial discard [most common case] */
6943 /* here, at least the first (most significant) discarded digit exists */
6944
6945 /* spin up the number, noting residue during the spin, until get to */
6946 /* the Unit with the first discarded digit. When reach it, extract */
6947 /* it and remember its position */
6948 count=0;
6949 for (up=lsu;; up++) {
6950 count+=DECDPUN;
6951 if (count>=discard) break; /* full ones all checked */
6952 if (*up!=0) *residue=1;
6953 } /* up */
6954
6955 /* here up -> Unit with first discarded digit */
6956 cut=discard-(count-DECDPUN)-1;
6957 if (cut==DECDPUN-1) { /* unit-boundary case (fast) */
6958 Unit half=(Unit)powers[DECDPUN]>>1;
6959 /* set residue directly */
6960 if (*up>=half) {
6961 if (*up>half) *residue=7;
6962 else *residue+=5; /* add sticky bit */
6963 }
6964 else { /* <half */
6965 if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
6966 }
6967 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
6968 *dn->lsu=0; /* .. result is 0 */
6969 dn->digits=1; /* .. */
6970 }
6971 else { /* shift to least */
6972 count=set->digits; /* now digits to end up with */
6973 dn->digits=count; /* set the new length */
6974 up++; /* move to next */
6975 /* on unit boundary, so shift-down copy loop is simple */
6976 for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6977 *target=*up;
6978 }
6979 } /* unit-boundary case */
6980
6981 else { /* discard digit is in low digit(s), and not top digit */
6982 uInt discard1; /* first discarded digit */
6983 uInt quot, rem; /* for divisions */
6984 if (cut==0) quot=*up; /* is at bottom of unit */
6985 else /* cut>0 */ { /* it's not at bottom of unit */
6986 #if DECDPUN<=4
6987 quot=QUOT10(*up, cut);
6988 rem=*up-quot*powers[cut];
6989 #else
6990 rem=*up%powers[cut];
6991 quot=*up/powers[cut];
6992 #endif
6993 if (rem!=0) *residue=1;
6994 }
6995 /* discard digit is now at bottom of quot */
6996 #if DECDPUN<=4
6997 temp=(quot*6554)>>16; /* fast /10 */
6998 /* Vowels algorithm here not a win (9 instructions) */
6999 discard1=quot-X10(temp);
7000 quot=temp;
7001 #else
7002 discard1=quot%10;
7003 quot=quot/10;
7004 #endif
7005 /* here, discard1 is the guard digit, and residue is everything */
7006 /* else [use mapping array to accumulate residue safely] */
7007 *residue+=resmap[discard1];
7008 cut++; /* update cut */
7009 /* here: up -> Unit of the array with bottom digit */
7010 /* cut is the division point for each Unit */
7011 /* quot holds the uncut high-order digits for the current unit */
7012 if (set->digits<=0) { /* special for Quantize/Subnormal :-( */
7013 *dn->lsu=0; /* .. result is 0 */
7014 dn->digits=1; /* .. */
7015 }
7016 else { /* shift to least needed */
7017 count=set->digits; /* now digits to end up with */
7018 dn->digits=count; /* set the new length */
7019 /* shift-copy the coefficient array to the result number */
7020 for (target=dn->lsu; ; target++) {
7021 *target=(Unit)quot;
7022 count-=(DECDPUN-cut);
7023 if (count<=0) break;
7024 up++;
7025 quot=*up;
7026 #if DECDPUN<=4
7027 quot=QUOT10(quot, cut);
7028 rem=*up-quot*powers[cut];
7029 #else
7030 rem=quot%powers[cut];
7031 quot=quot/powers[cut];
7032 #endif
7033 *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7034 count-=cut;
7035 if (count<=0) break;
7036 } /* shift-copy loop */
7037 } /* shift to least */
7038 } /* not unit boundary */
7039
7040 if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7041 return;
7042 } /* decSetCoeff */
7043
7044/* ------------------------------------------------------------------ */
7045/* decApplyRound -- apply pending rounding to a number */
7046/* */
7047/* dn is the number, with space for set->digits digits */
7048/* set is the context [for size and rounding mode] */
7049/* residue indicates pending rounding, being any accumulated */
7050/* guard and sticky information. It may be: */
7051/* 6-9: rounding digit is >5 */
7052/* 5: rounding digit is exactly half-way */
7053/* 1-4: rounding digit is <5 and >0 */
7054/* 0: the coefficient is exact */
7055/* -1: as 1, but the hidden digits are subtractive, that */
7056/* is, of the opposite sign to dn. In this case the */
7057/* coefficient must be non-0. This case occurs when */
7058/* subtracting a small number (which can be reduced to */
7059/* a sticky bit); see decAddOp. */
7060/* status is the status accumulator, as usual */
7061/* */
7062/* This routine applies rounding while keeping the length of the */
7063/* coefficient constant. The exponent and status are unchanged */
7064/* except if: */
7065/* */
7066/* -- the coefficient was increased and is all nines (in which */
7067/* case Overflow could occur, and is handled directly here so */
7068/* the caller does not need to re-test for overflow) */
7069/* */
7070/* -- the coefficient was decreased and becomes all nines (in which */
7071/* case Underflow could occur, and is also handled directly). */
7072/* */
7073/* All fields in dn are updated as required. */
7074/* */
7075/* ------------------------------------------------------------------ */
7076static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7077 uInt *status) {
7078 Int bump; /* 1 if coefficient needs to be incremented */
7079 /* -1 if coefficient needs to be decremented */
7080
7081 if (residue==0) return; /* nothing to apply */
7082
7083 bump=0; /* assume a smooth ride */
7084
7085 /* now decide whether, and how, to round, depending on mode */
7086 switch (set->round) {
7087 case DEC_ROUND_05UP: { /* round zero or five up (for reround) */
7088 /* This is the same as DEC_ROUND_DOWN unless there is a */
7089 /* positive residue and the lsd of dn is 0 or 5, in which case */
7090 /* it is bumped; when residue is <0, the number is therefore */
7091 /* bumped down unless the final digit was 1 or 6 (in which */
7092 /* case it is bumped down and then up -- a no-op) */
7093 Int lsd5=*dn->lsu%5; /* get lsd and quintate */
7094 if (residue<0 && lsd5!=1) bump=-1;
7095 else if (residue>0 && lsd5==0) bump=1;
7096 /* [bump==1 could be applied directly; use common path for clarity] */
7097 break;} /* r-05 */
7098
7099 case DEC_ROUND_DOWN: {
7100 /* no change, except if negative residue */
7101 if (residue<0) bump=-1;
7102 break;} /* r-d */
7103
7104 case DEC_ROUND_HALF_DOWN: {
7105 if (residue>5) bump=1;
7106 break;} /* r-h-d */
7107
7108 case DEC_ROUND_HALF_EVEN: {
7109 if (residue>5) bump=1; /* >0.5 goes up */
7110 else if (residue==5) { /* exactly 0.5000... */
7111 /* 0.5 goes up iff [new] lsd is odd */
7112 if (*dn->lsu & 0x01) bump=1;
7113 }
7114 break;} /* r-h-e */
7115
7116 case DEC_ROUND_HALF_UP: {
7117 if (residue>=5) bump=1;
7118 break;} /* r-h-u */
7119
7120 case DEC_ROUND_UP: {
7121 if (residue>0) bump=1;
7122 break;} /* r-u */
7123
7124 case DEC_ROUND_CEILING: {
7125 /* same as _UP for positive numbers, and as _DOWN for negatives */
7126 /* [negative residue cannot occur on 0] */
7127 if (decNumberIsNegative(dn)) {
7128 if (residue<0) bump=-1;
7129 }
7130 else {
7131 if (residue>0) bump=1;
7132 }
7133 break;} /* r-c */
7134
7135 case DEC_ROUND_FLOOR: {
7136 /* same as _UP for negative numbers, and as _DOWN for positive */
7137 /* [negative residue cannot occur on 0] */
7138 if (!decNumberIsNegative(dn)) {
7139 if (residue<0) bump=-1;
7140 }
7141 else {
7142 if (residue>0) bump=1;
7143 }
7144 break;} /* r-f */
7145
7146 default: { /* e.g., DEC_ROUND_MAX */
7147 *status|=DEC_Invalid_context;
7148 #if DECTRACE || (DECCHECK && DECVERB)
7149 printf("Unknown rounding mode: %d\n", set->round);
7150 #endif
7151 break;}
7152 } /* switch */
7153
7154 /* now bump the number, up or down, if need be */
7155 if (bump==0) return; /* no action required */
7156
7157 /* Simply use decUnitAddSub unless bumping up and the number is */
7158 /* all nines. In this special case set to 100... explicitly */
7159 /* and adjust the exponent by one (as otherwise could overflow */
7160 /* the array) */
7161 /* Similarly handle all-nines result if bumping down. */
7162 if (bump>0) {
7163 Unit *up; /* work */
7164 uInt count=dn->digits; /* digits to be checked */
7165 for (up=dn->lsu; ; up++) {
7166 if (count<=DECDPUN) {
7167 /* this is the last Unit (the msu) */
7168 if (*up!=powers[count]-1) break; /* not still 9s */
7169 /* here if it, too, is all nines */
7170 *up=(Unit)powers[count-1]; /* here 999 -> 100 etc. */
7171 for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7172 dn->exponent++; /* and bump exponent */
7173 /* [which, very rarely, could cause Overflow...] */
7174 if ((dn->exponent+dn->digits)>set->emax+1) {
7175 decSetOverflow(dn, set, status);
7176 }
7177 return; /* done */
7178 }
7179 /* a full unit to check, with more to come */
7180 if (*up!=DECDPUNMAX) break; /* not still 9s */
7181 count-=DECDPUN;
7182 } /* up */
7183 } /* bump>0 */
7184 else { /* -1 */
7185 /* here checking for a pre-bump of 1000... (leading 1, all */
7186 /* other digits zero) */
7187 Unit *up, *sup; /* work */
7188 uInt count=dn->digits; /* digits to be checked */
7189 for (up=dn->lsu; ; up++) {
7190 if (count<=DECDPUN) {
7191 /* this is the last Unit (the msu) */
7192 if (*up!=powers[count-1]) break; /* not 100.. */
7193 /* here if have the 1000... case */
7194 sup=up; /* save msu pointer */
7195 *up=(Unit)powers[count]-1; /* here 100 in msu -> 999 */
7196 /* others all to all-nines, too */
7197 for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7198 dn->exponent--; /* and bump exponent */
7199
7200 /* iff the number was at the subnormal boundary (exponent=etiny) */
7201 /* then the exponent is now out of range, so it will in fact get */
7202 /* clamped to etiny and the final 9 dropped. */
7203 /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7204 /* dn->exponent, set->digits); */
7205 if (dn->exponent+1==set->emin-set->digits+1) {
7206 if (count==1 && dn->digits==1) *sup=0; /* here 9 -> 0[.9] */
7207 else {
7208 *sup=(Unit)powers[count-1]-1; /* here 999.. in msu -> 99.. */
7209 dn->digits--;
7210 }
7211 dn->exponent++;
7212 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7213 }
7214 return; /* done */
7215 }
7216
7217 /* a full unit to check, with more to come */
7218 if (*up!=0) break; /* not still 0s */
7219 count-=DECDPUN;
7220 } /* up */
7221
7222 } /* bump<0 */
7223
7224 /* Actual bump needed. Do it. */
7225 decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7226 } /* decApplyRound */
7227
7228#if DECSUBSET
7229/* ------------------------------------------------------------------ */
7230/* decFinish -- finish processing a number */
7231/* */
7232/* dn is the number */
7233/* set is the context */
7234/* residue is the rounding accumulator (as in decApplyRound) */
7235/* status is the accumulator */
7236/* */
7237/* This finishes off the current number by: */
7238/* 1. If not extended: */
7239/* a. Converting a zero result to clean '0' */
7240/* b. Reducing positive exponents to 0, if would fit in digits */
7241/* 2. Checking for overflow and subnormals (always) */
7242/* Note this is just Finalize when no subset arithmetic. */
7243/* All fields are updated as required. */
7244/* ------------------------------------------------------------------ */
7245static void decFinish(decNumber *dn, decContext *set, Int *residue,
7246 uInt *status) {
7247 if (!set->extended) {
7248 if ISZERO(dn) { /* value is zero */
7249 dn->exponent=0; /* clean exponent .. */
7250 dn->bits=0; /* .. and sign */
7251 return; /* no error possible */
7252 }
7253 if (dn->exponent>=0) { /* non-negative exponent */
7254 /* >0; reduce to integer if possible */
7255 if (set->digits >= (dn->exponent+dn->digits)) {
7256 dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7257 dn->exponent=0;
7258 }
7259 }
7260 } /* !extended */
7261
7262 decFinalize(dn, set, residue, status);
7263 } /* decFinish */
7264#endif
7265
7266/* ------------------------------------------------------------------ */
7267/* decFinalize -- final check, clamp, and round of a number */
7268/* */
7269/* dn is the number */
7270/* set is the context */
7271/* residue is the rounding accumulator (as in decApplyRound) */
7272/* status is the status accumulator */
7273/* */
7274/* This finishes off the current number by checking for subnormal */
7275/* results, applying any pending rounding, checking for overflow, */
7276/* and applying any clamping. */
7277/* Underflow and overflow conditions are raised as appropriate. */
7278/* All fields are updated as required. */
7279/* ------------------------------------------------------------------ */
7280static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7281 uInt *status) {
7282 Int shift; /* shift needed if clamping */
7283 Int tinyexp=set->emin-dn->digits+1; /* precalculate subnormal boundary */
7284
7285 /* Must be careful, here, when checking the exponent as the */
7286 /* adjusted exponent could overflow 31 bits [because it may already */
7287 /* be up to twice the expected]. */
7288
7289 /* First test for subnormal. This must be done before any final */
7290 /* round as the result could be rounded to Nmin or 0. */
7291 if (dn->exponent<=tinyexp) { /* prefilter */
7292 Int comp;
7293 decNumber nmin;
7294 /* A very nasty case here is dn == Nmin and residue<0 */
7295 if (dn->exponent<tinyexp) {
7296 /* Go handle subnormals; this will apply round if needed. */
7297 decSetSubnormal(dn, set, residue, status);
7298 return;
7299 }
7300 /* Equals case: only subnormal if dn=Nmin and negative residue */
7301 decNumberZero(&nmin);
7302 nmin.lsu[0]=1;
7303 nmin.exponent=set->emin;
7304 comp=decCompare(dn, &nmin, 1); /* (signless compare) */
7305 if (comp==BADINT) { /* oops */
7306 *status|=DEC_Insufficient_storage; /* abandon... */
7307 return;
7308 }
7309 if (*residue<0 && comp==0) { /* neg residue and dn==Nmin */
7310 decApplyRound(dn, set, *residue, status); /* might force down */
7311 decSetSubnormal(dn, set, residue, status);
7312 return;
7313 }
7314 }
7315
7316 /* now apply any pending round (this could raise overflow). */
7317 if (*residue!=0) decApplyRound(dn, set, *residue, status);
7318
7319 /* Check for overflow [redundant in the 'rare' case] or clamp */
7320 if (dn->exponent<=set->emax-set->digits+1) return; /* neither needed */
7321
7322
7323 /* here when might have an overflow or clamp to do */
7324 if (dn->exponent>set->emax-dn->digits+1) { /* too big */
7325 decSetOverflow(dn, set, status);
7326 return;
7327 }
7328 /* here when the result is normal but in clamp range */
7329 if (!set->clamp) return;
7330
7331 /* here when need to apply the IEEE exponent clamp (fold-down) */
7332 shift=dn->exponent-(set->emax-set->digits+1);
7333
7334 /* shift coefficient (if non-zero) */
7335 if (!ISZERO(dn)) {
7336 dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7337 }
7338 dn->exponent-=shift; /* adjust the exponent to match */
7339 *status|=DEC_Clamped; /* and record the dirty deed */
7340 return;
7341 } /* decFinalize */
7342
7343/* ------------------------------------------------------------------ */
7344/* decSetOverflow -- set number to proper overflow value */
7345/* */
7346/* dn is the number (used for sign [only] and result) */
7347/* set is the context [used for the rounding mode, etc.] */
7348/* status contains the current status to be updated */
7349/* */
7350/* This sets the sign of a number and sets its value to either */
7351/* Infinity or the maximum finite value, depending on the sign of */
7352/* dn and the rounding mode, following IEEE 854 rules. */
7353/* ------------------------------------------------------------------ */
7354static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7355 Flag needmax=0; /* result is maximum finite value */
7356 uByte sign=dn->bits&DECNEG; /* clean and save sign bit */
7357
7358 if (ISZERO(dn)) { /* zero does not overflow magnitude */
7359 Int emax=set->emax; /* limit value */
7360 if (set->clamp) emax-=set->digits-1; /* lower if clamping */
7361 if (dn->exponent>emax) { /* clamp required */
7362 dn->exponent=emax;
7363 *status|=DEC_Clamped;
7364 }
7365 return;
7366 }
7367
7368 decNumberZero(dn);
7369 switch (set->round) {
7370 case DEC_ROUND_DOWN: {
7371 needmax=1; /* never Infinity */
7372 break;} /* r-d */
7373 case DEC_ROUND_05UP: {
7374 needmax=1; /* never Infinity */
7375 break;} /* r-05 */
7376 case DEC_ROUND_CEILING: {
7377 if (sign) needmax=1; /* Infinity if non-negative */
7378 break;} /* r-c */
7379 case DEC_ROUND_FLOOR: {
7380 if (!sign) needmax=1; /* Infinity if negative */
7381 break;} /* r-f */
7382 default: break; /* Infinity in all other cases */
7383 }
7384 if (needmax) {
7385 decSetMaxValue(dn, set);
7386 dn->bits=sign; /* set sign */
7387 }
7388 else dn->bits=sign|DECINF; /* Value is +/-Infinity */
7389 *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7390 } /* decSetOverflow */
7391
7392/* ------------------------------------------------------------------ */
7393/* decSetMaxValue -- set number to +Nmax (maximum normal value) */
7394/* */
7395/* dn is the number to set */
7396/* set is the context [used for digits and emax] */
7397/* */
7398/* This sets the number to the maximum positive value. */
7399/* ------------------------------------------------------------------ */
7400static void decSetMaxValue(decNumber *dn, decContext *set) {
7401 Unit *up; /* work */
7402 Int count=set->digits; /* nines to add */
7403 dn->digits=count;
7404 /* fill in all nines to set maximum value */
7405 for (up=dn->lsu; ; up++) {
7406 if (count>DECDPUN) *up=DECDPUNMAX; /* unit full o'nines */
7407 else { /* this is the msu */
7408 *up=(Unit)(powers[count]-1);
7409 break;
7410 }
7411 count-=DECDPUN; /* filled those digits */
7412 } /* up */
7413 dn->bits=0; /* + sign */
7414 dn->exponent=set->emax-set->digits+1;
7415 } /* decSetMaxValue */
7416
7417/* ------------------------------------------------------------------ */
7418/* decSetSubnormal -- process value whose exponent is <Emin */
7419/* */
7420/* dn is the number (used as input as well as output; it may have */
7421/* an allowed subnormal value, which may need to be rounded) */
7422/* set is the context [used for the rounding mode] */
7423/* residue is any pending residue */
7424/* status contains the current status to be updated */
7425/* */
7426/* If subset mode, set result to zero and set Underflow flags. */
7427/* */
7428/* Value may be zero with a low exponent; this does not set Subnormal */
7429/* but the exponent will be clamped to Etiny. */
7430/* */
7431/* Otherwise ensure exponent is not out of range, and round as */
7432/* necessary. Underflow is set if the result is Inexact. */
7433/* ------------------------------------------------------------------ */
7434static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7435 uInt *status) {
72ac97cd
TM
7436 decContext workset; /* work */
7437 Int etiny, adjust; /* .. */
7438
7439 #if DECSUBSET
7440 /* simple set to zero and 'hard underflow' for subset */
7441 if (!set->extended) {
7442 decNumberZero(dn);
7443 /* always full overflow */
7444 *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7445 return;
7446 }
7447 #endif
7448
7449 /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7450 /* (Etiny) if needed */
7451 etiny=set->emin-(set->digits-1); /* smallest allowed exponent */
7452
7453 if ISZERO(dn) { /* value is zero */
7454 /* residue can never be non-zero here */
7455 #if DECCHECK
7456 if (*residue!=0) {
7457 printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7458 *status|=DEC_Invalid_operation;
7459 }
7460 #endif
7461 if (dn->exponent<etiny) { /* clamp required */
7462 dn->exponent=etiny;
7463 *status|=DEC_Clamped;
7464 }
7465 return;
7466 }
7467
7468 *status|=DEC_Subnormal; /* have a non-zero subnormal */
7469 adjust=etiny-dn->exponent; /* calculate digits to remove */
7470 if (adjust<=0) { /* not out of range; unrounded */
7471 /* residue can never be non-zero here, except in the Nmin-residue */
7472 /* case (which is a subnormal result), so can take fast-path here */
7473 /* it may already be inexact (from setting the coefficient) */
7474 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7475 return;
7476 }
7477
7478 /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7479 /* [this code is similar to that in rescale] */
72ac97cd
TM
7480 workset=*set; /* clone rounding, etc. */
7481 workset.digits=dn->digits-adjust; /* set requested length */
7482 workset.emin-=adjust; /* and adjust emin to match */
7483 /* [note that the latter can be <1, here, similar to Rescale case] */
7484 decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7485 decApplyRound(dn, &workset, *residue, status);
7486
7487 /* Use 754R/854 default rule: Underflow is set iff Inexact */
7488 /* [independent of whether trapped] */
7489 if (*status&DEC_Inexact) *status|=DEC_Underflow;
7490
7491 /* if rounded up a 999s case, exponent will be off by one; adjust */
7492 /* back if so [it will fit, because it was shortened earlier] */
7493 if (dn->exponent>etiny) {
7494 dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7495 dn->exponent--; /* (re)adjust the exponent. */
7496 }
7497
7498 /* if rounded to zero, it is by definition clamped... */
7499 if (ISZERO(dn)) *status|=DEC_Clamped;
7500 } /* decSetSubnormal */
7501
7502/* ------------------------------------------------------------------ */
7503/* decCheckMath - check entry conditions for a math function */
7504/* */
7505/* This checks the context and the operand */
7506/* */
7507/* rhs is the operand to check */
7508/* set is the context to check */
7509/* status is unchanged if both are good */
7510/* */
7511/* returns non-zero if status is changed, 0 otherwise */
7512/* */
7513/* Restrictions enforced: */
7514/* */
7515/* digits, emax, and -emin in the context must be less than */
7516/* DEC_MAX_MATH (999999), and A must be within these bounds if */
7517/* non-zero. Invalid_operation is set in the status if a */
7518/* restriction is violated. */
7519/* ------------------------------------------------------------------ */
7520static uInt decCheckMath(const decNumber *rhs, decContext *set,
7521 uInt *status) {
7522 uInt save=*status; /* record */
7523 if (set->digits>DEC_MAX_MATH
7524 || set->emax>DEC_MAX_MATH
7525 || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7526 else if ((rhs->digits>DEC_MAX_MATH
7527 || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7528 || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7529 && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7530 return (*status!=save);
7531 } /* decCheckMath */
7532
7533/* ------------------------------------------------------------------ */
7534/* decGetInt -- get integer from a number */
7535/* */
7536/* dn is the number [which will not be altered] */
7537/* */
7538/* returns one of: */
7539/* BADINT if there is a non-zero fraction */
7540/* the converted integer */
7541/* BIGEVEN if the integer is even and magnitude > 2*10**9 */
7542/* BIGODD if the integer is odd and magnitude > 2*10**9 */
7543/* */
7544/* This checks and gets a whole number from the input decNumber. */
7545/* The sign can be determined from dn by the caller when BIGEVEN or */
7546/* BIGODD is returned. */
7547/* ------------------------------------------------------------------ */
7548static Int decGetInt(const decNumber *dn) {
7549 Int theInt; /* result accumulator */
7550 const Unit *up; /* work */
7551 Int got; /* digits (real or not) processed */
7552 Int ilength=dn->digits+dn->exponent; /* integral length */
7553 Flag neg=decNumberIsNegative(dn); /* 1 if -ve */
7554
7555 /* The number must be an integer that fits in 10 digits */
7556 /* Assert, here, that 10 is enough for any rescale Etiny */
7557 #if DEC_MAX_EMAX > 999999999
7558 #error GetInt may need updating [for Emax]
7559 #endif
7560 #if DEC_MIN_EMIN < -999999999
7561 #error GetInt may need updating [for Emin]
7562 #endif
7563 if (ISZERO(dn)) return 0; /* zeros are OK, with any exponent */
7564
7565 up=dn->lsu; /* ready for lsu */
7566 theInt=0; /* ready to accumulate */
7567 if (dn->exponent>=0) { /* relatively easy */
7568 /* no fractional part [usual]; allow for positive exponent */
7569 got=dn->exponent;
7570 }
7571 else { /* -ve exponent; some fractional part to check and discard */
7572 Int count=-dn->exponent; /* digits to discard */
7573 /* spin up whole units until reach the Unit with the unit digit */
7574 for (; count>=DECDPUN; up++) {
7575 if (*up!=0) return BADINT; /* non-zero Unit to discard */
7576 count-=DECDPUN;
7577 }
7578 if (count==0) got=0; /* [a multiple of DECDPUN] */
7579 else { /* [not multiple of DECDPUN] */
7580 Int rem; /* work */
7581 /* slice off fraction digits and check for non-zero */
7582 #if DECDPUN<=4
7583 theInt=QUOT10(*up, count);
7584 rem=*up-theInt*powers[count];
7585 #else
7586 rem=*up%powers[count]; /* slice off discards */
7587 theInt=*up/powers[count];
7588 #endif
7589 if (rem!=0) return BADINT; /* non-zero fraction */
7590 /* it looks good */
7591 got=DECDPUN-count; /* number of digits so far */
7592 up++; /* ready for next */
7593 }
7594 }
7595 /* now it's known there's no fractional part */
7596
7597 /* tricky code now, to accumulate up to 9.3 digits */
7598 if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7599
7600 if (ilength<11) {
7601 Int save=theInt;
7602 /* collect any remaining unit(s) */
7603 for (; got<ilength; up++) {
7604 theInt+=*up*powers[got];
7605 got+=DECDPUN;
7606 }
7607 if (ilength==10) { /* need to check for wrap */
7608 if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7609 /* [that test also disallows the BADINT result case] */
7610 else if (neg && theInt>1999999997) ilength=11;
7611 else if (!neg && theInt>999999999) ilength=11;
7612 if (ilength==11) theInt=save; /* restore correct low bit */
7613 }
7614 }
7615
7616 if (ilength>10) { /* too big */
7617 if (theInt&1) return BIGODD; /* bottom bit 1 */
7618 return BIGEVEN; /* bottom bit 0 */
7619 }
7620
7621 if (neg) theInt=-theInt; /* apply sign */
7622 return theInt;
7623 } /* decGetInt */
7624
7625/* ------------------------------------------------------------------ */
7626/* decDecap -- decapitate the coefficient of a number */
7627/* */
7628/* dn is the number to be decapitated */
7629/* drop is the number of digits to be removed from the left of dn; */
7630/* this must be <= dn->digits (if equal, the coefficient is */
7631/* set to 0) */
7632/* */
7633/* Returns dn; dn->digits will be <= the initial digits less drop */
7634/* (after removing drop digits there may be leading zero digits */
7635/* which will also be removed). Only dn->lsu and dn->digits change. */
7636/* ------------------------------------------------------------------ */
7637static decNumber *decDecap(decNumber *dn, Int drop) {
7638 Unit *msu; /* -> target cut point */
7639 Int cut; /* work */
7640 if (drop>=dn->digits) { /* losing the whole thing */
7641 #if DECCHECK
7642 if (drop>dn->digits)
7643 printf("decDecap called with drop>digits [%ld>%ld]\n",
7644 (LI)drop, (LI)dn->digits);
7645 #endif
7646 dn->lsu[0]=0;
7647 dn->digits=1;
7648 return dn;
7649 }
7650 msu=dn->lsu+D2U(dn->digits-drop)-1; /* -> likely msu */
7651 cut=MSUDIGITS(dn->digits-drop); /* digits to be in use in msu */
7652 if (cut!=DECDPUN) *msu%=powers[cut]; /* clear left digits */
7653 /* that may have left leading zero digits, so do a proper count... */
7654 dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7655 return dn;
7656 } /* decDecap */
7657
7658/* ------------------------------------------------------------------ */
7659/* decBiStr -- compare string with pairwise options */
7660/* */
7661/* targ is the string to compare */
7662/* str1 is one of the strings to compare against (length may be 0) */
7663/* str2 is the other; it must be the same length as str1 */
7664/* */
7665/* returns 1 if strings compare equal, (that is, it is the same */
7666/* length as str1 and str2, and each character of targ is in either */
7667/* str1 or str2 in the corresponding position), or 0 otherwise */
7668/* */
7669/* This is used for generic caseless compare, including the awkward */
7670/* case of the Turkish dotted and dotless Is. Use as (for example): */
7671/* if (decBiStr(test, "mike", "MIKE")) ... */
7672/* ------------------------------------------------------------------ */
7673static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7674 for (;;targ++, str1++, str2++) {
7675 if (*targ!=*str1 && *targ!=*str2) return 0;
7676 /* *targ has a match in one (or both, if terminator) */
7677 if (*targ=='\0') break;
7678 } /* forever */
7679 return 1;
7680 } /* decBiStr */
7681
7682/* ------------------------------------------------------------------ */
7683/* decNaNs -- handle NaN operand or operands */
7684/* */
7685/* res is the result number */
7686/* lhs is the first operand */
7687/* rhs is the second operand, or NULL if none */
7688/* context is used to limit payload length */
7689/* status contains the current status */
7690/* returns res in case convenient */
7691/* */
7692/* Called when one or both operands is a NaN, and propagates the */
7693/* appropriate result to res. When an sNaN is found, it is changed */
7694/* to a qNaN and Invalid operation is set. */
7695/* ------------------------------------------------------------------ */
7696static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7697 const decNumber *rhs, decContext *set,
7698 uInt *status) {
7699 /* This decision tree ends up with LHS being the source pointer, */
7700 /* and status updated if need be */
7701 if (lhs->bits & DECSNAN)
7702 *status|=DEC_Invalid_operation | DEC_sNaN;
7703 else if (rhs==NULL);
7704 else if (rhs->bits & DECSNAN) {
7705 lhs=rhs;
7706 *status|=DEC_Invalid_operation | DEC_sNaN;
7707 }
7708 else if (lhs->bits & DECNAN);
7709 else lhs=rhs;
7710
7711 /* propagate the payload */
7712 if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */
7713 else { /* too long */
7714 const Unit *ul;
7715 Unit *ur, *uresp1;
7716 /* copy safe number of units, then decapitate */
7717 res->bits=lhs->bits; /* need sign etc. */
7718 uresp1=res->lsu+D2U(set->digits);
7719 for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7720 res->digits=D2U(set->digits)*DECDPUN;
7721 /* maybe still too long */
7722 if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7723 }
7724
7725 res->bits&=~DECSNAN; /* convert any sNaN to NaN, while */
7726 res->bits|=DECNAN; /* .. preserving sign */
7727 res->exponent=0; /* clean exponent */
7728 /* [coefficient was copied/decapitated] */
7729 return res;
7730 } /* decNaNs */
7731
7732/* ------------------------------------------------------------------ */
7733/* decStatus -- apply non-zero status */
7734/* */
7735/* dn is the number to set if error */
7736/* status contains the current status (not yet in context) */
7737/* set is the context */
7738/* */
7739/* If the status is an error status, the number is set to a NaN, */
7740/* unless the error was an overflow, divide-by-zero, or underflow, */
7741/* in which case the number will have already been set. */
7742/* */
7743/* The context status is then updated with the new status. Note that */
7744/* this may raise a signal, so control may never return from this */
7745/* routine (hence resources must be recovered before it is called). */
7746/* ------------------------------------------------------------------ */
7747static void decStatus(decNumber *dn, uInt status, decContext *set) {
7748 if (status & DEC_NaNs) { /* error status -> NaN */
7749 /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7750 if (status & DEC_sNaN) status&=~DEC_sNaN;
7751 else {
7752 decNumberZero(dn); /* other error: clean throughout */
7753 dn->bits=DECNAN; /* and make a quiet NaN */
7754 }
7755 }
7756 decContextSetStatus(set, status); /* [may not return] */
7757 return;
7758 } /* decStatus */
7759
7760/* ------------------------------------------------------------------ */
7761/* decGetDigits -- count digits in a Units array */
7762/* */
7763/* uar is the Unit array holding the number (this is often an */
7764/* accumulator of some sort) */
7765/* len is the length of the array in units [>=1] */
7766/* */
7767/* returns the number of (significant) digits in the array */
7768/* */
7769/* All leading zeros are excluded, except the last if the array has */
7770/* only zero Units. */
7771/* ------------------------------------------------------------------ */
7772/* This may be called twice during some operations. */
7773static Int decGetDigits(Unit *uar, Int len) {
7774 Unit *up=uar+(len-1); /* -> msu */
7775 Int digits=(len-1)*DECDPUN+1; /* possible digits excluding msu */
7776 #if DECDPUN>4
7777 uInt const *pow; /* work */
7778 #endif
7779 /* (at least 1 in final msu) */
7780 #if DECCHECK
7781 if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7782 #endif
7783
7784 for (; up>=uar; up--) {
7785 if (*up==0) { /* unit is all 0s */
7786 if (digits==1) break; /* a zero has one digit */
7787 digits-=DECDPUN; /* adjust for 0 unit */
7788 continue;}
7789 /* found the first (most significant) non-zero Unit */
7790 #if DECDPUN>1 /* not done yet */
7791 if (*up<10) break; /* is 1-9 */
7792 digits++;
7793 #if DECDPUN>2 /* not done yet */
7794 if (*up<100) break; /* is 10-99 */
7795 digits++;
7796 #if DECDPUN>3 /* not done yet */
7797 if (*up<1000) break; /* is 100-999 */
7798 digits++;
7799 #if DECDPUN>4 /* count the rest ... */
7800 for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7801 #endif
7802 #endif
7803 #endif
7804 #endif
7805 break;
7806 } /* up */
7807 return digits;
7808 } /* decGetDigits */
7809
7810#if DECTRACE | DECCHECK
7811/* ------------------------------------------------------------------ */
7812/* decNumberShow -- display a number [debug aid] */
7813/* dn is the number to show */
7814/* */
7815/* Shows: sign, exponent, coefficient (msu first), digits */
7816/* or: sign, special-value */
7817/* ------------------------------------------------------------------ */
7818/* this is public so other modules can use it */
7819void decNumberShow(const decNumber *dn) {
7820 const Unit *up; /* work */
7821 uInt u, d; /* .. */
7822 Int cut; /* .. */
7823 char isign='+'; /* main sign */
7824 if (dn==NULL) {
7825 printf("NULL\n");
7826 return;}
7827 if (decNumberIsNegative(dn)) isign='-';
7828 printf(" >> %c ", isign);
7829 if (dn->bits&DECSPECIAL) { /* Is a special value */
7830 if (decNumberIsInfinite(dn)) printf("Infinity");
7831 else { /* a NaN */
7832 if (dn->bits&DECSNAN) printf("sNaN"); /* signalling NaN */
7833 else printf("NaN");
7834 }
7835 /* if coefficient and exponent are 0, no more to do */
7836 if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7837 printf("\n");
7838 return;}
7839 /* drop through to report other information */
7840 printf(" ");
7841 }
7842
7843 /* now carefully display the coefficient */
7844 up=dn->lsu+D2U(dn->digits)-1; /* msu */
7845 printf("%ld", (LI)*up);
7846 for (up=up-1; up>=dn->lsu; up--) {
7847 u=*up;
7848 printf(":");
7849 for (cut=DECDPUN-1; cut>=0; cut--) {
7850 d=u/powers[cut];
7851 u-=d*powers[cut];
7852 printf("%ld", (LI)d);
7853 } /* cut */
7854 } /* up */
7855 if (dn->exponent!=0) {
7856 char esign='+';
7857 if (dn->exponent<0) esign='-';
7858 printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7859 }
7860 printf(" [%ld]\n", (LI)dn->digits);
7861 } /* decNumberShow */
7862#endif
7863
7864#if DECTRACE || DECCHECK
7865/* ------------------------------------------------------------------ */
7866/* decDumpAr -- display a unit array [debug/check aid] */
7867/* name is a single-character tag name */
7868/* ar is the array to display */
7869/* len is the length of the array in Units */
7870/* ------------------------------------------------------------------ */
7871static void decDumpAr(char name, const Unit *ar, Int len) {
7872 Int i;
7873 const char *spec;
7874 #if DECDPUN==9
7875 spec="%09d ";
7876 #elif DECDPUN==8
7877 spec="%08d ";
7878 #elif DECDPUN==7
7879 spec="%07d ";
7880 #elif DECDPUN==6
7881 spec="%06d ";
7882 #elif DECDPUN==5
7883 spec="%05d ";
7884 #elif DECDPUN==4
7885 spec="%04d ";
7886 #elif DECDPUN==3
7887 spec="%03d ";
7888 #elif DECDPUN==2
7889 spec="%02d ";
7890 #else
7891 spec="%d ";
7892 #endif
7893 printf(" :%c: ", name);
7894 for (i=len-1; i>=0; i--) {
7895 if (i==len-1) printf("%ld ", (LI)ar[i]);
7896 else printf(spec, ar[i]);
7897 }
7898 printf("\n");
7899 return;}
7900#endif
7901
7902#if DECCHECK
7903/* ------------------------------------------------------------------ */
7904/* decCheckOperands -- check operand(s) to a routine */
7905/* res is the result structure (not checked; it will be set to */
7906/* quiet NaN if error found (and it is not NULL)) */
7907/* lhs is the first operand (may be DECUNRESU) */
7908/* rhs is the second (may be DECUNUSED) */
7909/* set is the context (may be DECUNCONT) */
7910/* returns 0 if both operands, and the context are clean, or 1 */
7911/* otherwise (in which case the context will show an error, */
7912/* unless NULL). Note that res is not cleaned; caller should */
7913/* handle this so res=NULL case is safe. */
7914/* The caller is expected to abandon immediately if 1 is returned. */
7915/* ------------------------------------------------------------------ */
7916static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7917 const decNumber *rhs, decContext *set) {
7918 Flag bad=0;
7919 if (set==NULL) { /* oops; hopeless */
7920 #if DECTRACE || DECVERB
7921 printf("Reference to context is NULL.\n");
7922 #endif
7923 bad=1;
7924 return 1;}
7925 else if (set!=DECUNCONT
7926 && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7927 bad=1;
7928 #if DECTRACE || DECVERB
7929 printf("Bad context [digits=%ld round=%ld].\n",
7930 (LI)set->digits, (LI)set->round);
7931 #endif
7932 }
7933 else {
7934 if (res==NULL) {
7935 bad=1;
7936 #if DECTRACE
7937 /* this one not DECVERB as standard tests include NULL */
7938 printf("Reference to result is NULL.\n");
7939 #endif
7940 }
7941 if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7942 if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7943 }
7944 if (bad) {
7945 if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7946 if (res!=DECUNRESU && res!=NULL) {
7947 decNumberZero(res);
7948 res->bits=DECNAN; /* qNaN */
7949 }
7950 }
7951 return bad;
7952 } /* decCheckOperands */
7953
7954/* ------------------------------------------------------------------ */
7955/* decCheckNumber -- check a number */
7956/* dn is the number to check */
7957/* returns 0 if the number is clean, or 1 otherwise */
7958/* */
7959/* The number is considered valid if it could be a result from some */
7960/* operation in some valid context. */
7961/* ------------------------------------------------------------------ */
7962static Flag decCheckNumber(const decNumber *dn) {
7963 const Unit *up; /* work */
7964 uInt maxuint; /* .. */
7965 Int ae, d, digits; /* .. */
7966 Int emin, emax; /* .. */
7967
7968 if (dn==NULL) { /* hopeless */
7969 #if DECTRACE
7970 /* this one not DECVERB as standard tests include NULL */
7971 printf("Reference to decNumber is NULL.\n");
7972 #endif
7973 return 1;}
7974
7975 /* check special values */
7976 if (dn->bits & DECSPECIAL) {
7977 if (dn->exponent!=0) {
7978 #if DECTRACE || DECVERB
7979 printf("Exponent %ld (not 0) for a special value [%02x].\n",
7980 (LI)dn->exponent, dn->bits);
7981 #endif
7982 return 1;}
7983
7984 /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
7985 if (decNumberIsInfinite(dn)) {
7986 if (dn->digits!=1) {
7987 #if DECTRACE || DECVERB
7988 printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7989 #endif
7990 return 1;}
7991 if (*dn->lsu!=0) {
7992 #if DECTRACE || DECVERB
7993 printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7994 #endif
7995 decDumpAr('I', dn->lsu, D2U(dn->digits));
7996 return 1;}
7997 } /* Inf */
7998 /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
7999 /* concrete formats (decimal64, etc.). */
8000 return 0;
8001 }
8002
8003 /* check the coefficient */
8004 if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8005 #if DECTRACE || DECVERB
8006 printf("Digits %ld in number.\n", (LI)dn->digits);
8007 #endif
8008 return 1;}
8009
8010 d=dn->digits;
8011
8012 for (up=dn->lsu; d>0; up++) {
8013 if (d>DECDPUN) maxuint=DECDPUNMAX;
8014 else { /* reached the msu */
8015 maxuint=powers[d]-1;
8016 if (dn->digits>1 && *up<powers[d-1]) {
8017 #if DECTRACE || DECVERB
8018 printf("Leading 0 in number.\n");
8019 decNumberShow(dn);
8020 #endif
8021 return 1;}
8022 }
8023 if (*up>maxuint) {
8024 #if DECTRACE || DECVERB
8025 printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8026 (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8027 #endif
8028 return 1;}
8029 d-=DECDPUN;
8030 }
8031
8032 /* check the exponent. Note that input operands can have exponents */
8033 /* which are out of the set->emin/set->emax and set->digits range */
8034 /* (just as they can have more digits than set->digits). */
8035 ae=dn->exponent+dn->digits-1; /* adjusted exponent */
8036 emax=DECNUMMAXE;
8037 emin=DECNUMMINE;
8038 digits=DECNUMMAXP;
8039 if (ae<emin-(digits-1)) {
8040 #if DECTRACE || DECVERB
8041 printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8042 decNumberShow(dn);
8043 #endif
8044 return 1;}
8045 if (ae>+emax) {
8046 #if DECTRACE || DECVERB
8047 printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8048 decNumberShow(dn);
8049 #endif
8050 return 1;}
8051
8052 return 0; /* it's OK */
8053 } /* decCheckNumber */
8054
8055/* ------------------------------------------------------------------ */
8056/* decCheckInexact -- check a normal finite inexact result has digits */
8057/* dn is the number to check */
8058/* set is the context (for status and precision) */
8059/* sets Invalid operation, etc., if some digits are missing */
8060/* [this check is not made for DECSUBSET compilation or when */
8061/* subnormal is not set] */
8062/* ------------------------------------------------------------------ */
8063static void decCheckInexact(const decNumber *dn, decContext *set) {
8064 #if !DECSUBSET && DECEXTFLAG
8065 if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8066 && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8067 #if DECTRACE || DECVERB
8068 printf("Insufficient digits [%ld] on normal Inexact result.\n",
8069 (LI)dn->digits);
8070 decNumberShow(dn);
8071 #endif
8072 decContextSetStatus(set, DEC_Invalid_operation);
8073 }
8074 #else
8075 /* next is a noop for quiet compiler */
8076 if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8077 #endif
8078 return;
8079 } /* decCheckInexact */
8080#endif
8081
8082#if DECALLOC
8083#undef malloc
8084#undef free
8085/* ------------------------------------------------------------------ */
8086/* decMalloc -- accountable allocation routine */
8087/* n is the number of bytes to allocate */
8088/* */
8089/* Semantics is the same as the stdlib malloc routine, but bytes */
8090/* allocated are accounted for globally, and corruption fences are */
8091/* added before and after the 'actual' storage. */
8092/* ------------------------------------------------------------------ */
8093/* This routine allocates storage with an extra twelve bytes; 8 are */
8094/* at the start and hold: */
8095/* 0-3 the original length requested */
8096/* 4-7 buffer corruption detection fence (DECFENCE, x4) */
8097/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8098/* ------------------------------------------------------------------ */
8099static void *decMalloc(size_t n) {
8100 uInt size=n+12; /* true size */
8101 void *alloc; /* -> allocated storage */
8102 uInt *j; /* work */
8103 uByte *b, *b0; /* .. */
8104
8105 alloc=malloc(size); /* -> allocated storage */
8106 if (alloc==NULL) return NULL; /* out of strorage */
8107 b0=(uByte *)alloc; /* as bytes */
8108 decAllocBytes+=n; /* account for storage */
8109 j=(uInt *)alloc; /* -> first four bytes */
8110 *j=n; /* save n */
8111 /* printf(" alloc ++ dAB: %ld (%d)\n", decAllocBytes, n); */
8112 for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8113 for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8114 return b0+8; /* -> play area */
8115 } /* decMalloc */
8116
8117/* ------------------------------------------------------------------ */
8118/* decFree -- accountable free routine */
8119/* alloc is the storage to free */
8120/* */
8121/* Semantics is the same as the stdlib malloc routine, except that */
8122/* the global storage accounting is updated and the fences are */
8123/* checked to ensure that no routine has written 'out of bounds'. */
8124/* ------------------------------------------------------------------ */
8125/* This routine first checks that the fences have not been corrupted. */
8126/* It then frees the storage using the 'truw' storage address (that */
8127/* is, offset by 8). */
8128/* ------------------------------------------------------------------ */
8129static void decFree(void *alloc) {
8130 uInt *j, n; /* pointer, original length */
8131 uByte *b, *b0; /* work */
8132
8133 if (alloc==NULL) return; /* allowed; it's a nop */
8134 b0=(uByte *)alloc; /* as bytes */
8135 b0-=8; /* -> true start of storage */
8136 j=(uInt *)b0; /* -> first four bytes */
8137 n=*j; /* lift */
8138 for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8139 printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8140 b-b0-8, (Int)b0);
8141 for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8142 printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8143 b-b0-8, (Int)b0, n);
8144 free(b0); /* drop the storage */
8145 decAllocBytes-=n; /* account for storage */
8146 /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8147 } /* decFree */
8148#define malloc(a) decMalloc(a)
8149#define free(a) decFree(a)
8150#endif