decNumber.c
This file
Path
vendor/decNumber/decNumber.c
8,143 lines · 388.0 KiB · C
Last changed by
Not known.
History of this fileTake it
1/* ------------------------------------------------------------------ */
2/* Decimal Number arithmetic module */
3/* ------------------------------------------------------------------ */
4/* Copyright (c) IBM Corporation, 2000, 2009. All rights reserved. */
5/* */
6/* This software is made available under the terms of the */
7/* ICU License -- ICU 1.8.1 and later. */
8/* */
9/* The description and User's Guide ("The decNumber C Library") for */
10/* this software is called decNumber.pdf. This document is */
11/* available, together with arithmetic and format specifications, */
12/* testcases, and Web links, on the General Decimal Arithmetic page. */
13/* */
14/* Please send comments, suggestions, and corrections to the author: */
15/* mfc@uk.ibm.com */
16/* Mike Cowlishaw, IBM Fellow */
17/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
18/* ------------------------------------------------------------------ */
19/* This module comprises the routines for arbitrary-precision General */
20/* Decimal Arithmetic as defined in the specification which may be */
21/* found on the General Decimal Arithmetic pages. It implements both */
22/* the full ('extended') arithmetic and the simpler ('subset') */
23/* arithmetic. */
24/* */
25/* Usage notes: */
26/* */
27/* 1. This code is ANSI C89 except: */
28/* */
29/* a) C99 line comments (double forward slash) are used. (Most C */
30/* compilers accept these. If yours does not, a simple script */
31/* can be used to convert them to ANSI C comments.) */
32/* */
33/* b) Types from C99 stdint.h are used. If you do not have this */
34/* header file, see the User's Guide section of the decNumber */
35/* documentation; this lists the necessary definitions. */
36/* */
37/* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
38/* uint64_t types may be used. To avoid these, set DECUSE64=0 */
39/* and DECDPUN<=4 (see documentation). */
40/* */
41/* The code also conforms to C99 restrictions; in particular, */
42/* strict aliasing rules are observed. */
43/* */
44/* 2. The decNumber format which this library uses is optimized for */
45/* efficient processing of relatively short numbers; in particular */
46/* it allows the use of fixed sized structures and minimizes copy */
47/* and move operations. It does, however, support arbitrary */
48/* precision (up to 999,999,999 digits) and arbitrary exponent */
49/* range (Emax in the range 0 through 999,999,999 and Emin in the */
50/* range -999,999,999 through 0). Mathematical functions (for */
51/* example decNumberExp) as identified below are restricted more */
52/* tightly: digits, emax, and -emin in the context must be <= */
53/* DEC_MAX_MATH (999999), and their operand(s) must be within */
54/* these bounds. */
55/* */
56/* 3. Logical functions are further restricted; their operands must */
57/* be finite, positive, have an exponent of zero, and all digits */
58/* must be either 0 or 1. The result will only contain digits */
59/* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
60/* */
61/* 4. Operands to operator functions are never modified unless they */
62/* are also specified to be the result number (which is always */
63/* permitted). Other than that case, operands must not overlap. */
64/* */
65/* 5. Error handling: the type of the error is ORed into the status */
66/* flags in the current context (decContext structure). The */
67/* SIGFPE signal is then raised if the corresponding trap-enabler */
68/* flag in the decContext is set (is 1). */
69/* */
70/* It is the responsibility of the caller to clear the status */
71/* flags as required. */
72/* */
73/* The result of any routine which returns a number will always */
74/* be a valid number (which may be a special value, such as an */
75/* Infinity or NaN). */
76/* */
77/* 6. The decNumber format is not an exchangeable concrete */
78/* representation as it comprises fields which may be machine- */
79/* dependent (packed or unpacked, or special length, for example). */
80/* Canonical conversions to and from strings are provided; other */
81/* conversions are available in separate modules. */
82/* */
83/* 7. Normally, input operands are assumed to be valid. Set DECCHECK */
84/* to 1 for extended operand checking (including NULL operands). */
85/* Results are undefined if a badly-formed structure (or a NULL */
86/* pointer to a structure) is provided, though with DECCHECK */
87/* enabled the operator routines are protected against exceptions. */
88/* (Except if the result pointer is NULL, which is unrecoverable.) */
89/* */
90/* However, the routines will never cause exceptions if they are */
91/* given well-formed operands, even if the value of the operands */
92/* is inappropriate for the operation and DECCHECK is not set. */
93/* (Except for SIGFPE, as and where documented.) */
94/* */
95/* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */
96/* ------------------------------------------------------------------ */
97/* Implementation notes for maintenance of this module: */
98/* */
99/* 1. Storage leak protection: Routines which use malloc are not */
100/* permitted to use return for fastpath or error exits (i.e., */
101/* they follow strict structured programming conventions). */
102/* Instead they have a do{}while(0); construct surrounding the */
103/* code which is protected -- break may be used to exit this. */
104/* Other routines can safely use the return statement inline. */
105/* */
106/* Storage leak accounting can be enabled using DECALLOC. */
107/* */
108/* 2. All loops use the for(;;) construct. Any do construct does */
109/* not loop; it is for allocation protection as just described. */
110/* */
111/* 3. Setting status in the context must always be the very last */
112/* action in a routine, as non-0 status may raise a trap and hence */
113/* the call to set status may not return (if the handler uses long */
114/* jump). Therefore all cleanup must be done first. In general, */
115/* to achieve this status is accumulated and is only applied just */
116/* before return by calling decContextSetStatus (via decStatus). */
117/* */
118/* Routines which allocate storage cannot, in general, use the */
119/* 'top level' routines which could cause a non-returning */
120/* transfer of control. The decXxxxOp routines are safe (do not */
121/* call decStatus even if traps are set in the context) and should */
122/* be used instead (they are also a little faster). */
123/* */
124/* 4. Exponent checking is minimized by allowing the exponent to */
125/* grow outside its limits during calculations, provided that */
126/* the decFinalize function is called later. Multiplication and */
127/* division, and intermediate calculations in exponentiation, */
128/* require more careful checks because of the risk of 31-bit */
129/* overflow (the most negative valid exponent is -1999999997, for */
130/* a 999999999-digit number with adjusted exponent of -999999999). */
131/* */
132/* 5. Rounding is deferred until finalization of results, with any */
133/* 'off to the right' data being represented as a single digit */
134/* residue (in the range -1 through 9). This avoids any double- */
135/* rounding when more than one shortening takes place (for */
136/* example, when a result is subnormal). */
137/* */
138/* 6. The digits count is allowed to rise to a multiple of DECDPUN */
139/* during many operations, so whole Units are handled and exact */
140/* accounting of digits is not needed. The correct digits value */
141/* is found by decGetDigits, which accounts for leading zeros. */
142/* This must be called before any rounding if the number of digits */
143/* is not known exactly. */
144/* */
145/* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
146/* numbers up to four digits, using appropriate constants. This */
147/* is not useful for longer numbers because overflow of 32 bits */
148/* would lead to 4 multiplies, which is almost as expensive as */
149/* a divide (unless a floating-point or 64-bit multiply is */
150/* assumed to be available). */
151/* */
152/* 8. Unusual abbreviations that may be used in the commentary: */
153/* lhs -- left hand side (operand, of an operation) */
154/* lsd -- least significant digit (of coefficient) */
155/* lsu -- least significant Unit (of coefficient) */
156/* msd -- most significant digit (of coefficient) */
157/* msi -- most significant item (in an array) */
158/* msu -- most significant Unit (of coefficient) */
159/* rhs -- right hand side (operand, of an operation) */
160/* +ve -- positive */
161/* -ve -- negative */
162/* ** -- raise to the power */
163/* ------------------------------------------------------------------ */
164
165#include <stdlib.h> // for malloc, free, etc.
166#include <stdio.h> // for printf [if needed]
167#include <string.h> // for strcpy
168#include <ctype.h> // for lower
169#include "decNumber.h" // base number library
170#include "decNumberLocal.h" // decNumber local types, etc.
171
172/* Constants */
173// Public lookup table used by the D2U macro
174const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
175
176#define DECVERB 1 // set to 1 for verbose DECCHECK
177#define powers DECPOWERS // old internal name
178
179// Local constants
180#define DIVIDE 0x80 // Divide operators
181#define REMAINDER 0x40 // ..
182#define DIVIDEINT 0x20 // ..
183#define REMNEAR 0x10 // ..
184#define COMPARE 0x01 // Compare operators
185#define COMPMAX 0x02 // ..
186#define COMPMIN 0x03 // ..
187#define COMPTOTAL 0x04 // ..
188#define COMPNAN 0x05 // .. [NaN processing]
189#define COMPSIG 0x06 // .. [signaling COMPARE]
190#define COMPMAXMAG 0x07 // ..
191#define COMPMINMAG 0x08 // ..
192
193#define DEC_sNaN 0x40000000 // local status: sNaN signal
194#define BADINT (Int)0x80000000 // most-negative Int; error indicator
195// Next two indicate an integer >= 10**6, and its parity (bottom bit)
196#define BIGEVEN (Int)0x80000002
197#define BIGODD (Int)0x80000003
198
199static Unit uarrone[1]={1}; // Unit array of 1, used for incrementing
200
201/* Granularity-dependent code */
202#if DECDPUN<=4
203 #define eInt Int // extended integer
204 #define ueInt uInt // unsigned extended integer
205 // Constant multipliers for divide-by-power-of five using reciprocal
206 // multiply, after removing powers of 2 by shifting, and final shift
207 // of 17 [we only need up to **4]
208 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
209 // QUOT10 -- macro to return the quotient of unit u divided by 10**n
210 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
211#else
212 // For DECDPUN>4 non-ANSI-89 64-bit types are needed.
213 #if !DECUSE64
214 #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
215 #endif
216 #define eInt Long // extended integer
217 #define ueInt uLong // unsigned extended integer
218#endif
219
220/* Local routines */
221static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
222 decContext *, uByte, uInt *);
223static Flag decBiStr(const char *, const char *, const char *);
224static uInt decCheckMath(const decNumber *, decContext *, uInt *);
225static void decApplyRound(decNumber *, decContext *, Int, uInt *);
226static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
227static decNumber * decCompareOp(decNumber *, const decNumber *,
228 const decNumber *, decContext *,
229 Flag, uInt *);
230static void decCopyFit(decNumber *, const decNumber *, decContext *,
231 Int *, uInt *);
232static decNumber * decDecap(decNumber *, Int);
233static decNumber * decDivideOp(decNumber *, const decNumber *,
234 const decNumber *, decContext *, Flag, uInt *);
235static decNumber * decExpOp(decNumber *, const decNumber *,
236 decContext *, uInt *);
237static void decFinalize(decNumber *, decContext *, Int *, uInt *);
238static Int decGetDigits(Unit *, Int);
239static Int decGetInt(const decNumber *);
240static decNumber * decLnOp(decNumber *, const decNumber *,
241 decContext *, uInt *);
242static decNumber * decMultiplyOp(decNumber *, const decNumber *,
243 const decNumber *, decContext *,
244 uInt *);
245static decNumber * decNaNs(decNumber *, const decNumber *,
246 const decNumber *, decContext *, uInt *);
247static decNumber * decQuantizeOp(decNumber *, const decNumber *,
248 const decNumber *, decContext *, Flag,
249 uInt *);
250static void decReverse(Unit *, Unit *);
251static void decSetCoeff(decNumber *, decContext *, const Unit *,
252 Int, Int *, uInt *);
253static void decSetMaxValue(decNumber *, decContext *);
254static void decSetOverflow(decNumber *, decContext *, uInt *);
255static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
256static Int decShiftToLeast(Unit *, Int, Int);
257static Int decShiftToMost(Unit *, Int, Int);
258static void decStatus(decNumber *, uInt, decContext *);
259static void decToString(const decNumber *, char[], Flag);
260static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
261static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
262 Unit *, Int);
263static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
264
265#if !DECSUBSET
266/* decFinish == decFinalize when no subset arithmetic needed */
267#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
268#else
269static void decFinish(decNumber *, decContext *, Int *, uInt *);
270static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
271#endif
272
273/* Local macros */
274// masked special-values bits
275#define SPECIALARG (rhs->bits & DECSPECIAL)
276#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
277
278/* Diagnostic macros, etc. */
279#if DECALLOC
280// Handle malloc/free accounting. If enabled, our accountable routines
281// are used; otherwise the code just goes straight to the system malloc
282// and free routines.
283#define malloc(a) decMalloc(a)
284#define free(a) decFree(a)
285#define DECFENCE 0x5a // corruption detector
286// 'Our' malloc and free:
287static void *decMalloc(size_t);
288static void decFree(void *);
289uInt decAllocBytes=0; // count of bytes allocated
290// Note that DECALLOC code only checks for storage buffer overflow.
291// To check for memory leaks, the decAllocBytes variable must be
292// checked to be 0 at appropriate times (e.g., after the test
293// harness completes a set of tests). This checking may be unreliable
294// if the testing is done in a multi-thread environment.
295#endif
296
297#if DECCHECK
298// Optional checking routines. Enabling these means that decNumber
299// and decContext operands to operator routines are checked for
300// correctness. This roughly doubles the execution time of the
301// fastest routines (and adds 600+ bytes), so should not normally be
302// used in 'production'.
303// decCheckInexact is used to check that inexact results have a full
304// complement of digits (where appropriate -- this is not the case
305// for Quantize, for example)
306#define DECUNRESU ((decNumber *)(void *)0xffffffff)
307#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
308#define DECUNCONT ((decContext *)(void *)(0xffffffff))
309static Flag decCheckOperands(decNumber *, const decNumber *,
310 const decNumber *, decContext *);
311static Flag decCheckNumber(const decNumber *);
312static void decCheckInexact(const decNumber *, decContext *);
313#endif
314
315#if DECTRACE || DECCHECK
316// Optional trace/debugging routines (may or may not be used)
317void decNumberShow(const decNumber *); // displays the components of a number
318static void decDumpAr(char, const Unit *, Int);
319#endif
320
321/* ================================================================== */
322/* Conversions */
323/* ================================================================== */
324
325/* ------------------------------------------------------------------ */
326/* from-int32 -- conversion from Int or uInt */
327/* */
328/* dn is the decNumber to receive the integer */
329/* in or uin is the integer to be converted */
330/* returns dn */
331/* */
332/* No error is possible. */
333/* ------------------------------------------------------------------ */
334decNumber * decNumberFromInt32(decNumber *dn, Int in) {
335 uInt unsig;
336 if (in>=0) unsig=in;
337 else { // negative (possibly BADINT)
338 if (in==BADINT) unsig=(uInt)1073741824*2; // special case
339 else unsig=-in; // invert
340 }
341 // in is now positive
342 decNumberFromUInt32(dn, unsig);
343 if (in<0) dn->bits=DECNEG; // sign needed
344 return dn;
345 } // decNumberFromInt32
346
347decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
348 Unit *up; // work pointer
349 decNumberZero(dn); // clean
350 if (uin==0) return dn; // [or decGetDigits bad call]
351 for (up=dn->lsu; uin>0; up++) {
352 *up=(Unit)(uin%(DECDPUNMAX+1));
353 uin=uin/(DECDPUNMAX+1);
354 }
355 dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
356 return dn;
357 } // decNumberFromUInt32
358
359/* ------------------------------------------------------------------ */
360/* to-int32 -- conversion to Int or uInt */
361/* */
362/* dn is the decNumber to convert */
363/* set is the context for reporting errors */
364/* returns the converted decNumber, or 0 if Invalid is set */
365/* */
366/* Invalid is set if the decNumber does not have exponent==0 or if */
367/* it is a NaN, Infinite, or out-of-range. */
368/* ------------------------------------------------------------------ */
369Int decNumberToInt32(const decNumber *dn, decContext *set) {
370 #if DECCHECK
371 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
372 #endif
373
374 // special or too many digits, or bad exponent
375 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad
376 else { // is a finite integer with 10 or fewer digits
377 Int d; // work
378 const Unit *up; // ..
379 uInt hi=0, lo; // ..
380 up=dn->lsu; // -> lsu
381 lo=*up; // get 1 to 9 digits
382 #if DECDPUN>1 // split to higher
383 hi=lo/10;
384 lo=lo%10;
385 #endif
386 up++;
387 // collect remaining Units, if any, into hi
388 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
389 // now low has the lsd, hi the remainder
390 if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
391 // most-negative is a reprieve
392 if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
393 // bad -- drop through
394 }
395 else { // in-range always
396 Int i=X10(hi)+lo;
397 if (dn->bits&DECNEG) return -i;
398 return i;
399 }
400 } // integer
401 decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
402 return 0;
403 } // decNumberToInt32
404
405uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
406 #if DECCHECK
407 if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
408 #endif
409 // special or too many digits, or bad exponent, or negative (<0)
410 if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
411 || (dn->bits&DECNEG && !ISZERO(dn))); // bad
412 else { // is a finite integer with 10 or fewer digits
413 Int d; // work
414 const Unit *up; // ..
415 uInt hi=0, lo; // ..
416 up=dn->lsu; // -> lsu
417 lo=*up; // get 1 to 9 digits
418 #if DECDPUN>1 // split to higher
419 hi=lo/10;
420 lo=lo%10;
421 #endif
422 up++;
423 // collect remaining Units, if any, into hi
424 for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
425
426 // now low has the lsd, hi the remainder
427 if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible
428 else return X10(hi)+lo;
429 } // integer
430 decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
431 return 0;
432 } // decNumberToUInt32
433
434/* ------------------------------------------------------------------ */
435/* to-scientific-string -- conversion to numeric string */
436/* to-engineering-string -- conversion to numeric string */
437/* */
438/* decNumberToString(dn, string); */
439/* decNumberToEngString(dn, string); */
440/* */
441/* dn is the decNumber to convert */
442/* string is the string where the result will be laid out */
443/* */
444/* string must be at least dn->digits+14 characters long */
445/* */
446/* No error is possible, and no status can be set. */
447/* ------------------------------------------------------------------ */
448char * decNumberToString(const decNumber *dn, char *string){
449 decToString(dn, string, 0);
450 return string;
451 } // DecNumberToString
452
453char * decNumberToEngString(const decNumber *dn, char *string){
454 decToString(dn, string, 1);
455 return string;
456 } // DecNumberToEngString
457
458/* ------------------------------------------------------------------ */
459/* to-number -- conversion from numeric string */
460/* */
461/* decNumberFromString -- convert string to decNumber */
462/* dn -- the number structure to fill */
463/* chars[] -- the string to convert ('\0' terminated) */
464/* set -- the context used for processing any error, */
465/* determining the maximum precision available */
466/* (set.digits), determining the maximum and minimum */
467/* exponent (set.emax and set.emin), determining if */
468/* extended values are allowed, and checking the */
469/* rounding mode if overflow occurs or rounding is */
470/* needed. */
471/* */
472/* The length of the coefficient and the size of the exponent are */
473/* checked by this routine, so the correct error (Underflow or */
474/* Overflow) can be reported or rounding applied, as necessary. */
475/* */
476/* If bad syntax is detected, the result will be a quiet NaN. */
477/* ------------------------------------------------------------------ */
478decNumber * decNumberFromString(decNumber *dn, const char chars[],
479 decContext *set) {
480 Int exponent=0; // working exponent [assume 0]
481 uByte bits=0; // working flags [assume +ve]
482 Unit *res; // where result will be built
483 Unit resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
484 // [+9 allows for ln() constants]
485 Unit *allocres=NULL; // -> allocated result, iff allocated
486 Int d=0; // count of digits found in decimal part
487 const char *dotchar=NULL; // where dot was found
488 const char *cfirst=chars; // -> first character of decimal part
489 const char *last=NULL; // -> last digit of decimal part
490 const char *c; // work
491 Unit *up; // ..
492 #if DECDPUN>1
493 Int cut, out; // ..
494 #endif
495 Int residue; // rounding residue
496 uInt status=0; // error code
497
498 #if DECCHECK
499 if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
500 return decNumberZero(dn);
501 #endif
502
503 do { // status & malloc protection
504 for (c=chars;; c++) { // -> input character
505 if (*c>='0' && *c<='9') { // test for Arabic digit
506 last=c;
507 d++; // count of real digits
508 continue; // still in decimal part
509 }
510 if (*c=='.' && dotchar==NULL) { // first '.'
511 dotchar=c; // record offset into decimal part
512 if (c==cfirst) cfirst++; // first digit must follow
513 continue;}
514 if (c==chars) { // first in string...
515 if (*c=='-') { // valid - sign
516 cfirst++;
517 bits=DECNEG;
518 continue;}
519 if (*c=='+') { // valid + sign
520 cfirst++;
521 continue;}
522 }
523 // *c is not a digit, or a valid +, -, or '.'
524 break;
525 } // c
526
527 if (last==NULL) { // no digits yet
528 status=DEC_Conversion_syntax;// assume the worst
529 if (*c=='\0') break; // and no more to come...
530 #if DECSUBSET
531 // if subset then infinities and NaNs are not allowed
532 if (!set->extended) break; // hopeless
533 #endif
534 // Infinities and NaNs are possible, here
535 if (dotchar!=NULL) break; // .. unless had a dot
536 decNumberZero(dn); // be optimistic
537 if (decBiStr(c, "infinity", "INFINITY")
538 || decBiStr(c, "inf", "INF")) {
539 dn->bits=bits | DECINF;
540 status=0; // is OK
541 break; // all done
542 }
543 // a NaN expected
544 // 2003.09.10 NaNs are now permitted to have a sign
545 dn->bits=bits | DECNAN; // assume simple NaN
546 if (*c=='s' || *c=='S') { // looks like an sNaN
547 c++;
548 dn->bits=bits | DECSNAN;
549 }
550 if (*c!='n' && *c!='N') break; // check caseless "NaN"
551 c++;
552 if (*c!='a' && *c!='A') break; // ..
553 c++;
554 if (*c!='n' && *c!='N') break; // ..
555 c++;
556 // now either nothing, or nnnn payload, expected
557 // -> start of integer and skip leading 0s [including plain 0]
558 for (cfirst=c; *cfirst=='0';) cfirst++;
559 if (*cfirst=='\0') { // "NaN" or "sNaN", maybe with all 0s
560 status=0; // it's good
561 break; // ..
562 }
563 // something other than 0s; setup last and d as usual [no dots]
564 for (c=cfirst;; c++, d++) {
565 if (*c<'0' || *c>'9') break; // test for Arabic digit
566 last=c;
567 }
568 if (*c!='\0') break; // not all digits
569 if (d>set->digits-1) {
570 // [NB: payload in a decNumber can be full length unless
571 // clamped, in which case can only be digits-1]
572 if (set->clamp) break;
573 if (d>set->digits) break;
574 } // too many digits?
575 // good; drop through to convert the integer to coefficient
576 status=0; // syntax is OK
577 bits=dn->bits; // for copy-back
578 } // last==NULL
579
580 else if (*c!='\0') { // more to process...
581 // had some digits; exponent is only valid sequence now
582 Flag nege; // 1=negative exponent
583 const char *firstexp; // -> first significant exponent digit
584 status=DEC_Conversion_syntax;// assume the worst
585 uInt expa=0; // accumulator for exponent
586 if (*c!='e' && *c!='E') break;
587 /* Found 'e' or 'E' -- now process explicit exponent */
588 // 1998.07.11: sign no longer required
589 nege=0;
590 c++; // to (possible) sign
591 if (*c=='-') {nege=1; c++;}
592 else if (*c=='+') c++;
593 if (*c=='\0') break;
594
595 for (; *c=='0' && *(c+1)!='\0';) c++; // strip insignificant zeros
596 firstexp=c; // save exponent digit place
597 for (; ;c++) {
598 if (*c<'0' || *c>'9') break; // not a digit
599 expa=X10(expa)+(Int)*c-(Int)'0';
600 } // c
601 // if not now on a '\0', *c must not be a digit
602 if (*c!='\0') break;
603
604 // (this next test must be after the syntax checks)
605 // if it was too long the exponent may have wrapped, so check
606 // carefully and set it to a certain overflow if wrap possible
607 if (c>=firstexp+9+1) {
608 if (c>firstexp+9+1 || *firstexp>'1') expa=DECNUMMAXE*2;
609 // [up to 1999999999 is OK, for example 1E-1000000998]
610 }
611 exponent=(Int)expa; // save exponent
612 if (nege) exponent=-exponent; // was negative
613 status=0; // is OK
614 } // stuff after digits
615
616 // Here when whole string has been inspected; syntax is good
617 // cfirst->first digit (never dot), last->last digit (ditto)
618
619 // strip leading zeros/dot [leave final 0 if all 0's]
620 if (*cfirst=='0') { // [cfirst has stepped over .]
621 for (c=cfirst; c<last; c++, cfirst++) {
622 if (*c=='.') continue; // ignore dots
623 if (*c!='0') break; // non-zero found
624 d--; // 0 stripped
625 } // c
626 #if DECSUBSET
627 // make a rapid exit for easy zeros if !extended
628 if (*cfirst=='0' && !set->extended) {
629 decNumberZero(dn); // clean result
630 break; // [could be return]
631 }
632 #endif
633 } // at least one leading 0
634
635 // Handle decimal point...
636 if (dotchar!=NULL && dotchar<last) // non-trailing '.' found?
637 exponent-=(last-dotchar); // adjust exponent
638 // [we can now ignore the .]
639
640 // OK, the digits string is good. Assemble in the decNumber, or in
641 // a temporary units array if rounding is needed
642 if (d<=set->digits) res=dn->lsu; // fits into supplied decNumber
643 else { // rounding needed
644 Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
645 res=resbuff; // assume use local buffer
646 if (needbytes>(Int)sizeof(resbuff)) { // too big for local
647 allocres=(Unit *)malloc(needbytes);
648 if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
649 res=allocres;
650 }
651 }
652 // res now -> number lsu, buffer, or allocated storage for Unit array
653
654 // Place the coefficient into the selected Unit array
655 // [this is often 70% of the cost of this function when DECDPUN>1]
656 #if DECDPUN>1
657 out=0; // accumulator
658 up=res+D2U(d)-1; // -> msu
659 cut=d-(up-res)*DECDPUN; // digits in top unit
660 for (c=cfirst;; c++) { // along the digits
661 if (*c=='.') continue; // ignore '.' [don't decrement cut]
662 out=X10(out)+(Int)*c-(Int)'0';
663 if (c==last) break; // done [never get to trailing '.']
664 cut--;
665 if (cut>0) continue; // more for this unit
666 *up=(Unit)out; // write unit
667 up--; // prepare for unit below..
668 cut=DECDPUN; // ..
669 out=0; // ..
670 } // c
671 *up=(Unit)out; // write lsu
672
673 #else
674 // DECDPUN==1
675 up=res; // -> lsu
676 for (c=last; c>=cfirst; c--) { // over each character, from least
677 if (*c=='.') continue; // ignore . [don't step up]
678 *up=(Unit)((Int)*c-(Int)'0');
679 up++;
680 } // c
681 #endif
682
683 dn->bits=bits;
684 dn->exponent=exponent;
685 dn->digits=d;
686
687 // if not in number (too long) shorten into the number
688 if (d>set->digits) {
689 residue=0;
690 decSetCoeff(dn, set, res, d, &residue, &status);
691 // always check for overflow or subnormal and round as needed
692 decFinalize(dn, set, &residue, &status);
693 }
694 else { // no rounding, but may still have overflow or subnormal
695 // [these tests are just for performance; finalize repeats them]
696 if ((dn->exponent-1<set->emin-dn->digits)
697 || (dn->exponent-1>set->emax-set->digits)) {
698 residue=0;
699 decFinalize(dn, set, &residue, &status);
700 }
701 }
702 // decNumberShow(dn);
703 } while(0); // [for break]
704
705 if (allocres!=NULL) free(allocres); // drop any storage used
706 if (status!=0) decStatus(dn, status, set);
707 return dn;
708 } /* decNumberFromString */
709
710/* ================================================================== */
711/* Operators */
712/* ================================================================== */
713
714/* ------------------------------------------------------------------ */
715/* decNumberAbs -- absolute value operator */
716/* */
717/* This computes C = abs(A) */
718/* */
719/* res is C, the result. C may be A */
720/* rhs is A */
721/* set is the context */
722/* */
723/* See also decNumberCopyAbs for a quiet bitwise version of this. */
724/* C must have space for set->digits digits. */
725/* ------------------------------------------------------------------ */
726/* This has the same effect as decNumberPlus unless A is negative, */
727/* in which case it has the same effect as decNumberMinus. */
728/* ------------------------------------------------------------------ */
729decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
730 decContext *set) {
731 decNumber dzero; // for 0
732 uInt status=0; // accumulator
733
734 #if DECCHECK
735 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
736 #endif
737
738 decNumberZero(&dzero); // set 0
739 dzero.exponent=rhs->exponent; // [no coefficient expansion]
740 decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
741 if (status!=0) decStatus(res, status, set);
742 #if DECCHECK
743 decCheckInexact(res, set);
744 #endif
745 return res;
746 } // decNumberAbs
747
748/* ------------------------------------------------------------------ */
749/* decNumberAdd -- add two Numbers */
750/* */
751/* This computes C = A + B */
752/* */
753/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
754/* lhs is A */
755/* rhs is B */
756/* set is the context */
757/* */
758/* C must have space for set->digits digits. */
759/* ------------------------------------------------------------------ */
760/* This just calls the routine shared with Subtract */
761decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
762 const decNumber *rhs, decContext *set) {
763 uInt status=0; // accumulator
764 decAddOp(res, lhs, rhs, set, 0, &status);
765 if (status!=0) decStatus(res, status, set);
766 #if DECCHECK
767 decCheckInexact(res, set);
768 #endif
769 return res;
770 } // decNumberAdd
771
772/* ------------------------------------------------------------------ */
773/* decNumberAnd -- AND two Numbers, digitwise */
774/* */
775/* This computes C = A & B */
776/* */
777/* res is C, the result. C may be A and/or B (e.g., X=X&X) */
778/* lhs is A */
779/* rhs is B */
780/* set is the context (used for result length and error report) */
781/* */
782/* C must have space for set->digits digits. */
783/* */
784/* Logical function restrictions apply (see above); a NaN is */
785/* returned with Invalid_operation if a restriction is violated. */
786/* ------------------------------------------------------------------ */
787decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
788 const decNumber *rhs, decContext *set) {
789 const Unit *ua, *ub; // -> operands
790 const Unit *msua, *msub; // -> operand msus
791 Unit *uc, *msuc; // -> result and its msu
792 Int msudigs; // digits in res msu
793 #if DECCHECK
794 if (decCheckOperands(res, lhs, rhs, set)) return res;
795 #endif
796
797 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
798 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
799 decStatus(res, DEC_Invalid_operation, set);
800 return res;
801 }
802
803 // operands are valid
804 ua=lhs->lsu; // bottom-up
805 ub=rhs->lsu; // ..
806 uc=res->lsu; // ..
807 msua=ua+D2U(lhs->digits)-1; // -> msu of lhs
808 msub=ub+D2U(rhs->digits)-1; // -> msu of rhs
809 msuc=uc+D2U(set->digits)-1; // -> msu of result
810 msudigs=MSUDIGITS(set->digits); // [faster than remainder]
811 for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop
812 Unit a, b; // extract units
813 if (ua>msua) a=0;
814 else a=*ua;
815 if (ub>msub) b=0;
816 else b=*ub;
817 *uc=0; // can now write back
818 if (a|b) { // maybe 1 bits to examine
819 Int i, j;
820 *uc=0; // can now write back
821 // This loop could be unrolled and/or use BIN2BCD tables
822 for (i=0; i<DECDPUN; i++) {
823 if (a&b&1) *uc=*uc+(Unit)powers[i]; // effect AND
824 j=a%10;
825 a=a/10;
826 j|=b%10;
827 b=b/10;
828 if (j>1) {
829 decStatus(res, DEC_Invalid_operation, set);
830 return res;
831 }
832 if (uc==msuc && i==msudigs-1) break; // just did final digit
833 } // each digit
834 } // both OK
835 } // each unit
836 // [here uc-1 is the msu of the result]
837 res->digits=decGetDigits(res->lsu, uc-res->lsu);
838 res->exponent=0; // integer
839 res->bits=0; // sign=0
840 return res; // [no status to set]
841 } // decNumberAnd
842
843/* ------------------------------------------------------------------ */
844/* decNumberCompare -- compare two Numbers */
845/* */
846/* This computes C = A ? B */
847/* */
848/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
849/* lhs is A */
850/* rhs is B */
851/* set is the context */
852/* */
853/* C must have space for one digit (or NaN). */
854/* ------------------------------------------------------------------ */
855decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
856 const decNumber *rhs, decContext *set) {
857 uInt status=0; // accumulator
858 decCompareOp(res, lhs, rhs, set, COMPARE, &status);
859 if (status!=0) decStatus(res, status, set);
860 return res;
861 } // decNumberCompare
862
863/* ------------------------------------------------------------------ */
864/* decNumberCompareSignal -- compare, signalling on all NaNs */
865/* */
866/* This computes C = A ? B */
867/* */
868/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
869/* lhs is A */
870/* rhs is B */
871/* set is the context */
872/* */
873/* C must have space for one digit (or NaN). */
874/* ------------------------------------------------------------------ */
875decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
876 const decNumber *rhs, decContext *set) {
877 uInt status=0; // accumulator
878 decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
879 if (status!=0) decStatus(res, status, set);
880 return res;
881 } // decNumberCompareSignal
882
883/* ------------------------------------------------------------------ */
884/* decNumberCompareTotal -- compare two Numbers, using total ordering */
885/* */
886/* This computes C = A ? B, under total ordering */
887/* */
888/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
889/* lhs is A */
890/* rhs is B */
891/* set is the context */
892/* */
893/* C must have space for one digit; the result will always be one of */
894/* -1, 0, or 1. */
895/* ------------------------------------------------------------------ */
896decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
897 const decNumber *rhs, decContext *set) {
898 uInt status=0; // accumulator
899 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
900 if (status!=0) decStatus(res, status, set);
901 return res;
902 } // decNumberCompareTotal
903
904/* ------------------------------------------------------------------ */
905/* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
906/* */
907/* This computes C = |A| ? |B|, under total ordering */
908/* */
909/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
910/* lhs is A */
911/* rhs is B */
912/* set is the context */
913/* */
914/* C must have space for one digit; the result will always be one of */
915/* -1, 0, or 1. */
916/* ------------------------------------------------------------------ */
917decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
918 const decNumber *rhs, decContext *set) {
919 uInt status=0; // accumulator
920 uInt needbytes; // for space calculations
921 decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
922 decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
923 decNumber bufb[D2N(DECBUFFER+1)];
924 decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated
925 decNumber *a, *b; // temporary pointers
926
927 #if DECCHECK
928 if (decCheckOperands(res, lhs, rhs, set)) return res;
929 #endif
930
931 do { // protect allocated storage
932 // if either is negative, take a copy and absolute
933 if (decNumberIsNegative(lhs)) { // lhs<0
934 a=bufa;
935 needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
936 if (needbytes>sizeof(bufa)) { // need malloc space
937 allocbufa=(decNumber *)malloc(needbytes);
938 if (allocbufa==NULL) { // hopeless -- abandon
939 status|=DEC_Insufficient_storage;
940 break;}
941 a=allocbufa; // use the allocated space
942 }
943 decNumberCopy(a, lhs); // copy content
944 a->bits&=~DECNEG; // .. and clear the sign
945 lhs=a; // use copy from here on
946 }
947 if (decNumberIsNegative(rhs)) { // rhs<0
948 b=bufb;
949 needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
950 if (needbytes>sizeof(bufb)) { // need malloc space
951 allocbufb=(decNumber *)malloc(needbytes);
952 if (allocbufb==NULL) { // hopeless -- abandon
953 status|=DEC_Insufficient_storage;
954 break;}
955 b=allocbufb; // use the allocated space
956 }
957 decNumberCopy(b, rhs); // copy content
958 b->bits&=~DECNEG; // .. and clear the sign
959 rhs=b; // use copy from here on
960 }
961 decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
962 } while(0); // end protected
963
964 if (allocbufa!=NULL) free(allocbufa); // drop any storage used
965 if (allocbufb!=NULL) free(allocbufb); // ..
966 if (status!=0) decStatus(res, status, set);
967 return res;
968 } // decNumberCompareTotalMag
969
970/* ------------------------------------------------------------------ */
971/* decNumberDivide -- divide one number by another */
972/* */
973/* This computes C = A / B */
974/* */
975/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
976/* lhs is A */
977/* rhs is B */
978/* set is the context */
979/* */
980/* C must have space for set->digits digits. */
981/* ------------------------------------------------------------------ */
982decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
983 const decNumber *rhs, decContext *set) {
984 uInt status=0; // accumulator
985 decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
986 if (status!=0) decStatus(res, status, set);
987 #if DECCHECK
988 decCheckInexact(res, set);
989 #endif
990 return res;
991 } // decNumberDivide
992
993/* ------------------------------------------------------------------ */
994/* decNumberDivideInteger -- divide and return integer quotient */
995/* */
996/* This computes C = A # B, where # is the integer divide operator */
997/* */
998/* res is C, the result. C may be A and/or B (e.g., X=X#X) */
999/* lhs is A */
1000/* rhs is B */
1001/* set is the context */
1002/* */
1003/* C must have space for set->digits digits. */
1004/* ------------------------------------------------------------------ */
1005decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1006 const decNumber *rhs, decContext *set) {
1007 uInt status=0; // accumulator
1008 decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1009 if (status!=0) decStatus(res, status, set);
1010 return res;
1011 } // decNumberDivideInteger
1012
1013/* ------------------------------------------------------------------ */
1014/* decNumberExp -- exponentiation */
1015/* */
1016/* This computes C = exp(A) */
1017/* */
1018/* res is C, the result. C may be A */
1019/* rhs is A */
1020/* set is the context; note that rounding mode has no effect */
1021/* */
1022/* C must have space for set->digits digits. */
1023/* */
1024/* Mathematical function restrictions apply (see above); a NaN is */
1025/* returned with Invalid_operation if a restriction is violated. */
1026/* */
1027/* Finite results will always be full precision and Inexact, except */
1028/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
1029/* */
1030/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1031/* almost always be correctly rounded, but may be up to 1 ulp in */
1032/* error in rare cases. */
1033/* ------------------------------------------------------------------ */
1034/* This is a wrapper for decExpOp which can handle the slightly wider */
1035/* (double) range needed by Ln (which has to be able to calculate */
1036/* exp(-a) where a can be the tiniest number (Ntiny). */
1037/* ------------------------------------------------------------------ */
1038decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1039 decContext *set) {
1040 uInt status=0; // accumulator
1041 #if DECSUBSET
1042 decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
1043 #endif
1044
1045 #if DECCHECK
1046 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1047 #endif
1048
1049 // Check restrictions; these restrictions ensure that if h=8 (see
1050 // decExpOp) then the result will either overflow or underflow to 0.
1051 // Other math functions restrict the input range, too, for inverses.
1052 // If not violated then carry out the operation.
1053 if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1054 #if DECSUBSET
1055 if (!set->extended) {
1056 // reduce operand and set lostDigits status, as needed
1057 if (rhs->digits>set->digits) {
1058 allocrhs=decRoundOperand(rhs, set, &status);
1059 if (allocrhs==NULL) break;
1060 rhs=allocrhs;
1061 }
1062 }
1063 #endif
1064 decExpOp(res, rhs, set, &status);
1065 } while(0); // end protected
1066
1067 #if DECSUBSET
1068 if (allocrhs !=NULL) free(allocrhs); // drop any storage used
1069 #endif
1070 // apply significant status
1071 if (status!=0) decStatus(res, status, set);
1072 #if DECCHECK
1073 decCheckInexact(res, set);
1074 #endif
1075 return res;
1076 } // decNumberExp
1077
1078/* ------------------------------------------------------------------ */
1079/* decNumberFMA -- fused multiply add */
1080/* */
1081/* This computes D = (A * B) + C with only one rounding */
1082/* */
1083/* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */
1084/* lhs is A */
1085/* rhs is B */
1086/* fhs is C [far hand side] */
1087/* set is the context */
1088/* */
1089/* Mathematical function restrictions apply (see above); a NaN is */
1090/* returned with Invalid_operation if a restriction is violated. */
1091/* */
1092/* C must have space for set->digits digits. */
1093/* ------------------------------------------------------------------ */
1094decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1095 const decNumber *rhs, const decNumber *fhs,
1096 decContext *set) {
1097 uInt status=0; // accumulator
1098 decContext dcmul; // context for the multiplication
1099 uInt needbytes; // for space calculations
1100 decNumber bufa[D2N(DECBUFFER*2+1)];
1101 decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
1102 decNumber *acc; // accumulator pointer
1103 decNumber dzero; // work
1104
1105 #if DECCHECK
1106 if (decCheckOperands(res, lhs, rhs, set)) return res;
1107 if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1108 #endif
1109
1110 do { // protect allocated storage
1111 #if DECSUBSET
1112 if (!set->extended) { // [undefined if subset]
1113 status|=DEC_Invalid_operation;
1114 break;}
1115 #endif
1116 // Check math restrictions [these ensure no overflow or underflow]
1117 if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1118 || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1119 || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1120 // set up context for multiply
1121 dcmul=*set;
1122 dcmul.digits=lhs->digits+rhs->digits; // just enough
1123 // [The above may be an over-estimate for subset arithmetic, but that's OK]
1124 dcmul.emax=DEC_MAX_EMAX; // effectively unbounded ..
1125 dcmul.emin=DEC_MIN_EMIN; // [thanks to Math restrictions]
1126 // set up decNumber space to receive the result of the multiply
1127 acc=bufa; // may fit
1128 needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1129 if (needbytes>sizeof(bufa)) { // need malloc space
1130 allocbufa=(decNumber *)malloc(needbytes);
1131 if (allocbufa==NULL) { // hopeless -- abandon
1132 status|=DEC_Insufficient_storage;
1133 break;}
1134 acc=allocbufa; // use the allocated space
1135 }
1136 // multiply with extended range and necessary precision
1137 //printf("emin=%ld\n", dcmul.emin);
1138 decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1139 // Only Invalid operation (from sNaN or Inf * 0) is possible in
1140 // status; if either is seen than ignore fhs (in case it is
1141 // another sNaN) and set acc to NaN unless we had an sNaN
1142 // [decMultiplyOp leaves that to caller]
1143 // Note sNaN has to go through addOp to shorten payload if
1144 // necessary
1145 if ((status&DEC_Invalid_operation)!=0) {
1146 if (!(status&DEC_sNaN)) { // but be true invalid
1147 decNumberZero(res); // acc not yet set
1148 res->bits=DECNAN;
1149 break;
1150 }
1151 decNumberZero(&dzero); // make 0 (any non-NaN would do)
1152 fhs=&dzero; // use that
1153 }
1154 #if DECCHECK
1155 else { // multiply was OK
1156 if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1157 }
1158 #endif
1159 // add the third operand and result -> res, and all is done
1160 decAddOp(res, acc, fhs, set, 0, &status);
1161 } while(0); // end protected
1162
1163 if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1164 if (status!=0) decStatus(res, status, set);
1165 #if DECCHECK
1166 decCheckInexact(res, set);
1167 #endif
1168 return res;
1169 } // decNumberFMA
1170
1171/* ------------------------------------------------------------------ */
1172/* decNumberInvert -- invert a Number, digitwise */
1173/* */
1174/* This computes C = ~A */
1175/* */
1176/* res is C, the result. C may be A (e.g., X=~X) */
1177/* rhs is A */
1178/* set is the context (used for result length and error report) */
1179/* */
1180/* C must have space for set->digits digits. */
1181/* */
1182/* Logical function restrictions apply (see above); a NaN is */
1183/* returned with Invalid_operation if a restriction is violated. */
1184/* ------------------------------------------------------------------ */
1185decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1186 decContext *set) {
1187 const Unit *ua, *msua; // -> operand and its msu
1188 Unit *uc, *msuc; // -> result and its msu
1189 Int msudigs; // digits in res msu
1190 #if DECCHECK
1191 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1192 #endif
1193
1194 if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1195 decStatus(res, DEC_Invalid_operation, set);
1196 return res;
1197 }
1198 // operand is valid
1199 ua=rhs->lsu; // bottom-up
1200 uc=res->lsu; // ..
1201 msua=ua+D2U(rhs->digits)-1; // -> msu of rhs
1202 msuc=uc+D2U(set->digits)-1; // -> msu of result
1203 msudigs=MSUDIGITS(set->digits); // [faster than remainder]
1204 for (; uc<=msuc; ua++, uc++) { // Unit loop
1205 Unit a; // extract unit
1206 Int i, j; // work
1207 if (ua>msua) a=0;
1208 else a=*ua;
1209 *uc=0; // can now write back
1210 // always need to examine all bits in rhs
1211 // This loop could be unrolled and/or use BIN2BCD tables
1212 for (i=0; i<DECDPUN; i++) {
1213 if ((~a)&1) *uc=*uc+(Unit)powers[i]; // effect INVERT
1214 j=a%10;
1215 a=a/10;
1216 if (j>1) {
1217 decStatus(res, DEC_Invalid_operation, set);
1218 return res;
1219 }
1220 if (uc==msuc && i==msudigs-1) break; // just did final digit
1221 } // each digit
1222 } // each unit
1223 // [here uc-1 is the msu of the result]
1224 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1225 res->exponent=0; // integer
1226 res->bits=0; // sign=0
1227 return res; // [no status to set]
1228 } // decNumberInvert
1229
1230/* ------------------------------------------------------------------ */
1231/* decNumberLn -- natural logarithm */
1232/* */
1233/* This computes C = ln(A) */
1234/* */
1235/* res is C, the result. C may be A */
1236/* rhs is A */
1237/* set is the context; note that rounding mode has no effect */
1238/* */
1239/* C must have space for set->digits digits. */
1240/* */
1241/* Notable cases: */
1242/* A<0 -> Invalid */
1243/* A=0 -> -Infinity (Exact) */
1244/* A=+Infinity -> +Infinity (Exact) */
1245/* A=1 exactly -> 0 (Exact) */
1246/* */
1247/* Mathematical function restrictions apply (see above); a NaN is */
1248/* returned with Invalid_operation if a restriction is violated. */
1249/* */
1250/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1251/* almost always be correctly rounded, but may be up to 1 ulp in */
1252/* error in rare cases. */
1253/* ------------------------------------------------------------------ */
1254/* This is a wrapper for decLnOp which can handle the slightly wider */
1255/* (+11) range needed by Ln, Log10, etc. (which may have to be able */
1256/* to calculate at p+e+2). */
1257/* ------------------------------------------------------------------ */
1258decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1259 decContext *set) {
1260 uInt status=0; // accumulator
1261 #if DECSUBSET
1262 decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
1263 #endif
1264
1265 #if DECCHECK
1266 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1267 #endif
1268
1269 // Check restrictions; this is a math function; if not violated
1270 // then carry out the operation.
1271 if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1272 #if DECSUBSET
1273 if (!set->extended) {
1274 // reduce operand and set lostDigits status, as needed
1275 if (rhs->digits>set->digits) {
1276 allocrhs=decRoundOperand(rhs, set, &status);
1277 if (allocrhs==NULL) break;
1278 rhs=allocrhs;
1279 }
1280 // special check in subset for rhs=0
1281 if (ISZERO(rhs)) { // +/- zeros -> error
1282 status|=DEC_Invalid_operation;
1283 break;}
1284 } // extended=0
1285 #endif
1286 decLnOp(res, rhs, set, &status);
1287 } while(0); // end protected
1288
1289 #if DECSUBSET
1290 if (allocrhs !=NULL) free(allocrhs); // drop any storage used
1291 #endif
1292 // apply significant status
1293 if (status!=0) decStatus(res, status, set);
1294 #if DECCHECK
1295 decCheckInexact(res, set);
1296 #endif
1297 return res;
1298 } // decNumberLn
1299
1300/* ------------------------------------------------------------------ */
1301/* decNumberLogB - get adjusted exponent, by 754 rules */
1302/* */
1303/* This computes C = adjustedexponent(A) */
1304/* */
1305/* res is C, the result. C may be A */
1306/* rhs is A */
1307/* set is the context, used only for digits and status */
1308/* */
1309/* For an unrounded result, digits may need to be 10 (A might have */
1310/* 10**9 digits and an exponent of +999999999, or one digit and an */
1311/* exponent of -1999999999). */
1312/* */
1313/* This returns the adjusted exponent of A after (in theory) padding */
1314/* with zeros on the right to set->digits digits while keeping the */
1315/* same value. The exponent is not limited by emin/emax. */
1316/* */
1317/* Notable cases: */
1318/* A<0 -> Use |A| */
1319/* A=0 -> -Infinity (Division by zero) */
1320/* A=Infinite -> +Infinity (Exact) */
1321/* A=1 exactly -> 0 (Exact) */
1322/* NaNs are propagated as usual */
1323/* ------------------------------------------------------------------ */
1324decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1325 decContext *set) {
1326 uInt status=0; // accumulator
1327
1328 #if DECCHECK
1329 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1330 #endif
1331
1332 // NaNs as usual; Infinities return +Infinity; 0->oops
1333 if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1334 else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1335 else if (decNumberIsZero(rhs)) {
1336 decNumberZero(res); // prepare for Infinity
1337 res->bits=DECNEG|DECINF; // -Infinity
1338 status|=DEC_Division_by_zero; // as per 754
1339 }
1340 else { // finite non-zero
1341 Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
1342 if (set->digits>=10) decNumberFromInt32(res, ae); // lay it out
1343 else {
1344 decNumber buft[D2N(10)]; // temporary number
1345 decNumber *t=buft; // ..
1346 decNumberFromInt32(t, ae); // lay it out
1347 decNumberPlus(res, t, set); // round as necessary
1348 }
1349 }
1350
1351 if (status!=0) decStatus(res, status, set);
1352 return res;
1353 } // decNumberLogB
1354
1355/* ------------------------------------------------------------------ */
1356/* decNumberLog10 -- logarithm in base 10 */
1357/* */
1358/* This computes C = log10(A) */
1359/* */
1360/* res is C, the result. C may be A */
1361/* rhs is A */
1362/* set is the context; note that rounding mode has no effect */
1363/* */
1364/* C must have space for set->digits digits. */
1365/* */
1366/* Notable cases: */
1367/* A<0 -> Invalid */
1368/* A=0 -> -Infinity (Exact) */
1369/* A=+Infinity -> +Infinity (Exact) */
1370/* A=10**n (if n is an integer) -> n (Exact) */
1371/* */
1372/* Mathematical function restrictions apply (see above); a NaN is */
1373/* returned with Invalid_operation if a restriction is violated. */
1374/* */
1375/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
1376/* almost always be correctly rounded, but may be up to 1 ulp in */
1377/* error in rare cases. */
1378/* ------------------------------------------------------------------ */
1379/* This calculates ln(A)/ln(10) using appropriate precision. For */
1380/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
1381/* requested digits and t is the number of digits in the exponent */
1382/* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
1383/* fastpath in decLnOp. The final division is done to the requested */
1384/* precision. */
1385/* ------------------------------------------------------------------ */
1386decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1387 decContext *set) {
1388 uInt status=0, ignore=0; // status accumulators
1389 uInt needbytes; // for space calculations
1390 Int p; // working precision
1391 Int t; // digits in exponent of A
1392
1393 // buffers for a and b working decimals
1394 // (adjustment calculator, same size)
1395 decNumber bufa[D2N(DECBUFFER+2)];
1396 decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
1397 decNumber *a=bufa; // temporary a
1398 decNumber bufb[D2N(DECBUFFER+2)];
1399 decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated
1400 decNumber *b=bufb; // temporary b
1401 decNumber bufw[D2N(10)]; // working 2-10 digit number
1402 decNumber *w=bufw; // ..
1403 #if DECSUBSET
1404 decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
1405 #endif
1406
1407 decContext aset; // working context
1408
1409 #if DECCHECK
1410 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1411 #endif
1412
1413 // Check restrictions; this is a math function; if not violated
1414 // then carry out the operation.
1415 if (!decCheckMath(rhs, set, &status)) do { // protect malloc
1416 #if DECSUBSET
1417 if (!set->extended) {
1418 // reduce operand and set lostDigits status, as needed
1419 if (rhs->digits>set->digits) {
1420 allocrhs=decRoundOperand(rhs, set, &status);
1421 if (allocrhs==NULL) break;
1422 rhs=allocrhs;
1423 }
1424 // special check in subset for rhs=0
1425 if (ISZERO(rhs)) { // +/- zeros -> error
1426 status|=DEC_Invalid_operation;
1427 break;}
1428 } // extended=0
1429 #endif
1430
1431 decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
1432
1433 // handle exact powers of 10; only check if +ve finite
1434 if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1435 Int residue=0; // (no residue)
1436 uInt copystat=0; // clean status
1437
1438 // round to a single digit...
1439 aset.digits=1;
1440 decCopyFit(w, rhs, &aset, &residue, ©stat); // copy & shorten
1441 // if exact and the digit is 1, rhs is a power of 10
1442 if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1443 // the exponent, conveniently, is the power of 10; making
1444 // this the result needs a little care as it might not fit,
1445 // so first convert it into the working number, and then move
1446 // to res
1447 decNumberFromInt32(w, w->exponent);
1448 residue=0;
1449 decCopyFit(res, w, set, &residue, &status); // copy & round
1450 decFinish(res, set, &residue, &status); // cleanup/set flags
1451 break;
1452 } // not a power of 10
1453 } // not a candidate for exact
1454
1455 // simplify the information-content calculation to use 'total
1456 // number of digits in a, including exponent' as compared to the
1457 // requested digits, as increasing this will only rarely cost an
1458 // iteration in ln(a) anyway
1459 t=6; // it can never be >6
1460
1461 // allocate space when needed...
1462 p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1463 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1464 if (needbytes>sizeof(bufa)) { // need malloc space
1465 allocbufa=(decNumber *)malloc(needbytes);
1466 if (allocbufa==NULL) { // hopeless -- abandon
1467 status|=DEC_Insufficient_storage;
1468 break;}
1469 a=allocbufa; // use the allocated space
1470 }
1471 aset.digits=p; // as calculated
1472 aset.emax=DEC_MAX_MATH; // usual bounds
1473 aset.emin=-DEC_MAX_MATH; // ..
1474 aset.clamp=0; // and no concrete format
1475 decLnOp(a, rhs, &aset, &status); // a=ln(rhs)
1476
1477 // skip the division if the result so far is infinite, NaN, or
1478 // zero, or there was an error; note NaN from sNaN needs copy
1479 if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1480 if (a->bits&DECSPECIAL || ISZERO(a)) {
1481 decNumberCopy(res, a); // [will fit]
1482 break;}
1483
1484 // for ln(10) an extra 3 digits of precision are needed
1485 p=set->digits+3;
1486 needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1487 if (needbytes>sizeof(bufb)) { // need malloc space
1488 allocbufb=(decNumber *)malloc(needbytes);
1489 if (allocbufb==NULL) { // hopeless -- abandon
1490 status|=DEC_Insufficient_storage;
1491 break;}
1492 b=allocbufb; // use the allocated space
1493 }
1494 decNumberZero(w); // set up 10...
1495 #if DECDPUN==1
1496 w->lsu[1]=1; w->lsu[0]=0; // ..
1497 #else
1498 w->lsu[0]=10; // ..
1499 #endif
1500 w->digits=2; // ..
1501
1502 aset.digits=p;
1503 decLnOp(b, w, &aset, &ignore); // b=ln(10)
1504
1505 aset.digits=set->digits; // for final divide
1506 decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
1507 } while(0); // [for break]
1508
1509 if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1510 if (allocbufb!=NULL) free(allocbufb); // ..
1511 #if DECSUBSET
1512 if (allocrhs !=NULL) free(allocrhs); // ..
1513 #endif
1514 // apply significant status
1515 if (status!=0) decStatus(res, status, set);
1516 #if DECCHECK
1517 decCheckInexact(res, set);
1518 #endif
1519 return res;
1520 } // decNumberLog10
1521
1522/* ------------------------------------------------------------------ */
1523/* decNumberMax -- compare two Numbers and return the maximum */
1524/* */
1525/* This computes C = A ? B, returning the maximum by 754 rules */
1526/* */
1527/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1528/* lhs is A */
1529/* rhs is B */
1530/* set is the context */
1531/* */
1532/* C must have space for set->digits digits. */
1533/* ------------------------------------------------------------------ */
1534decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1535 const decNumber *rhs, decContext *set) {
1536 uInt status=0; // accumulator
1537 decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1538 if (status!=0) decStatus(res, status, set);
1539 #if DECCHECK
1540 decCheckInexact(res, set);
1541 #endif
1542 return res;
1543 } // decNumberMax
1544
1545/* ------------------------------------------------------------------ */
1546/* decNumberMaxMag -- compare and return the maximum by magnitude */
1547/* */
1548/* This computes C = A ? B, returning the maximum by 754 rules */
1549/* */
1550/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1551/* lhs is A */
1552/* rhs is B */
1553/* set is the context */
1554/* */
1555/* C must have space for set->digits digits. */
1556/* ------------------------------------------------------------------ */
1557decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1558 const decNumber *rhs, decContext *set) {
1559 uInt status=0; // accumulator
1560 decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1561 if (status!=0) decStatus(res, status, set);
1562 #if DECCHECK
1563 decCheckInexact(res, set);
1564 #endif
1565 return res;
1566 } // decNumberMaxMag
1567
1568/* ------------------------------------------------------------------ */
1569/* decNumberMin -- compare two Numbers and return the minimum */
1570/* */
1571/* This computes C = A ? B, returning the minimum by 754 rules */
1572/* */
1573/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1574/* lhs is A */
1575/* rhs is B */
1576/* set is the context */
1577/* */
1578/* C must have space for set->digits digits. */
1579/* ------------------------------------------------------------------ */
1580decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1581 const decNumber *rhs, decContext *set) {
1582 uInt status=0; // accumulator
1583 decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1584 if (status!=0) decStatus(res, status, set);
1585 #if DECCHECK
1586 decCheckInexact(res, set);
1587 #endif
1588 return res;
1589 } // decNumberMin
1590
1591/* ------------------------------------------------------------------ */
1592/* decNumberMinMag -- compare and return the minimum by magnitude */
1593/* */
1594/* This computes C = A ? B, returning the minimum by 754 rules */
1595/* */
1596/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
1597/* lhs is A */
1598/* rhs is B */
1599/* set is the context */
1600/* */
1601/* C must have space for set->digits digits. */
1602/* ------------------------------------------------------------------ */
1603decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1604 const decNumber *rhs, decContext *set) {
1605 uInt status=0; // accumulator
1606 decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1607 if (status!=0) decStatus(res, status, set);
1608 #if DECCHECK
1609 decCheckInexact(res, set);
1610 #endif
1611 return res;
1612 } // decNumberMinMag
1613
1614/* ------------------------------------------------------------------ */
1615/* decNumberMinus -- prefix minus operator */
1616/* */
1617/* This computes C = 0 - A */
1618/* */
1619/* res is C, the result. C may be A */
1620/* rhs is A */
1621/* set is the context */
1622/* */
1623/* See also decNumberCopyNegate for a quiet bitwise version of this. */
1624/* C must have space for set->digits digits. */
1625/* ------------------------------------------------------------------ */
1626/* Simply use AddOp for the subtract, which will do the necessary. */
1627/* ------------------------------------------------------------------ */
1628decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1629 decContext *set) {
1630 decNumber dzero;
1631 uInt status=0; // accumulator
1632
1633 #if DECCHECK
1634 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1635 #endif
1636
1637 decNumberZero(&dzero); // make 0
1638 dzero.exponent=rhs->exponent; // [no coefficient expansion]
1639 decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1640 if (status!=0) decStatus(res, status, set);
1641 #if DECCHECK
1642 decCheckInexact(res, set);
1643 #endif
1644 return res;
1645 } // decNumberMinus
1646
1647/* ------------------------------------------------------------------ */
1648/* decNumberNextMinus -- next towards -Infinity */
1649/* */
1650/* This computes C = A - infinitesimal, rounded towards -Infinity */
1651/* */
1652/* res is C, the result. C may be A */
1653/* rhs is A */
1654/* set is the context */
1655/* */
1656/* This is a generalization of 754 NextDown. */
1657/* ------------------------------------------------------------------ */
1658decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1659 decContext *set) {
1660 decNumber dtiny; // constant
1661 decContext workset=*set; // work
1662 uInt status=0; // accumulator
1663 #if DECCHECK
1664 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1665 #endif
1666
1667 // +Infinity is the special case
1668 if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1669 decSetMaxValue(res, set); // is +ve
1670 // there is no status to set
1671 return res;
1672 }
1673 decNumberZero(&dtiny); // start with 0
1674 dtiny.lsu[0]=1; // make number that is ..
1675 dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
1676 workset.round=DEC_ROUND_FLOOR;
1677 decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1678 status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please
1679 if (status!=0) decStatus(res, status, set);
1680 return res;
1681 } // decNumberNextMinus
1682
1683/* ------------------------------------------------------------------ */
1684/* decNumberNextPlus -- next towards +Infinity */
1685/* */
1686/* This computes C = A + infinitesimal, rounded towards +Infinity */
1687/* */
1688/* res is C, the result. C may be A */
1689/* rhs is A */
1690/* set is the context */
1691/* */
1692/* This is a generalization of 754 NextUp. */
1693/* ------------------------------------------------------------------ */
1694decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1695 decContext *set) {
1696 decNumber dtiny; // constant
1697 decContext workset=*set; // work
1698 uInt status=0; // accumulator
1699 #if DECCHECK
1700 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1701 #endif
1702
1703 // -Infinity is the special case
1704 if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1705 decSetMaxValue(res, set);
1706 res->bits=DECNEG; // negative
1707 // there is no status to set
1708 return res;
1709 }
1710 decNumberZero(&dtiny); // start with 0
1711 dtiny.lsu[0]=1; // make number that is ..
1712 dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
1713 workset.round=DEC_ROUND_CEILING;
1714 decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1715 status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please
1716 if (status!=0) decStatus(res, status, set);
1717 return res;
1718 } // decNumberNextPlus
1719
1720/* ------------------------------------------------------------------ */
1721/* decNumberNextToward -- next towards rhs */
1722/* */
1723/* This computes C = A +/- infinitesimal, rounded towards */
1724/* +/-Infinity in the direction of B, as per 754-1985 nextafter */
1725/* modified during revision but dropped from 754-2008. */
1726/* */
1727/* res is C, the result. C may be A or B. */
1728/* lhs is A */
1729/* rhs is B */
1730/* set is the context */
1731/* */
1732/* This is a generalization of 754-1985 NextAfter. */
1733/* ------------------------------------------------------------------ */
1734decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1735 const decNumber *rhs, decContext *set) {
1736 decNumber dtiny; // constant
1737 decContext workset=*set; // work
1738 Int result; // ..
1739 uInt status=0; // accumulator
1740 #if DECCHECK
1741 if (decCheckOperands(res, lhs, rhs, set)) return res;
1742 #endif
1743
1744 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1745 decNaNs(res, lhs, rhs, set, &status);
1746 }
1747 else { // Is numeric, so no chance of sNaN Invalid, etc.
1748 result=decCompare(lhs, rhs, 0); // sign matters
1749 if (result==BADINT) status|=DEC_Insufficient_storage; // rare
1750 else { // valid compare
1751 if (result==0) decNumberCopySign(res, lhs, rhs); // easy
1752 else { // differ: need NextPlus or NextMinus
1753 uByte sub; // add or subtract
1754 if (result<0) { // lhs<rhs, do nextplus
1755 // -Infinity is the special case
1756 if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1757 decSetMaxValue(res, set);
1758 res->bits=DECNEG; // negative
1759 return res; // there is no status to set
1760 }
1761 workset.round=DEC_ROUND_CEILING;
1762 sub=0; // add, please
1763 } // plus
1764 else { // lhs>rhs, do nextminus
1765 // +Infinity is the special case
1766 if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1767 decSetMaxValue(res, set);
1768 return res; // there is no status to set
1769 }
1770 workset.round=DEC_ROUND_FLOOR;
1771 sub=DECNEG; // subtract, please
1772 } // minus
1773 decNumberZero(&dtiny); // start with 0
1774 dtiny.lsu[0]=1; // make number that is ..
1775 dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest
1776 decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
1777 // turn off exceptions if the result is a normal number
1778 // (including Nmin), otherwise let all status through
1779 if (decNumberIsNormal(res, set)) status=0;
1780 } // unequal
1781 } // compare OK
1782 } // numeric
1783 if (status!=0) decStatus(res, status, set);
1784 return res;
1785 } // decNumberNextToward
1786
1787/* ------------------------------------------------------------------ */
1788/* decNumberOr -- OR two Numbers, digitwise */
1789/* */
1790/* This computes C = A | B */
1791/* */
1792/* res is C, the result. C may be A and/or B (e.g., X=X|X) */
1793/* lhs is A */
1794/* rhs is B */
1795/* set is the context (used for result length and error report) */
1796/* */
1797/* C must have space for set->digits digits. */
1798/* */
1799/* Logical function restrictions apply (see above); a NaN is */
1800/* returned with Invalid_operation if a restriction is violated. */
1801/* ------------------------------------------------------------------ */
1802decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1803 const decNumber *rhs, decContext *set) {
1804 const Unit *ua, *ub; // -> operands
1805 const Unit *msua, *msub; // -> operand msus
1806 Unit *uc, *msuc; // -> result and its msu
1807 Int msudigs; // digits in res msu
1808 #if DECCHECK
1809 if (decCheckOperands(res, lhs, rhs, set)) return res;
1810 #endif
1811
1812 if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1813 || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1814 decStatus(res, DEC_Invalid_operation, set);
1815 return res;
1816 }
1817 // operands are valid
1818 ua=lhs->lsu; // bottom-up
1819 ub=rhs->lsu; // ..
1820 uc=res->lsu; // ..
1821 msua=ua+D2U(lhs->digits)-1; // -> msu of lhs
1822 msub=ub+D2U(rhs->digits)-1; // -> msu of rhs
1823 msuc=uc+D2U(set->digits)-1; // -> msu of result
1824 msudigs=MSUDIGITS(set->digits); // [faster than remainder]
1825 for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop
1826 Unit a, b; // extract units
1827 if (ua>msua) a=0;
1828 else a=*ua;
1829 if (ub>msub) b=0;
1830 else b=*ub;
1831 *uc=0; // can now write back
1832 if (a|b) { // maybe 1 bits to examine
1833 Int i, j;
1834 // This loop could be unrolled and/or use BIN2BCD tables
1835 for (i=0; i<DECDPUN; i++) {
1836 if ((a|b)&1) *uc=*uc+(Unit)powers[i]; // effect OR
1837 j=a%10;
1838 a=a/10;
1839 j|=b%10;
1840 b=b/10;
1841 if (j>1) {
1842 decStatus(res, DEC_Invalid_operation, set);
1843 return res;
1844 }
1845 if (uc==msuc && i==msudigs-1) break; // just did final digit
1846 } // each digit
1847 } // non-zero
1848 } // each unit
1849 // [here uc-1 is the msu of the result]
1850 res->digits=decGetDigits(res->lsu, uc-res->lsu);
1851 res->exponent=0; // integer
1852 res->bits=0; // sign=0
1853 return res; // [no status to set]
1854 } // decNumberOr
1855
1856/* ------------------------------------------------------------------ */
1857/* decNumberPlus -- prefix plus operator */
1858/* */
1859/* This computes C = 0 + A */
1860/* */
1861/* res is C, the result. C may be A */
1862/* rhs is A */
1863/* set is the context */
1864/* */
1865/* See also decNumberCopy for a quiet bitwise version of this. */
1866/* C must have space for set->digits digits. */
1867/* ------------------------------------------------------------------ */
1868/* This simply uses AddOp; Add will take fast path after preparing A. */
1869/* Performance is a concern here, as this routine is often used to */
1870/* check operands and apply rounding and overflow/underflow testing. */
1871/* ------------------------------------------------------------------ */
1872decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1873 decContext *set) {
1874 decNumber dzero;
1875 uInt status=0; // accumulator
1876 #if DECCHECK
1877 if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1878 #endif
1879
1880 decNumberZero(&dzero); // make 0
1881 dzero.exponent=rhs->exponent; // [no coefficient expansion]
1882 decAddOp(res, &dzero, rhs, set, 0, &status);
1883 if (status!=0) decStatus(res, status, set);
1884 #if DECCHECK
1885 decCheckInexact(res, set);
1886 #endif
1887 return res;
1888 } // decNumberPlus
1889
1890/* ------------------------------------------------------------------ */
1891/* decNumberMultiply -- multiply two Numbers */
1892/* */
1893/* This computes C = A x B */
1894/* */
1895/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
1896/* lhs is A */
1897/* rhs is B */
1898/* set is the context */
1899/* */
1900/* C must have space for set->digits digits. */
1901/* ------------------------------------------------------------------ */
1902decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1903 const decNumber *rhs, decContext *set) {
1904 uInt status=0; // accumulator
1905 decMultiplyOp(res, lhs, rhs, set, &status);
1906 if (status!=0) decStatus(res, status, set);
1907 #if DECCHECK
1908 decCheckInexact(res, set);
1909 #endif
1910 return res;
1911 } // decNumberMultiply
1912
1913/* ------------------------------------------------------------------ */
1914/* decNumberPower -- raise a number to a power */
1915/* */
1916/* This computes C = A ** B */
1917/* */
1918/* res is C, the result. C may be A and/or B (e.g., X=X**X) */
1919/* lhs is A */
1920/* rhs is B */
1921/* set is the context */
1922/* */
1923/* C must have space for set->digits digits. */
1924/* */
1925/* Mathematical function restrictions apply (see above); a NaN is */
1926/* returned with Invalid_operation if a restriction is violated. */
1927/* */
1928/* However, if 1999999997<=B<=999999999 and B is an integer then the */
1929/* restrictions on A and the context are relaxed to the usual bounds, */
1930/* for compatibility with the earlier (integer power only) version */
1931/* of this function. */
1932/* */
1933/* When B is an integer, the result may be exact, even if rounded. */
1934/* */
1935/* The final result is rounded according to the context; it will */
1936/* almost always be correctly rounded, but may be up to 1 ulp in */
1937/* error in rare cases. */
1938/* ------------------------------------------------------------------ */
1939decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1940 const decNumber *rhs, decContext *set) {
1941 #if DECSUBSET
1942 decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated
1943 decNumber *allocrhs=NULL; // .., rhs
1944 #endif
1945 decNumber *allocdac=NULL; // -> allocated acc buffer, iff used
1946 decNumber *allocinv=NULL; // -> allocated 1/x buffer, iff used
1947 Int reqdigits=set->digits; // requested DIGITS
1948 Int n; // rhs in binary
1949 Flag rhsint=0; // 1 if rhs is an integer
1950 Flag useint=0; // 1 if can use integer calculation
1951 Flag isoddint=0; // 1 if rhs is an integer and odd
1952 Int i; // work
1953 #if DECSUBSET
1954 Int dropped; // ..
1955 #endif
1956 uInt needbytes; // buffer size needed
1957 Flag seenbit; // seen a bit while powering
1958 Int residue=0; // rounding residue
1959 uInt status=0; // accumulators
1960 uByte bits=0; // result sign if errors
1961 decContext aset; // working context
1962 decNumber dnOne; // work value 1...
1963 // local accumulator buffer [a decNumber, with digits+elength+1 digits]
1964 decNumber dacbuff[D2N(DECBUFFER+9)];
1965 decNumber *dac=dacbuff; // -> result accumulator
1966 // same again for possible 1/lhs calculation
1967 decNumber invbuff[D2N(DECBUFFER+9)];
1968
1969 #if DECCHECK
1970 if (decCheckOperands(res, lhs, rhs, set)) return res;
1971 #endif
1972
1973 do { // protect allocated storage
1974 #if DECSUBSET
1975 if (!set->extended) { // reduce operands and set status, as needed
1976 if (lhs->digits>reqdigits) {
1977 alloclhs=decRoundOperand(lhs, set, &status);
1978 if (alloclhs==NULL) break;
1979 lhs=alloclhs;
1980 }
1981 if (rhs->digits>reqdigits) {
1982 allocrhs=decRoundOperand(rhs, set, &status);
1983 if (allocrhs==NULL) break;
1984 rhs=allocrhs;
1985 }
1986 }
1987 #endif
1988 // [following code does not require input rounding]
1989
1990 // handle NaNs and rhs Infinity (lhs infinity is harder)
1991 if (SPECIALARGS) {
1992 if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
1993 decNaNs(res, lhs, rhs, set, &status);
1994 break;}
1995 if (decNumberIsInfinite(rhs)) { // rhs Infinity
1996 Flag rhsneg=rhs->bits&DECNEG; // save rhs sign
1997 if (decNumberIsNegative(lhs) // lhs<0
1998 && !decNumberIsZero(lhs)) // ..
1999 status|=DEC_Invalid_operation;
2000 else { // lhs >=0
The first 2,000 of 8,143 lines.