Coverage Report

Created: 2025-11-29 06:11

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