Coverage Report

Created: 2025-08-03 06:43

/src/tarantool/third_party/decNumber/decNumber.c
Line
Count
Source (jump to first uncovered line)
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 <string.h>                // for strcpy
166
#include <stdlib.h>                // for malloc, free, etc.
167
#include <stdio.h>                 // for printf [if needed]
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
82.4k
#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
0
#define COMPARE     0x01           // Compare operators
185
0
#define COMPMAX     0x02           // ..
186
0
#define COMPMIN     0x03           // ..
187
0
#define COMPTOTAL   0x04           // ..
188
0
#define COMPNAN     0x05           // .. [NaN processing]
189
0
#define COMPSIG     0x06           // .. [signaling COMPARE]
190
0
#define COMPMAXMAG  0x07           // ..
191
0
#define COMPMINMAG  0x08           // ..
192
193
231
#define DEC_sNaN     0x40000000    // local status: sNaN signal
194
36
#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
2.30k
  #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
40.3k
  #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
1.87k
#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
1.87k
#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 * decNumberFromInt64(decNumber *dn, Long in) {
348
0
  uLong unsig;
349
0
  if (in>=0) unsig=in;
350
0
   else unsig=-(uLong)in;
351
0
  decNumberFromUInt64(dn, unsig);
352
0
  if (in<0) dn->bits=DECNEG;
353
0
  return dn;
354
0
  } // decNumberFromInt64
355
356
0
decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
357
0
  Unit *up;                             // work pointer
358
0
  decNumberZero(dn);                    // clean
359
0
  if (uin==0) return dn;                // [or decGetDigits bad call]
360
0
  for (up=dn->lsu; uin>0; up++) {
361
0
    *up=(Unit)(uin%(DECDPUNMAX+1));
362
0
    uin=uin/(DECDPUNMAX+1);
363
0
    }
364
0
  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
365
0
  return dn;
366
0
  } // decNumberFromUInt32
367
368
0
decNumber * decNumberFromUInt64(decNumber *dn, uLong uin) {
369
0
  Unit *up;
370
0
  decNumberZero(dn);
371
0
  if (uin == 0) return dn;
372
0
  for (up=dn->lsu; uin>0; up++) {
373
0
    *up=(Unit)(uin%(DECDPUNMAX+1));
374
0
    uin=uin/(DECDPUNMAX+1);
375
0
    }
376
0
  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
377
0
  return dn;
378
0
  } // decNumberFromUInt64
379
380
/* ------------------------------------------------------------------ */
381
/* to-int32 -- conversion to Int or uInt                              */
382
/*                                                                    */
383
/*  dn is the decNumber to convert                                    */
384
/*  set is the context for reporting errors                           */
385
/*  returns the converted decNumber, or 0 if Invalid is set           */
386
/*                                                                    */
387
/* Invalid is set if the decNumber does not have exponent==0 or if    */
388
/* it is a NaN, Infinite, or out-of-range.                            */
389
/* ------------------------------------------------------------------ */
390
0
Int decNumberToInt32(const decNumber *dn, decContext *set) {
391
  #if DECCHECK
392
  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
393
  #endif
394
395
  // special or too many digits, or bad exponent
396
0
  if ((dn->bits&DECSPECIAL) || dn->digits>10 || dn->exponent!=0){;} // bad
397
0
   else { // is a finite integer with 10 or fewer digits
398
0
    Int d;                         // work
399
0
    const Unit *up;                // ..
400
0
    uInt hi=0, lo;                 // ..
401
0
    up=dn->lsu;                    // -> lsu
402
0
    lo=*up;                        // get 1 to 9 digits
403
0
    #if DECDPUN>1                  // split to higher
404
0
      hi=lo/10;
405
0
      lo=lo%10;
406
0
    #endif
407
0
    up++;
408
    // collect remaining Units, if any, into hi
409
0
    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
410
    // now low has the lsd, hi the remainder
411
0
    if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
412
      // most-negative is a reprieve
413
0
      if ((dn->bits&DECNEG) && hi==214748364 && lo==8) return 0x80000000;
414
      // bad -- drop through
415
0
      }
416
0
     else { // in-range always
417
0
      Int i=X10(hi)+lo;
418
0
      if (dn->bits&DECNEG) return -i;
419
0
      return i;
420
0
      }
421
0
    } // integer
422
0
  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
423
0
  return 0;
424
0
  } // decNumberToInt32
425
426
0
Long decNumberToInt64(const decNumber *dn, decContext *set) {
427
0
  if (dn->bits&DECSPECIAL || dn->digits>19 || dn->exponent!=0) ;
428
0
   else {
429
0
    Int d;
430
0
    const Unit *up;
431
0
    uLong hi=0, lo;
432
0
    up=dn->lsu;
433
0
    lo=*up;
434
0
    #if DECDPUN>1
435
0
      hi=lo/10;
436
0
      lo=lo%10;
437
0
    #endif
438
0
    up++;
439
0
    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*bigpowers[d-1];
440
0
    if (hi>922337203685477580 || (hi==922337203685477580 && lo>7)) {
441
0
      if (dn->bits&DECNEG && hi==922337203685477580 && lo==8) return 0x8000000000000000;
442
0
      }
443
0
    else {
444
0
      Long i=X10(hi)+lo;
445
0
      if (dn->bits&DECNEG) return -i;
446
0
      return i;
447
0
      }
448
0
    }
449
0
  decContextSetStatus(set, DEC_Invalid_operation);
450
0
  return 0;
451
0
  } // decNumberToInt64
452
453
0
uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
454
  #if DECCHECK
455
  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
456
  #endif
457
  // special or too many digits, or bad exponent, or negative (<0)
458
0
  if ((dn->bits&DECSPECIAL) || dn->digits>10 || dn->exponent!=0
459
0
    || ((dn->bits&DECNEG) && !ISZERO(dn))){;}               // bad
460
0
   else { // is a finite integer with 10 or fewer digits
461
0
    Int d;                         // work
462
0
    const Unit *up;                // ..
463
0
    uInt hi=0, lo;                 // ..
464
0
    up=dn->lsu;                    // -> lsu
465
0
    lo=*up;                        // get 1 to 9 digits
466
0
    #if DECDPUN>1                  // split to higher
467
0
      hi=lo/10;
468
0
      lo=lo%10;
469
0
    #endif
470
0
    up++;
471
    // collect remaining Units, if any, into hi
472
0
    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
473
474
    // now low has the lsd, hi the remainder
475
0
    if (hi>429496729 || (hi==429496729 && lo>5)){;} // no reprieve possible
476
0
     else return X10(hi)+lo;
477
0
    } // integer
478
0
  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
479
0
  return 0;
480
0
  } // decNumberToUInt32
481
482
0
uLong decNumberToUInt64(const decNumber *dn, decContext *set) {
483
0
  if (dn->bits&DECSPECIAL || dn->digits>20 || dn->exponent!=0
484
0
    || (dn->bits&DECNEG && !ISZERO(dn)));
485
0
   else {
486
0
    Int d;
487
0
    const Unit *up;
488
0
    uLong hi=0, lo;
489
0
    up=dn->lsu;
490
0
    lo=*up;
491
0
    #if DECDPUN>1
492
0
      hi=lo/10;
493
0
      lo=lo%10;
494
0
    #endif
495
0
    up++;
496
0
    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*bigpowers[d-1];
497
0
    if (hi>1844674407370955161 || (hi==1844674407370955161 && lo>5)) ;
498
0
     else return X10(hi)+lo;
499
0
    }
500
0
  decContextSetStatus(set, DEC_Invalid_operation);
501
0
  return 0;
502
0
  }  // decNumberToUInt64
503
504
0
int32_t decNumberIsInt(const decNumber *dn) {
505
0
  const Unit *up=dn->lsu;
506
0
  if (dn->exponent>=0) {
507
0
    return 1;
508
0
    }
509
0
   else {
510
0
    Int count=-dn->exponent;
511
    // spin up whole units until reach the Unit with the unit digit
512
0
    for (; count>=DECDPUN; up++) {
513
0
      if (*up!=0) return 0;
514
0
      count-=DECDPUN;
515
0
      }
516
0
    if (count==0) return 1;             // [a multiple of DECDPUN]
517
0
     else {                             // [not multiple of DECDPUN]
518
0
      Int rem;                          // work
519
      // slice off fraction digits and check for non-zero
520
0
      #if DECDPUN<=4
521
0
        rem=*up-QUOT10(*up, count)*powers[count];
522
      #else
523
        rem=*up%powers[count];          // slice off discards
524
      #endif
525
0
      if (rem!=0) return 0;
526
0
      }
527
0
    }
528
0
    return 1;
529
0
  }  // decNumberIsInt
530
531
/* ------------------------------------------------------------------ */
532
/* to-scientific-string -- conversion to numeric string               */
533
/* to-engineering-string -- conversion to numeric string              */
534
/*                                                                    */
535
/*   decNumberToString(dn, string);                                   */
536
/*   decNumberToEngString(dn, string);                                */
537
/*                                                                    */
538
/*  dn is the decNumber to convert                                    */
539
/*  string is the string where the result will be laid out            */
540
/*                                                                    */
541
/*  string must be at least dn->digits+14 characters long             */
542
/*                                                                    */
543
/*  No error is possible, and no status can be set.                   */
544
/* ------------------------------------------------------------------ */
545
0
char * decNumberToString(const decNumber *dn, char *string){
546
0
  decToString(dn, string, 0);
547
0
  return string;
548
0
  } // DecNumberToString
549
550
0
char * decNumberToEngString(const decNumber *dn, char *string){
551
0
  decToString(dn, string, 1);
552
0
  return string;
553
0
  } // DecNumberToEngString
554
555
/* ------------------------------------------------------------------ */
556
/* to-number -- conversion from numeric string                        */
557
/*                                                                    */
558
/* decNumberFromString -- convert string to decNumber                 */
559
/*   dn        -- the number structure to fill                        */
560
/*   chars[]   -- the string to convert ('\0' terminated)             */
561
/*   set       -- the context used for processing any error,          */
562
/*                determining the maximum precision available         */
563
/*                (set.digits), determining the maximum and minimum   */
564
/*                exponent (set.emax and set.emin), determining if    */
565
/*                extended values are allowed, and checking the       */
566
/*                rounding mode if overflow occurs or rounding is     */
567
/*                needed.                                             */
568
/*                                                                    */
569
/* The length of the coefficient and the size of the exponent are     */
570
/* checked by this routine, so the correct error (Underflow or        */
571
/* Overflow) can be reported or rounding applied, as necessary.       */
572
/*                                                                    */
573
/* If bad syntax is detected, the result will be a quiet NaN.         */
574
/* ------------------------------------------------------------------ */
575
const char * decNumberFromString(decNumber *dn, const char chars[],
576
8.12k
                                 decContext *set) {
577
8.12k
  Int   exponent=0;                // working exponent [assume 0]
578
8.12k
  uByte bits=0;                    // working flags [assume +ve]
579
8.12k
  Unit  *res;                      // where result will be built
580
8.12k
  Unit  resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
581
                                   // [+9 allows for ln() constants]
582
8.12k
  Unit  *allocres=NULL;            // -> allocated result, iff allocated
583
8.12k
  Int   d=0;                       // count of digits found in decimal part
584
8.12k
  const char *dotchar=NULL;        // where dot was found
585
8.12k
  const char *cfirst=chars;        // -> first character of decimal part
586
8.12k
  const char *last=NULL;           // -> last digit of decimal part
587
8.12k
  const char *end=chars;
588
8.12k
  const char *c;                   // work
589
8.12k
  Unit  *up;                       // ..
590
8.12k
  #if DECDPUN>1
591
8.12k
  Int   cut, out;                  // ..
592
8.12k
  #endif
593
8.12k
  Int   residue;                   // rounding residue
594
8.12k
  uInt  status=0;                  // error code
595
596
  #if DECCHECK
597
  if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
598
    return decNumberZero(dn);
599
  #endif
600
601
8.12k
  do {                             // status & malloc protection
602
10.3M
    for (c=chars;; c++) {          // -> input character
603
10.3M
      if (*c>='0' && *c<='9') {    // test for Arabic digit
604
10.3M
        last=c;
605
10.3M
        d++;                       // count of real digits
606
10.3M
        continue;                  // still in decimal part
607
10.3M
        }
608
15.2k
      if (*c=='.' && dotchar==NULL) { // first '.'
609
7.08k
        dotchar=c;                 // record offset into decimal part
610
7.08k
        if (c==cfirst) cfirst++;   // first digit must follow
611
7.08k
        continue;}
612
8.12k
      if (c==chars) {              // first in string...
613
259
        if (*c=='-') {             // valid - sign
614
1
          cfirst++;
615
1
          bits=DECNEG;
616
1
          continue;}
617
258
        if (*c=='+') {             // valid + sign
618
2
          cfirst++;
619
2
          continue;}
620
258
        }
621
      // *c is not a digit, or a valid +, -, or '.'
622
8.12k
      break;
623
8.12k
      } // c
624
625
8.12k
    if (last==NULL) {              // no digits yet
626
262
      status=DEC_Conversion_syntax;// assume the worst
627
262
      if (*c=='\0') break;         // and no more to come...
628
      #if DECSUBSET
629
      // if subset then infinities and NaNs are not allowed
630
      if (!set->extended) break;   // hopeless
631
      #endif
632
      // Infinities and NaNs are possible, here
633
257
      if (dotchar!=NULL) break;    // .. unless had a dot
634
255
      decNumberZero(dn);           // be optimistic
635
255
      if (decBiStr(c, "infinity", "INFINITY")
636
255
       || decBiStr(c, "inf", "INF")) {
637
3
        dn->bits=bits | DECINF;
638
3
        status=0;                  // is OK
639
3
        break; // all done
640
3
        }
641
      // a NaN expected
642
      // 2003.09.10 NaNs are now permitted to have a sign
643
252
      dn->bits=bits | DECNAN;      // assume simple NaN
644
252
      if (*c=='s' || *c=='S') {    // looks like an sNaN
645
3
        c++;
646
3
        dn->bits=bits | DECSNAN;
647
3
        }
648
252
      if (*c!='n' && *c!='N') break;    // check caseless "NaN"
649
174
      c++;
650
174
      if (*c!='a' && *c!='A') break;    // ..
651
145
      c++;
652
145
      if (*c!='n' && *c!='N') break;    // ..
653
118
      c++;
654
      // now either nothing, or nnnn payload, expected
655
      // -> start of integer and skip leading 0s [including plain 0]
656
312
      for (cfirst=c; *cfirst=='0';) cfirst++;
657
118
      if (*cfirst=='\0') {         // "NaN" or "sNaN", maybe with all 0s
658
10
        status=0;                  // it's good
659
10
        break;                     // ..
660
10
        }
661
      // something other than 0s; setup last and d as usual [no dots]
662
5.71M
      for (c=cfirst;; c++, d++) {
663
5.71M
        if (*c<'0' || *c>'9') break; // test for Arabic digit
664
5.71M
        last=c;
665
5.71M
        }
666
108
      if (*c!='\0') break;         // not all digits
667
82
      if (d>set->digits-1) {
668
        // [NB: payload in a decNumber can be full length unless
669
        // clamped, in which case can only be digits-1]
670
65
        if (set->clamp) break;
671
65
        if (d>set->digits) break;
672
65
        } // too many digits?
673
      // good; drop through to convert the integer to coefficient
674
18
      status=0;                    // syntax is OK
675
18
      bits=dn->bits;               // for copy-back
676
18
      } // last==NULL
677
678
7.86k
     else if (*c!='\0') {          // more to process...
679
      // had some digits; exponent is only valid sequence now
680
681
      status=0;                    // we have a number already
681
681
      end=c;                       // backup for invalid exponent
682
681
      Flag nege;                   // 1=negative exponent
683
681
      const char *firstexp;        // -> first significant exponent digit
684
681
      if (*c!='e' && *c!='E') goto finalize;
685
      /* Found 'e' or 'E' -- now process explicit exponent */
686
      // 1998.07.11: sign no longer required
687
646
      nege=0;
688
646
      c++;                         // to (possible) sign
689
646
      if (*c=='-') {nege=1; c++;}
690
247
       else if (*c=='+') c++;
691
646
      if (*c<'0' || *c>'9') goto finalize;
692
693
1.00k
      for (; *c=='0' && *(c+1)!='\0';) c++;  // strip insignificant zeros
694
610
      firstexp=c;                            // save exponent digit place
695
4.54k
      for (; ;c++) {
696
4.54k
        if (*c<'0' || *c>'9') break;         // not a digit
697
3.93k
        exponent=X10(exponent)+(Int)*c-(Int)'0';
698
3.93k
        } // c
699
700
610
      end=c;
701
702
      // (this next test must be after the syntax checks)
703
      // if it was too long the exponent may have wrapped, so check
704
      // carefully and set it to a certain overflow if wrap possible
705
610
      if (c>=firstexp+9+1) {
706
15
        if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
707
        // [up to 1999999999 is OK, for example 1E-1000000998]
708
15
        }
709
610
      if (nege) exponent=-exponent;     // was negative
710
610
      } // stuff after digits
711
712
7.18k
      else end=c;
713
7.88k
finalize:
714
    // Here when whole string has been inspected; syntax is good
715
    // cfirst->first digit (never dot), last->last digit (ditto)
716
717
    // strip leading zeros/dot [leave final 0 if all 0's]
718
7.88k
    if (*cfirst=='0') {                 // [cfirst has stepped over .]
719
26.9k
      for (c=cfirst; c<last; c++, cfirst++) {
720
23.5k
        if (*c=='.') continue;          // ignore dots
721
20.0k
        if (*c!='0') break;             // non-zero found
722
19.6k
        d--;                            // 0 stripped
723
19.6k
        } // c
724
      #if DECSUBSET
725
      // make a rapid exit for easy zeros if !extended
726
      if (*cfirst=='0' && !set->extended) {
727
        decNumberZero(dn);              // clean result
728
        break;                          // [could be return]
729
        }
730
      #endif
731
3.70k
      } // at least one leading 0
732
733
    // Handle decimal point...
734
7.88k
    if (dotchar!=NULL && dotchar<last)  // non-trailing '.' found?
735
7.07k
      exponent-=(last-dotchar);         // adjust exponent
736
    // [we can now ignore the .]
737
738
    // OK, the digits string is good.  Assemble in the decNumber, or in
739
    // a temporary units array if rounding is needed
740
7.88k
    if (d<=set->digits) res=dn->lsu;    // fits into supplied decNumber
741
3.59k
     else {                             // rounding needed
742
3.59k
      Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
743
3.59k
      res=resbuff;                      // assume use local buffer
744
3.59k
      if (needbytes>(Int)sizeof(resbuff)) { // too big for local
745
3.59k
        allocres=(Unit *)malloc(needbytes);
746
3.59k
        if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
747
3.59k
        res=allocres;
748
3.59k
        }
749
3.59k
      }
750
    // res now -> number lsu, buffer, or allocated storage for Unit array
751
752
    // Place the coefficient into the selected Unit array
753
    // [this is often 70% of the cost of this function when DECDPUN>1]
754
7.88k
    #if DECDPUN>1
755
7.88k
    out=0;                         // accumulator
756
7.88k
    up=res+D2U(d)-1;               // -> msu
757
7.88k
    cut=d-(up-res)*DECDPUN;        // digits in top unit
758
10.3M
    for (c=cfirst;; c++) {         // along the digits
759
10.3M
      if (*c=='.') continue;       // ignore '.' [don't decrement cut]
760
10.3M
      out=X10(out)+(Int)*c-(Int)'0';
761
10.3M
      if (c==last) break;          // done [never get to trailing '.']
762
10.3M
      cut--;
763
10.3M
      if (cut>0) continue;         // more for this unit
764
3.43M
      *up=(Unit)out;               // write unit
765
3.43M
      up--;                        // prepare for unit below..
766
3.43M
      cut=DECDPUN;                 // ..
767
3.43M
      out=0;                       // ..
768
3.43M
      } // c
769
7.88k
    *up=(Unit)out;                 // write lsu
770
771
    #else
772
    // DECDPUN==1
773
    up=res;                        // -> lsu
774
    for (c=last; c>=cfirst; c--) { // over each character, from least
775
      if (*c=='.') continue;       // ignore . [don't step up]
776
      *up=(Unit)((Int)*c-(Int)'0');
777
      up++;
778
      } // c
779
    #endif
780
781
7.88k
    dn->bits=bits;
782
7.88k
    dn->exponent=exponent;
783
7.88k
    dn->digits=d;
784
785
    // if not in number (too long) shorten into the number
786
7.88k
    if (d>set->digits) {
787
3.59k
      residue=0;
788
3.59k
      decSetCoeff(dn, set, res, d, &residue, &status);
789
      // always check for overflow or subnormal and round as needed
790
3.59k
      decFinalize(dn, set, &residue, &status);
791
3.59k
      }
792
4.28k
     else { // no rounding, but may still have overflow or subnormal
793
      // [these tests are just for performance; finalize repeats them]
794
4.28k
      if ((dn->exponent-1<set->emin-dn->digits)
795
4.28k
       || (dn->exponent-1>set->emax-set->digits)) {
796
400
        residue=0;
797
400
        decFinalize(dn, set, &residue, &status);
798
400
        }
799
4.28k
      }
800
    // decNumberShow(dn);
801
7.88k
    } while(0);                         // [for break]
802
803
8.12k
  if (allocres!=NULL) free(allocres);   // drop any storage used
804
8.12k
  if (status!=0) decStatus(dn, status, set);
805
8.12k
  return end;
806
8.12k
  } /* decNumberFromString */
807
808
/* ================================================================== */
809
/* Operators                                                          */
810
/* ================================================================== */
811
812
/* ------------------------------------------------------------------ */
813
/* decNumberAbs -- absolute value operator                            */
814
/*                                                                    */
815
/*   This computes C = abs(A)                                         */
816
/*                                                                    */
817
/*   res is C, the result.  C may be A                                */
818
/*   rhs is A                                                         */
819
/*   set is the context                                               */
820
/*                                                                    */
821
/* See also decNumberCopyAbs for a quiet bitwise version of this.     */
822
/* C must have space for set->digits digits.                          */
823
/* ------------------------------------------------------------------ */
824
/* This has the same effect as decNumberPlus unless A is negative,    */
825
/* in which case it has the same effect as decNumberMinus.            */
826
/* ------------------------------------------------------------------ */
827
decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
828
0
                         decContext *set) {
829
0
  decNumber dzero;                      // for 0
830
0
  uInt status=0;                        // accumulator
831
832
  #if DECCHECK
833
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
834
  #endif
835
836
0
  decNumberZero(&dzero);                // set 0
837
0
  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
838
0
  decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
839
0
  if (status!=0) decStatus(res, status, set);
840
  #if DECCHECK
841
  decCheckInexact(res, set);
842
  #endif
843
0
  return res;
844
0
  } // decNumberAbs
845
846
/* ------------------------------------------------------------------ */
847
/* decNumberAdd -- add two Numbers                                    */
848
/*                                                                    */
849
/*   This computes C = A + B                                          */
850
/*                                                                    */
851
/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
852
/*   lhs is A                                                         */
853
/*   rhs is B                                                         */
854
/*   set is the context                                               */
855
/*                                                                    */
856
/* C must have space for set->digits digits.                          */
857
/* ------------------------------------------------------------------ */
858
/* This just calls the routine shared with Subtract                   */
859
decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
860
0
                         const decNumber *rhs, decContext *set) {
861
0
  uInt status=0;                        // accumulator
862
0
  decAddOp(res, lhs, rhs, set, 0, &status);
863
0
  if (status!=0) decStatus(res, status, set);
864
  #if DECCHECK
865
  decCheckInexact(res, set);
866
  #endif
867
0
  return res;
868
0
  } // decNumberAdd
869
870
/* ------------------------------------------------------------------ */
871
/* decNumberAnd -- AND two Numbers, digitwise                         */
872
/*                                                                    */
873
/*   This computes C = A & B                                          */
874
/*                                                                    */
875
/*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
876
/*   lhs is A                                                         */
877
/*   rhs is B                                                         */
878
/*   set is the context (used for result length and error report)     */
879
/*                                                                    */
880
/* C must have space for set->digits digits.                          */
881
/*                                                                    */
882
/* Logical function restrictions apply (see above); a NaN is          */
883
/* returned with Invalid_operation if a restriction is violated.      */
884
/* ------------------------------------------------------------------ */
885
decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
886
0
                         const decNumber *rhs, decContext *set) {
887
0
  const Unit *ua, *ub;                  // -> operands
888
0
  const Unit *msua, *msub;              // -> operand msus
889
0
  Unit *uc,  *msuc;                     // -> result and its msu
890
0
  Int   msudigs;                        // digits in res msu
891
  #if DECCHECK
892
  if (decCheckOperands(res, lhs, rhs, set)) return res;
893
  #endif
894
895
0
  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
896
0
   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
897
0
    decStatus(res, DEC_Invalid_operation, set);
898
0
    return res;
899
0
    }
900
901
  // operands are valid
902
0
  ua=lhs->lsu;                          // bottom-up
903
0
  ub=rhs->lsu;                          // ..
904
0
  uc=res->lsu;                          // ..
905
0
  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
906
0
  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
907
0
  msuc=uc+D2U(set->digits)-1;           // -> msu of result
908
0
  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
909
0
  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
910
0
    Unit a, b;                          // extract units
911
0
    if (ua>msua) a=0;
912
0
     else a=*ua;
913
0
    if (ub>msub) b=0;
914
0
     else b=*ub;
915
0
    *uc=0;                              // can now write back
916
0
    if (a|b) {                          // maybe 1 bits to examine
917
0
      Int i, j;
918
0
      *uc=0;                            // can now write back
919
      // This loop could be unrolled and/or use BIN2BCD tables
920
0
      for (i=0; i<DECDPUN; i++) {
921
0
        if (a&b&1) *uc=*uc+(Unit)powers[i];  // effect AND
922
0
        j=a%10;
923
0
        a=a/10;
924
0
        j|=b%10;
925
0
        b=b/10;
926
0
        if (j>1) {
927
0
          decStatus(res, DEC_Invalid_operation, set);
928
0
          return res;
929
0
          }
930
0
        if (uc==msuc && i==msudigs-1) break; // just did final digit
931
0
        } // each digit
932
0
      } // both OK
933
0
    } // each unit
934
  // [here uc-1 is the msu of the result]
935
0
  res->digits=decGetDigits(res->lsu, uc-res->lsu);
936
0
  res->exponent=0;                      // integer
937
0
  res->bits=0;                          // sign=0
938
0
  return res;  // [no status to set]
939
0
  } // decNumberAnd
940
941
/* ------------------------------------------------------------------ */
942
/* decNumberCompare -- compare two Numbers                            */
943
/*                                                                    */
944
/*   This computes C = A ? B                                          */
945
/*                                                                    */
946
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
947
/*   lhs is A                                                         */
948
/*   rhs is B                                                         */
949
/*   set is the context                                               */
950
/*                                                                    */
951
/* C must have space for one digit (or NaN).                          */
952
/* ------------------------------------------------------------------ */
953
decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
954
0
                             const decNumber *rhs, decContext *set) {
955
0
  uInt status=0;                        // accumulator
956
0
  decCompareOp(res, lhs, rhs, set, COMPARE, &status);
957
0
  if (status!=0) decStatus(res, status, set);
958
0
  return res;
959
0
  } // decNumberCompare
960
961
/* ------------------------------------------------------------------ */
962
/* decNumberCompareSignal -- compare, signalling on all NaNs          */
963
/*                                                                    */
964
/*   This computes C = A ? B                                          */
965
/*                                                                    */
966
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
967
/*   lhs is A                                                         */
968
/*   rhs is B                                                         */
969
/*   set is the context                                               */
970
/*                                                                    */
971
/* C must have space for one digit (or NaN).                          */
972
/* ------------------------------------------------------------------ */
973
decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
974
0
                                   const decNumber *rhs, decContext *set) {
975
0
  uInt status=0;                        // accumulator
976
0
  decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
977
0
  if (status!=0) decStatus(res, status, set);
978
0
  return res;
979
0
  } // decNumberCompareSignal
980
981
/* ------------------------------------------------------------------ */
982
/* decNumberCompareTotal -- compare two Numbers, using total ordering */
983
/*                                                                    */
984
/*   This computes C = A ? B, under total ordering                    */
985
/*                                                                    */
986
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
987
/*   lhs is A                                                         */
988
/*   rhs is B                                                         */
989
/*   set is the context                                               */
990
/*                                                                    */
991
/* C must have space for one digit; the result will always be one of  */
992
/* -1, 0, or 1.                                                       */
993
/* ------------------------------------------------------------------ */
994
decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
995
0
                                  const decNumber *rhs, decContext *set) {
996
0
  uInt status=0;                        // accumulator
997
0
  decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
998
0
  if (status!=0) decStatus(res, status, set);
999
0
  return res;
1000
0
  } // decNumberCompareTotal
1001
1002
/* ------------------------------------------------------------------ */
1003
/* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
1004
/*                                                                    */
1005
/*   This computes C = |A| ? |B|, under total ordering                */
1006
/*                                                                    */
1007
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1008
/*   lhs is A                                                         */
1009
/*   rhs is B                                                         */
1010
/*   set is the context                                               */
1011
/*                                                                    */
1012
/* C must have space for one digit; the result will always be one of  */
1013
/* -1, 0, or 1.                                                       */
1014
/* ------------------------------------------------------------------ */
1015
decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
1016
0
                                     const decNumber *rhs, decContext *set) {
1017
0
  uInt status=0;                   // accumulator
1018
0
  uInt needbytes;                  // for space calculations
1019
0
  decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
1020
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1021
0
  decNumber bufb[D2N(DECBUFFER+1)];
1022
0
  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
1023
0
  decNumber *a, *b;                // temporary pointers
1024
1025
  #if DECCHECK
1026
  if (decCheckOperands(res, lhs, rhs, set)) return res;
1027
  #endif
1028
1029
0
  do {                                  // protect allocated storage
1030
    // if either is negative, take a copy and absolute
1031
0
    if (decNumberIsNegative(lhs)) {     // lhs<0
1032
0
      a=bufa;
1033
0
      needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
1034
0
      if (needbytes>sizeof(bufa)) {     // need malloc space
1035
0
        allocbufa=(decNumber *)malloc(needbytes);
1036
0
        if (allocbufa==NULL) {          // hopeless -- abandon
1037
0
          status|=DEC_Insufficient_storage;
1038
0
          break;}
1039
0
        a=allocbufa;                    // use the allocated space
1040
0
        }
1041
0
      decNumberCopy(a, lhs);            // copy content
1042
0
      a->bits&=~DECNEG;                 // .. and clear the sign
1043
0
      lhs=a;                            // use copy from here on
1044
0
      }
1045
0
    if (decNumberIsNegative(rhs)) {     // rhs<0
1046
0
      b=bufb;
1047
0
      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
1048
0
      if (needbytes>sizeof(bufb)) {     // need malloc space
1049
0
        allocbufb=(decNumber *)malloc(needbytes);
1050
0
        if (allocbufb==NULL) {          // hopeless -- abandon
1051
0
          status|=DEC_Insufficient_storage;
1052
0
          break;}
1053
0
        b=allocbufb;                    // use the allocated space
1054
0
        }
1055
0
      decNumberCopy(b, rhs);            // copy content
1056
0
      b->bits&=~DECNEG;                 // .. and clear the sign
1057
0
      rhs=b;                            // use copy from here on
1058
0
      }
1059
0
    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
1060
0
    } while(0);                         // end protected
1061
1062
0
  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1063
0
  if (allocbufb!=NULL) free(allocbufb); // ..
1064
0
  if (status!=0) decStatus(res, status, set);
1065
0
  return res;
1066
0
  } // decNumberCompareTotalMag
1067
1068
/* ------------------------------------------------------------------ */
1069
/* decNumberDivide -- divide one number by another                    */
1070
/*                                                                    */
1071
/*   This computes C = A / B                                          */
1072
/*                                                                    */
1073
/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
1074
/*   lhs is A                                                         */
1075
/*   rhs is B                                                         */
1076
/*   set is the context                                               */
1077
/*                                                                    */
1078
/* C must have space for set->digits digits.                          */
1079
/* ------------------------------------------------------------------ */
1080
decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
1081
0
                            const decNumber *rhs, decContext *set) {
1082
0
  uInt status=0;                        // accumulator
1083
0
  decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1084
0
  if (status!=0) decStatus(res, status, set);
1085
  #if DECCHECK
1086
  decCheckInexact(res, set);
1087
  #endif
1088
0
  return res;
1089
0
  } // decNumberDivide
1090
1091
/* ------------------------------------------------------------------ */
1092
/* decNumberDivideInteger -- divide and return integer quotient       */
1093
/*                                                                    */
1094
/*   This computes C = A # B, where # is the integer divide operator  */
1095
/*                                                                    */
1096
/*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1097
/*   lhs is A                                                         */
1098
/*   rhs is B                                                         */
1099
/*   set is the context                                               */
1100
/*                                                                    */
1101
/* C must have space for set->digits digits.                          */
1102
/* ------------------------------------------------------------------ */
1103
decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1104
0
                                   const decNumber *rhs, decContext *set) {
1105
0
  uInt status=0;                        // accumulator
1106
0
  decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1107
0
  if (status!=0) decStatus(res, status, set);
1108
0
  return res;
1109
0
  } // decNumberDivideInteger
1110
1111
/* ------------------------------------------------------------------ */
1112
/* decNumberExp -- exponentiation                                     */
1113
/*                                                                    */
1114
/*   This computes C = exp(A)                                         */
1115
/*                                                                    */
1116
/*   res is C, the result.  C may be A                                */
1117
/*   rhs is A                                                         */
1118
/*   set is the context; note that rounding mode has no effect        */
1119
/*                                                                    */
1120
/* C must have space for set->digits digits.                          */
1121
/*                                                                    */
1122
/* Mathematical function restrictions apply (see above); a NaN is     */
1123
/* returned with Invalid_operation if a restriction is violated.      */
1124
/*                                                                    */
1125
/* Finite results will always be full precision and Inexact, except   */
1126
/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1127
/*                                                                    */
1128
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1129
/* almost always be correctly rounded, but may be up to 1 ulp in      */
1130
/* error in rare cases.                                               */
1131
/* ------------------------------------------------------------------ */
1132
/* This is a wrapper for decExpOp which can handle the slightly wider */
1133
/* (double) range needed by Ln (which has to be able to calculate     */
1134
/* exp(-a) where a can be the tiniest number (Ntiny).                 */
1135
/* ------------------------------------------------------------------ */
1136
decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1137
0
                         decContext *set) {
1138
0
  uInt status=0;                        // accumulator
1139
  #if DECSUBSET
1140
  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1141
  #endif
1142
1143
  #if DECCHECK
1144
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1145
  #endif
1146
1147
  // Check restrictions; these restrictions ensure that if h=8 (see
1148
  // decExpOp) then the result will either overflow or underflow to 0.
1149
  // Other math functions restrict the input range, too, for inverses.
1150
  // If not violated then carry out the operation.
1151
0
  if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1152
    #if DECSUBSET
1153
    if (!set->extended) {
1154
      // reduce operand and set lostDigits status, as needed
1155
      if (rhs->digits>set->digits) {
1156
        allocrhs=decRoundOperand(rhs, set, &status);
1157
        if (allocrhs==NULL) break;
1158
        rhs=allocrhs;
1159
        }
1160
      }
1161
    #endif
1162
0
    decExpOp(res, rhs, set, &status);
1163
0
    } while(0);                         // end protected
1164
1165
  #if DECSUBSET
1166
  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
1167
  #endif
1168
  // apply significant status
1169
0
  if (status!=0) decStatus(res, status, set);
1170
  #if DECCHECK
1171
  decCheckInexact(res, set);
1172
  #endif
1173
0
  return res;
1174
0
  } // decNumberExp
1175
1176
/* ------------------------------------------------------------------ */
1177
/* decNumberFMA -- fused multiply add                                 */
1178
/*                                                                    */
1179
/*   This computes D = (A * B) + C with only one rounding             */
1180
/*                                                                    */
1181
/*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1182
/*   lhs is A                                                         */
1183
/*   rhs is B                                                         */
1184
/*   fhs is C [far hand side]                                         */
1185
/*   set is the context                                               */
1186
/*                                                                    */
1187
/* Mathematical function restrictions apply (see above); a NaN is     */
1188
/* returned with Invalid_operation if a restriction is violated.      */
1189
/*                                                                    */
1190
/* C must have space for set->digits digits.                          */
1191
/* ------------------------------------------------------------------ */
1192
decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1193
                         const decNumber *rhs, const decNumber *fhs,
1194
0
                         decContext *set) {
1195
0
  uInt status=0;                   // accumulator
1196
0
  decContext dcmul;                // context for the multiplication
1197
0
  uInt needbytes;                  // for space calculations
1198
0
  decNumber bufa[D2N(DECBUFFER*2+1)];
1199
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1200
0
  decNumber *acc;                  // accumulator pointer
1201
0
  decNumber dzero;                 // work
1202
1203
  #if DECCHECK
1204
  if (decCheckOperands(res, lhs, rhs, set)) return res;
1205
  if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1206
  #endif
1207
1208
0
  do {                                  // protect allocated storage
1209
    #if DECSUBSET
1210
    if (!set->extended) {               // [undefined if subset]
1211
      status|=DEC_Invalid_operation;
1212
      break;}
1213
    #endif
1214
    // Check math restrictions [these ensure no overflow or underflow]
1215
0
    if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1216
0
     || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1217
0
     || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1218
    // set up context for multiply
1219
0
    dcmul=*set;
1220
0
    dcmul.digits=lhs->digits+rhs->digits; // just enough
1221
    // [The above may be an over-estimate for subset arithmetic, but that's OK]
1222
0
    dcmul.emax=DEC_MAX_EMAX;            // effectively unbounded ..
1223
0
    dcmul.emin=DEC_MIN_EMIN;            // [thanks to Math restrictions]
1224
    // set up decNumber space to receive the result of the multiply
1225
0
    acc=bufa;                           // may fit
1226
0
    needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1227
0
    if (needbytes>sizeof(bufa)) {       // need malloc space
1228
0
      allocbufa=(decNumber *)malloc(needbytes);
1229
0
      if (allocbufa==NULL) {            // hopeless -- abandon
1230
0
        status|=DEC_Insufficient_storage;
1231
0
        break;}
1232
0
      acc=allocbufa;                    // use the allocated space
1233
0
      }
1234
    // multiply with extended range and necessary precision
1235
    //printf("emin=%ld\n", dcmul.emin);
1236
0
    decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1237
    // Only Invalid operation (from sNaN or Inf * 0) is possible in
1238
    // status; if either is seen than ignore fhs (in case it is
1239
    // another sNaN) and set acc to NaN unless we had an sNaN
1240
    // [decMultiplyOp leaves that to caller]
1241
    // Note sNaN has to go through addOp to shorten payload if
1242
    // necessary
1243
0
    if ((status&DEC_Invalid_operation)!=0) {
1244
0
      if (!(status&DEC_sNaN)) {         // but be true invalid
1245
0
        decNumberZero(res);             // acc not yet set
1246
0
        res->bits=DECNAN;
1247
0
        break;
1248
0
        }
1249
0
      decNumberZero(&dzero);            // make 0 (any non-NaN would do)
1250
0
      fhs=&dzero;                       // use that
1251
0
      }
1252
    #if DECCHECK
1253
     else { // multiply was OK
1254
      if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1255
      }
1256
    #endif
1257
    // add the third operand and result -> res, and all is done
1258
0
    decAddOp(res, acc, fhs, set, 0, &status);
1259
0
    } while(0);                         // end protected
1260
1261
0
  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1262
0
  if (status!=0) decStatus(res, status, set);
1263
  #if DECCHECK
1264
  decCheckInexact(res, set);
1265
  #endif
1266
0
  return res;
1267
0
  } // decNumberFMA
1268
1269
/* ------------------------------------------------------------------ */
1270
/* decNumberInvert -- invert a Number, digitwise                      */
1271
/*                                                                    */
1272
/*   This computes C = ~A                                             */
1273
/*                                                                    */
1274
/*   res is C, the result.  C may be A (e.g., X=~X)                   */
1275
/*   rhs is A                                                         */
1276
/*   set is the context (used for result length and error report)     */
1277
/*                                                                    */
1278
/* C must have space for set->digits digits.                          */
1279
/*                                                                    */
1280
/* Logical function restrictions apply (see above); a NaN is          */
1281
/* returned with Invalid_operation if a restriction is violated.      */
1282
/* ------------------------------------------------------------------ */
1283
decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1284
0
                            decContext *set) {
1285
0
  const Unit *ua, *msua;                // -> operand and its msu
1286
0
  Unit  *uc, *msuc;                     // -> result and its msu
1287
0
  Int   msudigs;                        // digits in res msu
1288
  #if DECCHECK
1289
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1290
  #endif
1291
1292
0
  if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1293
0
    decStatus(res, DEC_Invalid_operation, set);
1294
0
    return res;
1295
0
    }
1296
  // operand is valid
1297
0
  ua=rhs->lsu;                          // bottom-up
1298
0
  uc=res->lsu;                          // ..
1299
0
  msua=ua+D2U(rhs->digits)-1;           // -> msu of rhs
1300
0
  msuc=uc+D2U(set->digits)-1;           // -> msu of result
1301
0
  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1302
0
  for (; uc<=msuc; ua++, uc++) {        // Unit loop
1303
0
    Unit a;                             // extract unit
1304
0
    Int  i, j;                          // work
1305
0
    if (ua>msua) a=0;
1306
0
     else a=*ua;
1307
0
    *uc=0;                              // can now write back
1308
    // always need to examine all bits in rhs
1309
    // This loop could be unrolled and/or use BIN2BCD tables
1310
0
    for (i=0; i<DECDPUN; i++) {
1311
0
      if ((~a)&1) *uc=*uc+(Unit)powers[i];   // effect INVERT
1312
0
      j=a%10;
1313
0
      a=a/10;
1314
0
      if (j>1) {
1315
0
        decStatus(res, DEC_Invalid_operation, set);
1316
0
        return res;
1317
0
        }
1318
0
      if (uc==msuc && i==msudigs-1) break;   // just did final digit
1319
0
      } // each digit
1320
0
    } // each unit
1321
  // [here uc-1 is the msu of the result]
1322
0
  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1323
0
  res->exponent=0;                      // integer
1324
0
  res->bits=0;                          // sign=0
1325
0
  return res;  // [no status to set]
1326
0
  } // decNumberInvert
1327
1328
/* ------------------------------------------------------------------ */
1329
/* decNumberLn -- natural logarithm                                   */
1330
/*                                                                    */
1331
/*   This computes C = ln(A)                                          */
1332
/*                                                                    */
1333
/*   res is C, the result.  C may be A                                */
1334
/*   rhs is A                                                         */
1335
/*   set is the context; note that rounding mode has no effect        */
1336
/*                                                                    */
1337
/* C must have space for set->digits digits.                          */
1338
/*                                                                    */
1339
/* Notable cases:                                                     */
1340
/*   A<0 -> Invalid                                                   */
1341
/*   A=0 -> -Infinity (Exact)                                         */
1342
/*   A=+Infinity -> +Infinity (Exact)                                 */
1343
/*   A=1 exactly -> 0 (Exact)                                         */
1344
/*                                                                    */
1345
/* Mathematical function restrictions apply (see above); a NaN is     */
1346
/* returned with Invalid_operation if a restriction is violated.      */
1347
/*                                                                    */
1348
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1349
/* almost always be correctly rounded, but may be up to 1 ulp in      */
1350
/* error in rare cases.                                               */
1351
/* ------------------------------------------------------------------ */
1352
/* This is a wrapper for decLnOp which can handle the slightly wider  */
1353
/* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1354
/* to calculate at p+e+2).                                            */
1355
/* ------------------------------------------------------------------ */
1356
decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1357
0
                        decContext *set) {
1358
0
  uInt status=0;                   // accumulator
1359
  #if DECSUBSET
1360
  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1361
  #endif
1362
1363
  #if DECCHECK
1364
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1365
  #endif
1366
1367
  // Check restrictions; this is a math function; if not violated
1368
  // then carry out the operation.
1369
0
  if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1370
    #if DECSUBSET
1371
    if (!set->extended) {
1372
      // reduce operand and set lostDigits status, as needed
1373
      if (rhs->digits>set->digits) {
1374
        allocrhs=decRoundOperand(rhs, set, &status);
1375
        if (allocrhs==NULL) break;
1376
        rhs=allocrhs;
1377
        }
1378
      // special check in subset for rhs=0
1379
      if (ISZERO(rhs)) {                // +/- zeros -> error
1380
        status|=DEC_Invalid_operation;
1381
        break;}
1382
      } // extended=0
1383
    #endif
1384
0
    decLnOp(res, rhs, set, &status);
1385
0
    } while(0);                         // end protected
1386
1387
  #if DECSUBSET
1388
  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
1389
  #endif
1390
  // apply significant status
1391
0
  if (status!=0) decStatus(res, status, set);
1392
  #if DECCHECK
1393
  decCheckInexact(res, set);
1394
  #endif
1395
0
  return res;
1396
0
  } // decNumberLn
1397
1398
/* ------------------------------------------------------------------ */
1399
/* decNumberLogB - get adjusted exponent, by 754 rules                */
1400
/*                                                                    */
1401
/*   This computes C = adjustedexponent(A)                            */
1402
/*                                                                    */
1403
/*   res is C, the result.  C may be A                                */
1404
/*   rhs is A                                                         */
1405
/*   set is the context, used only for digits and status              */
1406
/*                                                                    */
1407
/* For an unrounded result, digits may need to be 10 (A might have    */
1408
/* 10**9 digits and an exponent of +999999999, or one digit and an    */
1409
/* exponent of -1999999999).                                          */
1410
/*                                                                    */
1411
/* This returns the adjusted exponent of A after (in theory) padding  */
1412
/* with zeros on the right to set->digits digits while keeping the    */
1413
/* same value.  The exponent is not limited by emin/emax.             */
1414
/*                                                                    */
1415
/* Notable cases:                                                     */
1416
/*   A<0 -> Use |A|                                                   */
1417
/*   A=0 -> -Infinity (Division by zero)                              */
1418
/*   A=Infinite -> +Infinity (Exact)                                  */
1419
/*   A=1 exactly -> 0 (Exact)                                         */
1420
/*   NaNs are propagated as usual                                     */
1421
/* ------------------------------------------------------------------ */
1422
decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1423
0
                          decContext *set) {
1424
0
  uInt status=0;                   // accumulator
1425
1426
  #if DECCHECK
1427
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1428
  #endif
1429
1430
  // NaNs as usual; Infinities return +Infinity; 0->oops
1431
0
  if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1432
0
   else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1433
0
   else if (decNumberIsZero(rhs)) {
1434
0
    decNumberZero(res);                 // prepare for Infinity
1435
0
    res->bits=DECNEG|DECINF;            // -Infinity
1436
0
    status|=DEC_Division_by_zero;       // as per 754
1437
0
    }
1438
0
   else { // finite non-zero
1439
0
    Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
1440
0
    if (set->digits>=10) decNumberFromInt32(res, ae);  // lay it out
1441
0
     else {
1442
0
      decNumber buft[D2N(10)];          // temporary number
1443
0
      decNumber *t=buft;                // ..
1444
0
      decNumberFromInt32(t, ae);        // lay it out
1445
0
      decNumberPlus(res, t, set);       // round as necessary
1446
0
      }
1447
0
    }
1448
1449
0
  if (status!=0) decStatus(res, status, set);
1450
0
  return res;
1451
0
  } // decNumberLogB
1452
1453
/* ------------------------------------------------------------------ */
1454
/* decNumberLog10 -- logarithm in base 10                             */
1455
/*                                                                    */
1456
/*   This computes C = log10(A)                                       */
1457
/*                                                                    */
1458
/*   res is C, the result.  C may be A                                */
1459
/*   rhs is A                                                         */
1460
/*   set is the context; note that rounding mode has no effect        */
1461
/*                                                                    */
1462
/* C must have space for set->digits digits.                          */
1463
/*                                                                    */
1464
/* Notable cases:                                                     */
1465
/*   A<0 -> Invalid                                                   */
1466
/*   A=0 -> -Infinity (Exact)                                         */
1467
/*   A=+Infinity -> +Infinity (Exact)                                 */
1468
/*   A=10**n (if n is an integer) -> n (Exact)                        */
1469
/*                                                                    */
1470
/* Mathematical function restrictions apply (see above); a NaN is     */
1471
/* returned with Invalid_operation if a restriction is violated.      */
1472
/*                                                                    */
1473
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1474
/* almost always be correctly rounded, but may be up to 1 ulp in      */
1475
/* error in rare cases.                                               */
1476
/* ------------------------------------------------------------------ */
1477
/* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1478
/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1479
/* requested digits and t is the number of digits in the exponent     */
1480
/* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1481
/* fastpath in decLnOp.  The final division is done to the requested  */
1482
/* precision.                                                         */
1483
/* ------------------------------------------------------------------ */
1484
decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1485
0
                          decContext *set) {
1486
0
  uInt status=0, ignore=0;         // status accumulators
1487
0
  uInt needbytes;                  // for space calculations
1488
0
  Int p;                           // working precision
1489
0
  Int t;                           // digits in exponent of A
1490
1491
  // buffers for a and b working decimals
1492
  // (adjustment calculator, same size)
1493
0
  decNumber bufa[D2N(DECBUFFER+2)];
1494
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1495
0
  decNumber *a=bufa;               // temporary a
1496
0
  decNumber bufb[D2N(DECBUFFER+2)];
1497
0
  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
1498
0
  decNumber *b=bufb;               // temporary b
1499
0
  decNumber bufw[D2N(10)];         // working 2-10 digit number
1500
0
  decNumber *w=bufw;               // ..
1501
  #if DECSUBSET
1502
  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1503
  #endif
1504
1505
0
  decContext aset;                 // working context
1506
1507
  #if DECCHECK
1508
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1509
  #endif
1510
1511
  // Check restrictions; this is a math function; if not violated
1512
  // then carry out the operation.
1513
0
  if (!decCheckMath(rhs, set, &status)) do { // protect malloc
1514
    #if DECSUBSET
1515
    if (!set->extended) {
1516
      // reduce operand and set lostDigits status, as needed
1517
      if (rhs->digits>set->digits) {
1518
        allocrhs=decRoundOperand(rhs, set, &status);
1519
        if (allocrhs==NULL) break;
1520
        rhs=allocrhs;
1521
        }
1522
      // special check in subset for rhs=0
1523
      if (ISZERO(rhs)) {                // +/- zeros -> error
1524
        status|=DEC_Invalid_operation;
1525
        break;}
1526
      } // extended=0
1527
    #endif
1528
1529
0
    decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
1530
1531
    // handle exact powers of 10; only check if +ve finite
1532
0
    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1533
0
      Int residue=0;               // (no residue)
1534
0
      uInt copystat=0;             // clean status
1535
1536
      // round to a single digit...
1537
0
      aset.digits=1;
1538
0
      decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten
1539
      // if exact and the digit is 1, rhs is a power of 10
1540
0
      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1541
        // the exponent, conveniently, is the power of 10; making
1542
        // this the result needs a little care as it might not fit,
1543
        // so first convert it into the working number, and then move
1544
        // to res
1545
0
        decNumberFromInt32(w, w->exponent);
1546
0
        residue=0;
1547
0
        decCopyFit(res, w, set, &residue, &status); // copy & round
1548
0
        decFinish(res, set, &residue, &status);     // cleanup/set flags
1549
0
        break;
1550
0
        } // not a power of 10
1551
0
      } // not a candidate for exact
1552
1553
    // simplify the information-content calculation to use 'total
1554
    // number of digits in a, including exponent' as compared to the
1555
    // requested digits, as increasing this will only rarely cost an
1556
    // iteration in ln(a) anyway
1557
0
    t=6;                                // it can never be >6
1558
1559
    // allocate space when needed...
1560
0
    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1561
0
    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1562
0
    if (needbytes>sizeof(bufa)) {       // need malloc space
1563
0
      allocbufa=(decNumber *)malloc(needbytes);
1564
0
      if (allocbufa==NULL) {            // hopeless -- abandon
1565
0
        status|=DEC_Insufficient_storage;
1566
0
        break;}
1567
0
      a=allocbufa;                      // use the allocated space
1568
0
      }
1569
0
    aset.digits=p;                      // as calculated
1570
0
    aset.emax=DEC_MAX_MATH;             // usual bounds
1571
0
    aset.emin=-DEC_MAX_MATH;            // ..
1572
0
    aset.clamp=0;                       // and no concrete format
1573
0
    decLnOp(a, rhs, &aset, &status);    // a=ln(rhs)
1574
1575
    // skip the division if the result so far is infinite, NaN, or
1576
    // zero, or there was an error; note NaN from sNaN needs copy
1577
0
    if ((status&DEC_NaNs) && !(status&DEC_sNaN)) break;
1578
0
    if ((a->bits&DECSPECIAL) || ISZERO(a)) {
1579
0
      decNumberCopy(res, a);            // [will fit]
1580
0
      break;}
1581
1582
    // for ln(10) an extra 3 digits of precision are needed
1583
0
    p=set->digits+3;
1584
0
    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1585
0
    if (needbytes>sizeof(bufb)) {       // need malloc space
1586
0
      allocbufb=(decNumber *)malloc(needbytes);
1587
0
      if (allocbufb==NULL) {            // hopeless -- abandon
1588
0
        status|=DEC_Insufficient_storage;
1589
0
        break;}
1590
0
      b=allocbufb;                      // use the allocated space
1591
0
      }
1592
0
    decNumberZero(w);                   // set up 10...
1593
    #if DECDPUN==1
1594
    w->lsu[1]=1; w->lsu[0]=0;           // ..
1595
    #else
1596
0
    w->lsu[0]=10;                       // ..
1597
0
    #endif
1598
0
    w->digits=2;                        // ..
1599
1600
0
    aset.digits=p;
1601
0
    decLnOp(b, w, &aset, &ignore);      // b=ln(10)
1602
1603
0
    aset.digits=set->digits;            // for final divide
1604
0
    decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
1605
0
    } while(0);                         // [for break]
1606
1607
0
  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1608
0
  if (allocbufb!=NULL) free(allocbufb); // ..
1609
  #if DECSUBSET
1610
  if (allocrhs !=NULL) free(allocrhs);  // ..
1611
  #endif
1612
  // apply significant status
1613
0
  if (status!=0) decStatus(res, status, set);
1614
  #if DECCHECK
1615
  decCheckInexact(res, set);
1616
  #endif
1617
0
  return res;
1618
0
  } // decNumberLog10
1619
1620
/* ------------------------------------------------------------------ */
1621
/* decNumberMax -- compare two Numbers and return the maximum         */
1622
/*                                                                    */
1623
/*   This computes C = A ? B, returning the maximum by 754 rules      */
1624
/*                                                                    */
1625
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1626
/*   lhs is A                                                         */
1627
/*   rhs is B                                                         */
1628
/*   set is the context                                               */
1629
/*                                                                    */
1630
/* C must have space for set->digits digits.                          */
1631
/* ------------------------------------------------------------------ */
1632
decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1633
0
                         const decNumber *rhs, decContext *set) {
1634
0
  uInt status=0;                        // accumulator
1635
0
  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1636
0
  if (status!=0) decStatus(res, status, set);
1637
  #if DECCHECK
1638
  decCheckInexact(res, set);
1639
  #endif
1640
0
  return res;
1641
0
  } // decNumberMax
1642
1643
/* ------------------------------------------------------------------ */
1644
/* decNumberMaxMag -- compare and return the maximum by magnitude     */
1645
/*                                                                    */
1646
/*   This computes C = A ? B, returning the maximum by 754 rules      */
1647
/*                                                                    */
1648
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1649
/*   lhs is A                                                         */
1650
/*   rhs is B                                                         */
1651
/*   set is the context                                               */
1652
/*                                                                    */
1653
/* C must have space for set->digits digits.                          */
1654
/* ------------------------------------------------------------------ */
1655
decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1656
0
                         const decNumber *rhs, decContext *set) {
1657
0
  uInt status=0;                        // accumulator
1658
0
  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1659
0
  if (status!=0) decStatus(res, status, set);
1660
  #if DECCHECK
1661
  decCheckInexact(res, set);
1662
  #endif
1663
0
  return res;
1664
0
  } // decNumberMaxMag
1665
1666
/* ------------------------------------------------------------------ */
1667
/* decNumberMin -- compare two Numbers and return the minimum         */
1668
/*                                                                    */
1669
/*   This computes C = A ? B, returning the minimum by 754 rules      */
1670
/*                                                                    */
1671
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1672
/*   lhs is A                                                         */
1673
/*   rhs is B                                                         */
1674
/*   set is the context                                               */
1675
/*                                                                    */
1676
/* C must have space for set->digits digits.                          */
1677
/* ------------------------------------------------------------------ */
1678
decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1679
0
                         const decNumber *rhs, decContext *set) {
1680
0
  uInt status=0;                        // accumulator
1681
0
  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1682
0
  if (status!=0) decStatus(res, status, set);
1683
  #if DECCHECK
1684
  decCheckInexact(res, set);
1685
  #endif
1686
0
  return res;
1687
0
  } // decNumberMin
1688
1689
/* ------------------------------------------------------------------ */
1690
/* decNumberMinMag -- compare and return the minimum by magnitude     */
1691
/*                                                                    */
1692
/*   This computes C = A ? B, returning the minimum by 754 rules      */
1693
/*                                                                    */
1694
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1695
/*   lhs is A                                                         */
1696
/*   rhs is B                                                         */
1697
/*   set is the context                                               */
1698
/*                                                                    */
1699
/* C must have space for set->digits digits.                          */
1700
/* ------------------------------------------------------------------ */
1701
decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1702
0
                         const decNumber *rhs, decContext *set) {
1703
0
  uInt status=0;                        // accumulator
1704
0
  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1705
0
  if (status!=0) decStatus(res, status, set);
1706
  #if DECCHECK
1707
  decCheckInexact(res, set);
1708
  #endif
1709
0
  return res;
1710
0
  } // decNumberMinMag
1711
1712
/* ------------------------------------------------------------------ */
1713
/* decNumberMinus -- prefix minus operator                            */
1714
/*                                                                    */
1715
/*   This computes C = 0 - A                                          */
1716
/*                                                                    */
1717
/*   res is C, the result.  C may be A                                */
1718
/*   rhs is A                                                         */
1719
/*   set is the context                                               */
1720
/*                                                                    */
1721
/* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1722
/* C must have space for set->digits digits.                          */
1723
/* ------------------------------------------------------------------ */
1724
/* Simply use AddOp for the subtract, which will do the necessary.    */
1725
/* ------------------------------------------------------------------ */
1726
decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1727
1.87k
                           decContext *set) {
1728
1.87k
  decNumber dzero;
1729
1.87k
  uInt status=0;                        // accumulator
1730
1731
  #if DECCHECK
1732
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1733
  #endif
1734
1735
1.87k
  decNumberZero(&dzero);                // make 0
1736
1.87k
  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1737
1.87k
  decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1738
1.87k
  if (status!=0) decStatus(res, status, set);
1739
  #if DECCHECK
1740
  decCheckInexact(res, set);
1741
  #endif
1742
1.87k
  return res;
1743
1.87k
  } // decNumberMinus
1744
1745
/* ------------------------------------------------------------------ */
1746
/* decNumberNextMinus -- next towards -Infinity                       */
1747
/*                                                                    */
1748
/*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1749
/*                                                                    */
1750
/*   res is C, the result.  C may be A                                */
1751
/*   rhs is A                                                         */
1752
/*   set is the context                                               */
1753
/*                                                                    */
1754
/* This is a generalization of 754 NextDown.                          */
1755
/* ------------------------------------------------------------------ */
1756
decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1757
0
                               decContext *set) {
1758
0
  decNumber dtiny;                           // constant
1759
0
  decContext workset=*set;                   // work
1760
0
  uInt status=0;                             // accumulator
1761
  #if DECCHECK
1762
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1763
  #endif
1764
1765
  // +Infinity is the special case
1766
0
  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1767
0
    decSetMaxValue(res, set);                // is +ve
1768
    // there is no status to set
1769
0
    return res;
1770
0
    }
1771
0
  decNumberZero(&dtiny);                     // start with 0
1772
0
  dtiny.lsu[0]=1;                            // make number that is ..
1773
0
  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
1774
0
  workset.round=DEC_ROUND_FLOOR;
1775
0
  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1776
0
  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1777
0
  if (status!=0) decStatus(res, status, set);
1778
0
  return res;
1779
0
  } // decNumberNextMinus
1780
1781
/* ------------------------------------------------------------------ */
1782
/* decNumberNextPlus -- next towards +Infinity                        */
1783
/*                                                                    */
1784
/*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1785
/*                                                                    */
1786
/*   res is C, the result.  C may be A                                */
1787
/*   rhs is A                                                         */
1788
/*   set is the context                                               */
1789
/*                                                                    */
1790
/* This is a generalization of 754 NextUp.                            */
1791
/* ------------------------------------------------------------------ */
1792
decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1793
0
                              decContext *set) {
1794
0
  decNumber dtiny;                           // constant
1795
0
  decContext workset=*set;                   // work
1796
0
  uInt status=0;                             // accumulator
1797
  #if DECCHECK
1798
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1799
  #endif
1800
1801
  // -Infinity is the special case
1802
0
  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1803
0
    decSetMaxValue(res, set);
1804
0
    res->bits=DECNEG;                        // negative
1805
    // there is no status to set
1806
0
    return res;
1807
0
    }
1808
0
  decNumberZero(&dtiny);                     // start with 0
1809
0
  dtiny.lsu[0]=1;                            // make number that is ..
1810
0
  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
1811
0
  workset.round=DEC_ROUND_CEILING;
1812
0
  decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1813
0
  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1814
0
  if (status!=0) decStatus(res, status, set);
1815
0
  return res;
1816
0
  } // decNumberNextPlus
1817
1818
/* ------------------------------------------------------------------ */
1819
/* decNumberNextToward -- next towards rhs                            */
1820
/*                                                                    */
1821
/*   This computes C = A +/- infinitesimal, rounded towards           */
1822
/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1823
/*   modified during revision but dropped from 754-2008.              */
1824
/*                                                                    */
1825
/*   res is C, the result.  C may be A or B.                          */
1826
/*   lhs is A                                                         */
1827
/*   rhs is B                                                         */
1828
/*   set is the context                                               */
1829
/*                                                                    */
1830
/* This is a generalization of 754-1985 NextAfter.                    */
1831
/* ------------------------------------------------------------------ */
1832
decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1833
0
                                const decNumber *rhs, decContext *set) {
1834
0
  decNumber dtiny;                           // constant
1835
0
  decContext workset=*set;                   // work
1836
0
  Int result;                                // ..
1837
0
  uInt status=0;                             // accumulator
1838
  #if DECCHECK
1839
  if (decCheckOperands(res, lhs, rhs, set)) return res;
1840
  #endif
1841
1842
0
  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1843
0
    decNaNs(res, lhs, rhs, set, &status);
1844
0
    }
1845
0
   else { // Is numeric, so no chance of sNaN Invalid, etc.
1846
0
    result=decCompare(lhs, rhs, 0);     // sign matters
1847
0
    if (result==BADINT) status|=DEC_Insufficient_storage; // rare
1848
0
     else { // valid compare
1849
0
      if (result==0) decNumberCopySign(res, lhs, rhs); // easy
1850
0
       else { // differ: need NextPlus or NextMinus
1851
0
        uByte sub;                      // add or subtract
1852
0
        if (result<0) {                 // lhs<rhs, do nextplus
1853
          // -Infinity is the special case
1854
0
          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1855
0
            decSetMaxValue(res, set);
1856
0
            res->bits=DECNEG;           // negative
1857
0
            return res;                 // there is no status to set
1858
0
            }
1859
0
          workset.round=DEC_ROUND_CEILING;
1860
0
          sub=0;                        // add, please
1861
0
          } // plus
1862
0
         else {                         // lhs>rhs, do nextminus
1863
          // +Infinity is the special case
1864
0
          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1865
0
            decSetMaxValue(res, set);
1866
0
            return res;                 // there is no status to set
1867
0
            }
1868
0
          workset.round=DEC_ROUND_FLOOR;
1869
0
          sub=DECNEG;                   // subtract, please
1870
0
          } // minus
1871
0
        decNumberZero(&dtiny);          // start with 0
1872
0
        dtiny.lsu[0]=1;                 // make number that is ..
1873
0
        dtiny.exponent=DEC_MIN_EMIN-1;  // .. smaller than tiniest
1874
0
        decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
1875
        // turn off exceptions if the result is a normal number
1876
        // (including Nmin), otherwise let all status through
1877
0
        if (decNumberIsNormal(res, set)) status=0;
1878
0
        } // unequal
1879
0
      } // compare OK
1880
0
    } // numeric
1881
0
  if (status!=0) decStatus(res, status, set);
1882
0
  return res;
1883
0
  } // decNumberNextToward
1884
1885
/* ------------------------------------------------------------------ */
1886
/* decNumberOr -- OR two Numbers, digitwise                           */
1887
/*                                                                    */
1888
/*   This computes C = A | B                                          */
1889
/*                                                                    */
1890
/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1891
/*   lhs is A                                                         */
1892
/*   rhs is B                                                         */
1893
/*   set is the context (used for result length and error report)     */
1894
/*                                                                    */
1895
/* C must have space for set->digits digits.                          */
1896
/*                                                                    */
1897
/* Logical function restrictions apply (see above); a NaN is          */
1898
/* returned with Invalid_operation if a restriction is violated.      */
1899
/* ------------------------------------------------------------------ */
1900
decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1901
0
                        const decNumber *rhs, decContext *set) {
1902
0
  const Unit *ua, *ub;                  // -> operands
1903
0
  const Unit *msua, *msub;              // -> operand msus
1904
0
  Unit  *uc, *msuc;                     // -> result and its msu
1905
0
  Int   msudigs;                        // digits in res msu
1906
  #if DECCHECK
1907
  if (decCheckOperands(res, lhs, rhs, set)) return res;
1908
  #endif
1909
1910
0
  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1911
0
   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1912
0
    decStatus(res, DEC_Invalid_operation, set);
1913
0
    return res;
1914
0
    }
1915
  // operands are valid
1916
0
  ua=lhs->lsu;                          // bottom-up
1917
0
  ub=rhs->lsu;                          // ..
1918
0
  uc=res->lsu;                          // ..
1919
0
  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
1920
0
  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
1921
0
  msuc=uc+D2U(set->digits)-1;           // -> msu of result
1922
0
  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1923
0
  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
1924
0
    Unit a, b;                          // extract units
1925
0
    if (ua>msua) a=0;
1926
0
     else a=*ua;
1927
0
    if (ub>msub) b=0;
1928
0
     else b=*ub;
1929
0
    *uc=0;                              // can now write back
1930
0
    if (a|b) {                          // maybe 1 bits to examine
1931
0
      Int i, j;
1932
      // This loop could be unrolled and/or use BIN2BCD tables
1933
0
      for (i=0; i<DECDPUN; i++) {
1934
0
        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     // effect OR
1935
0
        j=a%10;
1936
0
        a=a/10;
1937
0
        j|=b%10;
1938
0
        b=b/10;
1939
0
        if (j>1) {
1940
0
          decStatus(res, DEC_Invalid_operation, set);
1941
0
          return res;
1942
0
          }
1943
0
        if (uc==msuc && i==msudigs-1) break;      // just did final digit
1944
0
        } // each digit
1945
0
      } // non-zero
1946
0
    } // each unit
1947
  // [here uc-1 is the msu of the result]
1948
0
  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1949
0
  res->exponent=0;                      // integer
1950
0
  res->bits=0;                          // sign=0
1951
0
  return res;  // [no status to set]
1952
0
  } // decNumberOr
1953
1954
/* ------------------------------------------------------------------ */
1955
/* decNumberPlus -- prefix plus operator                              */
1956
/*                                                                    */
1957
/*   This computes C = 0 + A                                          */
1958
/*                                                                    */
1959
/*   res is C, the result.  C may be A                                */
1960
/*   rhs is A                                                         */
1961
/*   set is the context                                               */
1962
/*                                                                    */
1963
/* See also decNumberCopy for a quiet bitwise version of this.        */
1964
/* C must have space for set->digits digits.                          */
1965
/* ------------------------------------------------------------------ */
1966
/* This simply uses AddOp; Add will take fast path after preparing A. */
1967
/* Performance is a concern here, as this routine is often used to    */
1968
/* check operands and apply rounding and overflow/underflow testing.  */
1969
/* ------------------------------------------------------------------ */
1970
decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1971
0
                          decContext *set) {
1972
0
  decNumber dzero;
1973
0
  uInt status=0;                        // accumulator
1974
  #if DECCHECK
1975
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1976
  #endif
1977
1978
0
  decNumberZero(&dzero);                // make 0
1979
0
  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1980
0
  decAddOp(res, &dzero, rhs, set, 0, &status);
1981
0
  if (status!=0) decStatus(res, status, set);
1982
  #if DECCHECK
1983
  decCheckInexact(res, set);
1984
  #endif
1985
0
  return res;
1986
0
  } // decNumberPlus
1987
1988
/* ------------------------------------------------------------------ */
1989
/* decNumberMultiply -- multiply two Numbers                          */
1990
/*                                                                    */
1991
/*   This computes C = A x B                                          */
1992
/*                                                                    */
1993
/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1994
/*   lhs is A                                                         */
1995
/*   rhs is B                                                         */
1996
/*   set is the context                                               */
1997
/*                                                                    */
1998
/* C must have space for set->digits digits.                          */
1999
/* ------------------------------------------------------------------ */
2000
decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
2001
0
                              const decNumber *rhs, decContext *set) {
2002
0
  uInt status=0;                   // accumulator
2003
0
  decMultiplyOp(res, lhs, rhs, set, &status);
2004
0
  if (status!=0) decStatus(res, status, set);
2005
  #if DECCHECK
2006
  decCheckInexact(res, set);
2007
  #endif
2008
0
  return res;
2009
0
  } // decNumberMultiply
2010
2011
/* ------------------------------------------------------------------ */
2012
/* decNumberPower -- raise a number to a power                        */
2013
/*                                                                    */
2014
/*   This computes C = A ** B                                         */
2015
/*                                                                    */
2016
/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
2017
/*   lhs is A                                                         */
2018
/*   rhs is B                                                         */
2019
/*   set is the context                                               */
2020
/*                                                                    */
2021
/* C must have space for set->digits digits.                          */
2022
/*                                                                    */
2023
/* Mathematical function restrictions apply (see above); a NaN is     */
2024
/* returned with Invalid_operation if a restriction is violated.      */
2025
/*                                                                    */
2026
/* However, if 1999999997<=B<=999999999 and B is an integer then the  */
2027
/* restrictions on A and the context are relaxed to the usual bounds, */
2028
/* for compatibility with the earlier (integer power only) version    */
2029
/* of this function.                                                  */
2030
/*                                                                    */
2031
/* When B is an integer, the result may be exact, even if rounded.    */
2032
/*                                                                    */
2033
/* The final result is rounded according to the context; it will      */
2034
/* almost always be correctly rounded, but may be up to 1 ulp in      */
2035
/* error in rare cases.                                               */
2036
/* ------------------------------------------------------------------ */
2037
decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
2038
0
                           const decNumber *rhs, decContext *set) {
2039
  #if DECSUBSET
2040
  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
2041
  decNumber *allocrhs=NULL;        // .., rhs
2042
  #endif
2043
0
  decNumber *allocdac=NULL;        // -> allocated acc buffer, iff used
2044
0
  decNumber *allocinv=NULL;        // -> allocated 1/x buffer, iff used
2045
0
  Int   reqdigits=set->digits;     // requested DIGITS
2046
0
  Int   n;                         // rhs in binary
2047
0
  Flag  rhsint=0;                  // 1 if rhs is an integer
2048
0
  Flag  useint=0;                  // 1 if can use integer calculation
2049
0
  Flag  isoddint=0;                // 1 if rhs is an integer and odd
2050
0
  Int   i;                         // work
2051
  #if DECSUBSET
2052
  Int   dropped;                   // ..
2053
  #endif
2054
0
  uInt  needbytes;                 // buffer size needed
2055
0
  Flag  seenbit;                   // seen a bit while powering
2056
0
  Int   residue=0;                 // rounding residue
2057
0
  uInt  status=0;                  // accumulators
2058
0
  uByte bits=0;                    // result sign if errors
2059
0
  decContext aset;                 // working context
2060
0
  decNumber dnOne;                 // work value 1...
2061
  // local accumulator buffer [a decNumber, with digits+elength+1 digits]
2062
0
  decNumber dacbuff[D2N(DECBUFFER+9)];
2063
0
  decNumber *dac=dacbuff;          // -> result accumulator
2064
  // same again for possible 1/lhs calculation
2065
0
  decNumber invbuff[D2N(DECBUFFER+9)];
2066
2067
  #if DECCHECK
2068
  if (decCheckOperands(res, lhs, rhs, set)) return res;
2069
  #endif
2070
2071
0
  do {                             // protect allocated storage
2072
    #if DECSUBSET
2073
    if (!set->extended) { // reduce operands and set status, as needed
2074
      if (lhs->digits>reqdigits) {
2075
        alloclhs=decRoundOperand(lhs, set, &status);
2076
        if (alloclhs==NULL) break;
2077
        lhs=alloclhs;
2078
        }
2079
      if (rhs->digits>reqdigits) {
2080
        allocrhs=decRoundOperand(rhs, set, &status);
2081
        if (allocrhs==NULL) break;
2082
        rhs=allocrhs;
2083
        }
2084
      }
2085
    #endif
2086
    // [following code does not require input rounding]
2087
2088
    // handle NaNs and rhs Infinity (lhs infinity is harder)
2089
0
    if (SPECIALARGS) {
2090
0
      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
2091
0
        decNaNs(res, lhs, rhs, set, &status);
2092
0
        break;}
2093
0
      if (decNumberIsInfinite(rhs)) {   // rhs Infinity
2094
0
        Flag rhsneg=rhs->bits&DECNEG;   // save rhs sign
2095
0
        if (decNumberIsNegative(lhs)    // lhs<0
2096
0
         && !decNumberIsZero(lhs))      // ..
2097
0
          status|=DEC_Invalid_operation;
2098
0
         else {                         // lhs >=0
2099
0
          decNumberZero(&dnOne);        // set up 1
2100
0
          dnOne.lsu[0]=1;
2101
0
          decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1
2102
0
          decNumberZero(res);           // prepare for 0/1/Infinity
2103
0
          if (decNumberIsNegative(dac)) {    // lhs<1
2104
0
            if (rhsneg) res->bits|=DECINF;   // +Infinity [else is +0]
2105
0
            }
2106
0
           else if (dac->lsu[0]==0) {        // lhs=1
2107
            // 1**Infinity is inexact, so return fully-padded 1.0000
2108
0
            Int shift=set->digits-1;
2109
0
            *res->lsu=1;                     // was 0, make int 1
2110
0
            res->digits=decShiftToMost(res->lsu, 1, shift);
2111
0
            res->exponent=-shift;            // make 1.0000...
2112
0
            status|=DEC_Inexact|DEC_Rounded; // deemed inexact
2113
0
            }
2114
0
           else {                            // lhs>1
2115
0
            if (!rhsneg) res->bits|=DECINF;  // +Infinity [else is +0]
2116
0
            }
2117
0
          } // lhs>=0
2118
0
        break;}
2119
      // [lhs infinity drops through]
2120
0
      } // specials
2121
2122
    // Original rhs may be an integer that fits and is in range
2123
0
    n=decGetInt(rhs);
2124
0
    if (n!=BADINT) {                    // it is an integer
2125
0
      rhsint=1;                         // record the fact for 1**n
2126
0
      isoddint=(Flag)n&1;               // [works even if big]
2127
0
      if (n!=BIGEVEN && n!=BIGODD)      // can use integer path?
2128
0
        useint=1;                       // looks good
2129
0
      }
2130
2131
0
    if (decNumberIsNegative(lhs)        // -x ..
2132
0
      && isoddint) bits=DECNEG;         // .. to an odd power
2133
2134
    // handle LHS infinity
2135
0
    if (decNumberIsInfinite(lhs)) {     // [NaNs already handled]
2136
0
      uByte rbits=rhs->bits;            // save
2137
0
      decNumberZero(res);               // prepare
2138
0
      if (n==0) *res->lsu=1;            // [-]Inf**0 => 1
2139
0
       else {
2140
        // -Inf**nonint -> error
2141
0
        if (!rhsint && decNumberIsNegative(lhs)) {
2142
0
          status|=DEC_Invalid_operation;     // -Inf**nonint is error
2143
0
          break;}
2144
0
        if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n
2145
        // [otherwise will be 0 or -0]
2146
0
        res->bits=bits;
2147
0
        }
2148
0
      break;}
2149
2150
    // similarly handle LHS zero
2151
0
    if (decNumberIsZero(lhs)) {
2152
0
      if (n==0) {                            // 0**0 => Error
2153
        #if DECSUBSET
2154
        if (!set->extended) {                // [unless subset]
2155
          decNumberZero(res);
2156
          *res->lsu=1;                       // return 1
2157
          break;}
2158
        #endif
2159
0
        status|=DEC_Invalid_operation;
2160
0
        }
2161
0
       else {                                // 0**x
2162
0
        uByte rbits=rhs->bits;               // save
2163
0
        if (rbits & DECNEG) {                // was a 0**(-n)
2164
          #if DECSUBSET
2165
          if (!set->extended) {              // [bad if subset]
2166
            status|=DEC_Invalid_operation;
2167
            break;}
2168
          #endif
2169
0
          bits|=DECINF;
2170
0
          }
2171
0
        decNumberZero(res);                  // prepare
2172
        // [otherwise will be 0 or -0]
2173
0
        res->bits=bits;
2174
0
        }
2175
0
      break;}
2176
2177
    // here both lhs and rhs are finite; rhs==0 is handled in the
2178
    // integer path.  Next handle the non-integer cases
2179
0
    if (!useint) {                      // non-integral rhs
2180
      // any -ve lhs is bad, as is either operand or context out of
2181
      // bounds
2182
0
      if (decNumberIsNegative(lhs)) {
2183
0
        status|=DEC_Invalid_operation;
2184
0
        break;}
2185
0
      if (decCheckMath(lhs, set, &status)
2186
0
       || decCheckMath(rhs, set, &status)) break; // variable status
2187
2188
0
      decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
2189
0
      aset.emax=DEC_MAX_MATH;           // usual bounds
2190
0
      aset.emin=-DEC_MAX_MATH;          // ..
2191
0
      aset.clamp=0;                     // and no concrete format
2192
2193
      // calculate the result using exp(ln(lhs)*rhs), which can
2194
      // all be done into the accumulator, dac.  The precision needed
2195
      // is enough to contain the full information in the lhs (which
2196
      // is the total digits, including exponent), or the requested
2197
      // precision, if larger, + 4; 6 is used for the exponent
2198
      // maximum length, and this is also used when it is shorter
2199
      // than the requested digits as it greatly reduces the >0.5 ulp
2200
      // cases at little cost (because Ln doubles digits each
2201
      // iteration so a few extra digits rarely causes an extra
2202
      // iteration)
2203
0
      aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2204
0
      } // non-integer rhs
2205
2206
0
     else { // rhs is in-range integer
2207
0
      if (n==0) {                       // x**0 = 1
2208
        // (0**0 was handled above)
2209
0
        decNumberZero(res);             // result=1
2210
0
        *res->lsu=1;                    // ..
2211
0
        break;}
2212
      // rhs is a non-zero integer
2213
0
      if (n<0) n=-n;                    // use abs(n)
2214
2215
0
      aset=*set;                        // clone the context
2216
0
      aset.round=DEC_ROUND_HALF_EVEN;   // internally use balanced
2217
      // calculate the working DIGITS
2218
0
      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2219
      #if DECSUBSET
2220
      if (!set->extended) aset.digits--;     // use classic precision
2221
      #endif
2222
      // it's an error if this is more than can be handled
2223
0
      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2224
0
      } // integer path
2225
2226
    // aset.digits is the count of digits for the accumulator needed
2227
    // if accumulator is too long for local storage, then allocate
2228
0
    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2229
    // [needbytes also used below if 1/lhs needed]
2230
0
    if (needbytes>sizeof(dacbuff)) {
2231
0
      allocdac=(decNumber *)malloc(needbytes);
2232
0
      if (allocdac==NULL) {   // hopeless -- abandon
2233
0
        status|=DEC_Insufficient_storage;
2234
0
        break;}
2235
0
      dac=allocdac;           // use the allocated space
2236
0
      }
2237
    // here, aset is set up and accumulator is ready for use
2238
2239
0
    if (!useint) {                           // non-integral rhs
2240
      // x ** y; special-case x=1 here as it will otherwise always
2241
      // reduce to integer 1; decLnOp has a fastpath which detects
2242
      // the case of x=1
2243
0
      decLnOp(dac, lhs, &aset, &status);     // dac=ln(lhs)
2244
      // [no error possible, as lhs 0 already handled]
2245
0
      if (ISZERO(dac)) {                     // x==1, 1.0, etc.
2246
        // need to return fully-padded 1.0000 etc., but rhsint->1
2247
0
        *dac->lsu=1;                         // was 0, make int 1
2248
0
        if (!rhsint) {                       // add padding
2249
0
          Int shift=set->digits-1;
2250
0
          dac->digits=decShiftToMost(dac->lsu, 1, shift);
2251
0
          dac->exponent=-shift;              // make 1.0000...
2252
0
          status|=DEC_Inexact|DEC_Rounded;   // deemed inexact
2253
0
          }
2254
0
        }
2255
0
       else {
2256
0
        decMultiplyOp(dac, dac, rhs, &aset, &status);  // dac=dac*rhs
2257
0
        decExpOp(dac, dac, &aset, &status);            // dac=exp(dac)
2258
0
        }
2259
      // and drop through for final rounding
2260
0
      } // non-integer rhs
2261
2262
0
     else {                             // carry on with integer
2263
0
      decNumberZero(dac);               // acc=1
2264
0
      *dac->lsu=1;                      // ..
2265
2266
      // if a negative power the constant 1 is needed, and if not subset
2267
      // invert the lhs now rather than inverting the result later
2268
0
      if (decNumberIsNegative(rhs)) {   // was a **-n [hence digits>0]
2269
0
        decNumber *inv=invbuff;         // asssume use fixed buffer
2270
0
        decNumberCopy(&dnOne, dac);     // dnOne=1;  [needed now or later]
2271
        #if DECSUBSET
2272
        if (set->extended) {            // need to calculate 1/lhs
2273
        #endif
2274
          // divide lhs into 1, putting result in dac [dac=1/dac]
2275
0
          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2276
          // now locate or allocate space for the inverted lhs
2277
0
          if (needbytes>sizeof(invbuff)) {
2278
0
            allocinv=(decNumber *)malloc(needbytes);
2279
0
            if (allocinv==NULL) {       // hopeless -- abandon
2280
0
              status|=DEC_Insufficient_storage;
2281
0
              break;}
2282
0
            inv=allocinv;               // use the allocated space
2283
0
            }
2284
          // [inv now points to big-enough buffer or allocated storage]
2285
0
          decNumberCopy(inv, dac);      // copy the 1/lhs
2286
0
          decNumberCopy(dac, &dnOne);   // restore acc=1
2287
0
          lhs=inv;                      // .. and go forward with new lhs
2288
        #if DECSUBSET
2289
          }
2290
        #endif
2291
0
        }
2292
2293
      // Raise-to-the-power loop...
2294
0
      seenbit=0;                   // set once a 1-bit is encountered
2295
0
      for (i=1;;i++){              // for each bit [top bit ignored]
2296
        // abandon if had overflow or terminal underflow
2297
0
        if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?
2298
0
          if ((status&DEC_Overflow) || ISZERO(dac)) break;
2299
0
          }
2300
        // [the following two lines revealed an optimizer bug in a C++
2301
        // compiler, with symptom: 5**3 -> 25, when n=n+n was used]
2302
0
        n=n<<1;                    // move next bit to testable position
2303
0
        if (n<0) {                 // top bit is set
2304
0
          seenbit=1;               // OK, significant bit seen
2305
0
          decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x
2306
0
          }
2307
0
        if (i==31) break;          // that was the last bit
2308
0
        if (!seenbit) continue;    // no need to square 1
2309
0
        decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]
2310
0
        } /*i*/ // 32 bits
2311
2312
      // complete internal overflow or underflow processing
2313
0
      if (status & (DEC_Overflow|DEC_Underflow)) {
2314
        #if DECSUBSET
2315
        // If subset, and power was negative, reverse the kind of -erflow
2316
        // [1/x not yet done]
2317
        if (!set->extended && decNumberIsNegative(rhs)) {
2318
          if (status & DEC_Overflow)
2319
            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2320
           else { // trickier -- Underflow may or may not be set
2321
            status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]
2322
            status|=DEC_Overflow;
2323
            }
2324
          }
2325
        #endif
2326
0
        dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign
2327
        // round subnormals [to set.digits rather than aset.digits]
2328
        // or set overflow result similarly as required
2329
0
        decFinalize(dac, set, &residue, &status);
2330
0
        decNumberCopy(res, dac);   // copy to result (is now OK length)
2331
0
        break;
2332
0
        }
2333
2334
      #if DECSUBSET
2335
      if (!set->extended &&                  // subset math
2336
          decNumberIsNegative(rhs)) {        // was a **-n [hence digits>0]
2337
        // so divide result into 1 [dac=1/dac]
2338
        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2339
        }
2340
      #endif
2341
0
      } // rhs integer path
2342
2343
    // reduce result to the requested length and copy to result
2344
0
    decCopyFit(res, dac, set, &residue, &status);
2345
0
    decFinish(res, set, &residue, &status);  // final cleanup
2346
    #if DECSUBSET
2347
    if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros
2348
    #endif
2349
0
    } while(0);                         // end protected
2350
2351
0
  if (allocdac!=NULL) free(allocdac);   // drop any storage used
2352
0
  if (allocinv!=NULL) free(allocinv);   // ..
2353
  #if DECSUBSET
2354
  if (alloclhs!=NULL) free(alloclhs);   // ..
2355
  if (allocrhs!=NULL) free(allocrhs);   // ..
2356
  #endif
2357
0
  if (status!=0) decStatus(res, status, set);
2358
  #if DECCHECK
2359
  decCheckInexact(res, set);
2360
  #endif
2361
0
  return res;
2362
0
  } // decNumberPower
2363
2364
/* ------------------------------------------------------------------ */
2365
/* decNumberQuantize -- force exponent to requested value             */
2366
/*                                                                    */
2367
/*   This computes C = op(A, B), where op adjusts the coefficient     */
2368
/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2369
/*   of C has exponent of B.  The numerical value of C will equal A,  */
2370
/*   except for the effects of any rounding that occurred.            */
2371
/*                                                                    */
2372
/*   res is C, the result.  C may be A or B                           */
2373
/*   lhs is A, the number to adjust                                   */
2374
/*   rhs is B, the number with exponent to match                      */
2375
/*   set is the context                                               */
2376
/*                                                                    */
2377
/* C must have space for set->digits digits.                          */
2378
/*                                                                    */
2379
/* Unless there is an error or the result is infinite, the exponent   */
2380
/* after the operation is guaranteed to be equal to that of B.        */
2381
/* ------------------------------------------------------------------ */
2382
decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2383
0
                              const decNumber *rhs, decContext *set) {
2384
0
  uInt status=0;                        // accumulator
2385
0
  decQuantizeOp(res, lhs, rhs, set, 1, &status);
2386
0
  if (status!=0) decStatus(res, status, set);
2387
0
  return res;
2388
0
  } // decNumberQuantize
2389
2390
/* ------------------------------------------------------------------ */
2391
/* decNumberReduce -- remove trailing zeros                           */
2392
/*                                                                    */
2393
/*   This computes C = 0 + A, and normalizes the result               */
2394
/*                                                                    */
2395
/*   res is C, the result.  C may be A                                */
2396
/*   rhs is A                                                         */
2397
/*   set is the context                                               */
2398
/*                                                                    */
2399
/* C must have space for set->digits digits.                          */
2400
/* ------------------------------------------------------------------ */
2401
// Previously known as Normalize
2402
decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2403
0
                               decContext *set) {
2404
0
  return decNumberReduce(res, rhs, set);
2405
0
  } // decNumberNormalize
2406
2407
decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2408
0
                            decContext *set) {
2409
  #if DECSUBSET
2410
  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2411
  #endif
2412
0
  uInt status=0;                   // as usual
2413
0
  Int  residue=0;                  // as usual
2414
0
  Int  dropped;                    // work
2415
2416
  #if DECCHECK
2417
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2418
  #endif
2419
2420
0
  do {                             // protect allocated storage
2421
    #if DECSUBSET
2422
    if (!set->extended) {
2423
      // reduce operand and set lostDigits status, as needed
2424
      if (rhs->digits>set->digits) {
2425
        allocrhs=decRoundOperand(rhs, set, &status);
2426
        if (allocrhs==NULL) break;
2427
        rhs=allocrhs;
2428
        }
2429
      }
2430
    #endif
2431
    // [following code does not require input rounding]
2432
2433
    // Infinities copy through; NaNs need usual treatment
2434
0
    if (decNumberIsNaN(rhs)) {
2435
0
      decNaNs(res, rhs, NULL, set, &status);
2436
0
      break;
2437
0
      }
2438
2439
    // reduce result to the requested length and copy to result
2440
0
    decCopyFit(res, rhs, set, &residue, &status); // copy & round
2441
0
    decFinish(res, set, &residue, &status);       // cleanup/set flags
2442
0
    decTrim(res, set, 1, 0, &dropped);            // normalize in place
2443
                                                  // [may clamp]
2444
0
    } while(0);                              // end protected
2445
2446
  #if DECSUBSET
2447
  if (allocrhs !=NULL) free(allocrhs);       // ..
2448
  #endif
2449
0
  if (status!=0) decStatus(res, status, set);// then report status
2450
0
  return res;
2451
0
  } // decNumberReduce
2452
2453
/* ------------------------------------------------------------------ */
2454
/* decNumberRescale -- force exponent to requested value              */
2455
/*                                                                    */
2456
/*   This computes C = op(A, B), where op adjusts the coefficient     */
2457
/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2458
/*   of C has the value B.  The numerical value of C will equal A,    */
2459
/*   except for the effects of any rounding that occurred.            */
2460
/*                                                                    */
2461
/*   res is C, the result.  C may be A or B                           */
2462
/*   lhs is A, the number to adjust                                   */
2463
/*   rhs is B, the requested exponent                                 */
2464
/*   set is the context                                               */
2465
/*                                                                    */
2466
/* C must have space for set->digits digits.                          */
2467
/*                                                                    */
2468
/* Unless there is an error or the result is infinite, the exponent   */
2469
/* after the operation is guaranteed to be equal to B.                */
2470
/* ------------------------------------------------------------------ */
2471
decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2472
0
                             const decNumber *rhs, decContext *set) {
2473
0
  uInt status=0;                        // accumulator
2474
0
  decQuantizeOp(res, lhs, rhs, set, 0, &status);
2475
0
  if (status!=0) decStatus(res, status, set);
2476
0
  return res;
2477
0
  } // decNumberRescale
2478
2479
/* ------------------------------------------------------------------ */
2480
/* decNumberRemainder -- divide and return remainder                  */
2481
/*                                                                    */
2482
/*   This computes C = A % B                                          */
2483
/*                                                                    */
2484
/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2485
/*   lhs is A                                                         */
2486
/*   rhs is B                                                         */
2487
/*   set is the context                                               */
2488
/*                                                                    */
2489
/* C must have space for set->digits digits.                          */
2490
/* ------------------------------------------------------------------ */
2491
decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2492
0
                               const decNumber *rhs, decContext *set) {
2493
0
  uInt status=0;                        // accumulator
2494
0
  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2495
0
  if (status!=0) decStatus(res, status, set);
2496
  #if DECCHECK
2497
  decCheckInexact(res, set);
2498
  #endif
2499
0
  return res;
2500
0
  } // decNumberRemainder
2501
2502
/* ------------------------------------------------------------------ */
2503
/* decNumberRemainderNear -- divide and return remainder from nearest */
2504
/*                                                                    */
2505
/*   This computes C = A % B, where % is the IEEE remainder operator  */
2506
/*                                                                    */
2507
/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2508
/*   lhs is A                                                         */
2509
/*   rhs is B                                                         */
2510
/*   set is the context                                               */
2511
/*                                                                    */
2512
/* C must have space for set->digits digits.                          */
2513
/* ------------------------------------------------------------------ */
2514
decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2515
0
                                   const decNumber *rhs, decContext *set) {
2516
0
  uInt status=0;                        // accumulator
2517
0
  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2518
0
  if (status!=0) decStatus(res, status, set);
2519
  #if DECCHECK
2520
  decCheckInexact(res, set);
2521
  #endif
2522
0
  return res;
2523
0
  } // decNumberRemainderNear
2524
2525
/* ------------------------------------------------------------------ */
2526
/* decNumberRotate -- rotate the coefficient of a Number left/right   */
2527
/*                                                                    */
2528
/*   This computes C = A rot B  (in base ten and rotating set->digits */
2529
/*   digits).                                                         */
2530
/*                                                                    */
2531
/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2532
/*   lhs is A                                                         */
2533
/*   rhs is B, the number of digits to rotate (-ve to right)          */
2534
/*   set is the context                                               */
2535
/*                                                                    */
2536
/* The digits of the coefficient of A are rotated to the left (if B   */
2537
/* is positive) or to the right (if B is negative) without adjusting  */
2538
/* the exponent or the sign of A.  If lhs->digits is less than        */
2539
/* set->digits the coefficient is padded with zeros on the left       */
2540
/* before the rotate.  Any leading zeros in the result are removed    */
2541
/* as usual.                                                          */
2542
/*                                                                    */
2543
/* B must be an integer (q=0) and in the range -set->digits through   */
2544
/* +set->digits.                                                      */
2545
/* C must have space for set->digits digits.                          */
2546
/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2547
/* B must be valid).  No status is set unless B is invalid or an      */
2548
/* operand is an sNaN.                                                */
2549
/* ------------------------------------------------------------------ */
2550
decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2551
0
                           const decNumber *rhs, decContext *set) {
2552
0
  uInt status=0;              // accumulator
2553
0
  Int  rotate;                // rhs as an Int
2554
2555
  #if DECCHECK
2556
  if (decCheckOperands(res, lhs, rhs, set)) return res;
2557
  #endif
2558
2559
  // NaNs propagate as normal
2560
0
  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2561
0
    decNaNs(res, lhs, rhs, set, &status);
2562
   // rhs must be an integer
2563
0
   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2564
0
    status=DEC_Invalid_operation;
2565
0
   else { // both numeric, rhs is an integer
2566
0
    rotate=decGetInt(rhs);                   // [cannot fail]
2567
0
    if (rotate==BADINT                       // something bad ..
2568
0
     || rotate==BIGODD || rotate==BIGEVEN    // .. very big ..
2569
0
     || abs(rotate)>set->digits)             // .. or out of range
2570
0
      status=DEC_Invalid_operation;
2571
0
     else {                                  // rhs is OK
2572
0
      decNumberCopy(res, lhs);
2573
      // convert -ve rotate to equivalent positive rotation
2574
0
      if (rotate<0) rotate=set->digits+rotate;
2575
0
      if (rotate!=0 && rotate!=set->digits   // zero or full rotation
2576
0
       && !decNumberIsInfinite(res)) {       // lhs was infinite
2577
        // left-rotate to do; 0 < rotate < set->digits
2578
0
        uInt units, shift;                   // work
2579
0
        uInt msudigits;                      // digits in result msu
2580
0
        Unit *msu=res->lsu+D2U(res->digits)-1;    // current msu
2581
0
        Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu
2582
0
        for (msu++; msu<=msumax; msu++) *msu=0;   // ensure high units=0
2583
0
        res->digits=set->digits;                  // now full-length
2584
0
        msudigits=MSUDIGITS(res->digits);         // actual digits in msu
2585
2586
        // rotation here is done in-place, in three steps
2587
        // 1. shift all to least up to one unit to unit-align final
2588
        //    lsd [any digits shifted out are rotated to the left,
2589
        //    abutted to the original msd (which may require split)]
2590
        //
2591
        //    [if there are no whole units left to rotate, the
2592
        //    rotation is now complete]
2593
        //
2594
        // 2. shift to least, from below the split point only, so that
2595
        //    the final msd is in the right place in its Unit [any
2596
        //    digits shifted out will fit exactly in the current msu,
2597
        //    left aligned, no split required]
2598
        //
2599
        // 3. rotate all the units by reversing left part, right
2600
        //    part, and then whole
2601
        //
2602
        // example: rotate right 8 digits (2 units + 2), DECDPUN=3.
2603
        //
2604
        //   start: 00a bcd efg hij klm npq
2605
        //
2606
        //      1a  000 0ab cde fgh|ijk lmn [pq saved]
2607
        //      1b  00p qab cde fgh|ijk lmn
2608
        //
2609
        //      2a  00p qab cde fgh|00i jkl [mn saved]
2610
        //      2b  mnp qab cde fgh|00i jkl
2611
        //
2612
        //      3a  fgh cde qab mnp|00i jkl
2613
        //      3b  fgh cde qab mnp|jkl 00i
2614
        //      3c  00i jkl mnp qab cde fgh
2615
2616
        // Step 1: amount to shift is the partial right-rotate count
2617
0
        rotate=set->digits-rotate;      // make it right-rotate
2618
0
        units=rotate/DECDPUN;           // whole units to rotate
2619
0
        shift=rotate%DECDPUN;           // left-over digits count
2620
0
        if (shift>0) {                  // not an exact number of units
2621
0
          uInt save=res->lsu[0]%powers[shift];    // save low digit(s)
2622
0
          decShiftToLeast(res->lsu, D2U(res->digits), shift);
2623
0
          if (shift>msudigits) {        // msumax-1 needs >0 digits
2624
0
            uInt rem=save%powers[shift-msudigits];// split save
2625
0
            *msumax=(Unit)(save/powers[shift-msudigits]); // and insert
2626
0
            *(msumax-1)=*(msumax-1)
2627
0
                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..
2628
0
            }
2629
0
           else { // all fits in msumax
2630
0
            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]
2631
0
            }
2632
0
          } // digits shift needed
2633
2634
        // If whole units to rotate...
2635
0
        if (units>0) {                  // some to do
2636
          // Step 2: the units to touch are the whole ones in rotate,
2637
          //   if any, and the shift is DECDPUN-msudigits (which may be
2638
          //   0, again)
2639
0
          shift=DECDPUN-msudigits;
2640
0
          if (shift>0) {                // not an exact number of units
2641
0
            uInt save=res->lsu[0]%powers[shift];  // save low digit(s)
2642
0
            decShiftToLeast(res->lsu, units, shift);
2643
0
            *msumax=*msumax+(Unit)(save*powers[msudigits]);
2644
0
            } // partial shift needed
2645
2646
          // Step 3: rotate the units array using triple reverse
2647
          // (reversing is easy and fast)
2648
0
          decReverse(res->lsu+units, msumax);     // left part
2649
0
          decReverse(res->lsu, res->lsu+units-1); // right part
2650
0
          decReverse(res->lsu, msumax);           // whole
2651
0
          } // whole units to rotate
2652
        // the rotation may have left an undetermined number of zeros
2653
        // on the left, so true length needs to be calculated
2654
0
        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2655
0
        } // rotate needed
2656
0
      } // rhs OK
2657
0
    } // numerics
2658
0
  if (status!=0) decStatus(res, status, set);
2659
0
  return res;
2660
0
  } // decNumberRotate
2661
2662
/* ------------------------------------------------------------------ */
2663
/* decNumberSameQuantum -- test for equal exponents                   */
2664
/*                                                                    */
2665
/*   res is the result number, which will contain either 0 or 1       */
2666
/*   lhs is a number to test                                          */
2667
/*   rhs is the second (usually a pattern)                            */
2668
/*                                                                    */
2669
/* No errors are possible and no context is needed.                   */
2670
/* ------------------------------------------------------------------ */
2671
decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2672
0
                                 const decNumber *rhs) {
2673
0
  Unit ret=0;                      // return value
2674
2675
  #if DECCHECK
2676
  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2677
  #endif
2678
2679
0
  if (SPECIALARGS) {
2680
0
    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2681
0
     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2682
     // [anything else with a special gives 0]
2683
0
    }
2684
0
   else if (lhs->exponent==rhs->exponent) ret=1;
2685
2686
0
  decNumberZero(res);              // OK to overwrite an operand now
2687
0
  *res->lsu=ret;
2688
0
  return res;
2689
0
  } // decNumberSameQuantum
2690
2691
/* ------------------------------------------------------------------ */
2692
/* decNumberScaleB -- multiply by a power of 10                       */
2693
/*                                                                    */
2694
/* This computes C = A x 10**B where B is an integer (q=0) with       */
2695
/* maximum magnitude 2*(emax+digits)                                  */
2696
/*                                                                    */
2697
/*   res is C, the result.  C may be A or B                           */
2698
/*   lhs is A, the number to adjust                                   */
2699
/*   rhs is B, the requested power of ten to use                      */
2700
/*   set is the context                                               */
2701
/*                                                                    */
2702
/* C must have space for set->digits digits.                          */
2703
/*                                                                    */
2704
/* The result may underflow or overflow.                              */
2705
/* ------------------------------------------------------------------ */
2706
decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2707
0
                            const decNumber *rhs, decContext *set) {
2708
0
  Int  reqexp;                // requested exponent change [B]
2709
0
  uInt status=0;              // accumulator
2710
0
  Int  residue;               // work
2711
2712
  #if DECCHECK
2713
  if (decCheckOperands(res, lhs, rhs, set)) return res;
2714
  #endif
2715
2716
  // Handle special values except lhs infinite
2717
0
  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2718
0
    decNaNs(res, lhs, rhs, set, &status);
2719
    // rhs must be an integer
2720
0
   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2721
0
    status=DEC_Invalid_operation;
2722
0
   else {
2723
    // lhs is a number; rhs is a finite with q==0
2724
0
    reqexp=decGetInt(rhs);                   // [cannot fail]
2725
    // maximum range is larger than getInt can handle, so this is
2726
    // more restrictive than the specification
2727
0
    if (reqexp==BADINT                       // something bad ..
2728
0
     || reqexp==BIGODD || reqexp==BIGEVEN    // it was huge
2729
0
     || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range
2730
0
      status=DEC_Invalid_operation;
2731
0
     else {                                  // rhs is OK
2732
0
      decNumberCopy(res, lhs);               // all done if infinite lhs
2733
0
      if (!decNumberIsInfinite(res)) {       // prepare to scale
2734
0
        Int exp=res->exponent;               // save for overflow test
2735
0
        res->exponent+=reqexp;               // adjust the exponent
2736
0
        if (((exp^reqexp)>=0)                // same sign ...
2737
0
         && ((exp^res->exponent)<0)) {       // .. but result had different
2738
          // the calculation overflowed, so force right treatment
2739
0
          if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;
2740
0
           else      res->exponent=DEC_MAX_EMAX+1;
2741
0
          }
2742
0
        residue=0;
2743
0
        decFinalize(res, set, &residue, &status); // final check
2744
0
        } // finite LHS
2745
0
      } // rhs OK
2746
0
    } // rhs finite
2747
0
  if (status!=0) decStatus(res, status, set);
2748
0
  return res;
2749
0
  } // decNumberScaleB
2750
2751
/* ------------------------------------------------------------------ */
2752
/* decNumberShift -- shift the coefficient of a Number left or right  */
2753
/*                                                                    */
2754
/*   This computes C = A << B or C = A >> -B  (in base ten).          */
2755
/*                                                                    */
2756
/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2757
/*   lhs is A                                                         */
2758
/*   rhs is B, the number of digits to shift (-ve to right)           */
2759
/*   set is the context                                               */
2760
/*                                                                    */
2761
/* The digits of the coefficient of A are shifted to the left (if B   */
2762
/* is positive) or to the right (if B is negative) without adjusting  */
2763
/* the exponent or the sign of A.                                     */
2764
/*                                                                    */
2765
/* B must be an integer (q=0) and in the range -set->digits through   */
2766
/* +set->digits.                                                      */
2767
/* C must have space for set->digits digits.                          */
2768
/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2769
/* B must be valid).  No status is set unless B is invalid or an      */
2770
/* operand is an sNaN.                                                */
2771
/* ------------------------------------------------------------------ */
2772
decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2773
0
                           const decNumber *rhs, decContext *set) {
2774
0
  uInt status=0;              // accumulator
2775
0
  Int  shift;                 // rhs as an Int
2776
2777
  #if DECCHECK
2778
  if (decCheckOperands(res, lhs, rhs, set)) return res;
2779
  #endif
2780
2781
  // NaNs propagate as normal
2782
0
  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2783
0
    decNaNs(res, lhs, rhs, set, &status);
2784
   // rhs must be an integer
2785
0
   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2786
0
    status=DEC_Invalid_operation;
2787
0
   else { // both numeric, rhs is an integer
2788
0
    shift=decGetInt(rhs);                    // [cannot fail]
2789
0
    if (shift==BADINT                        // something bad ..
2790
0
     || shift==BIGODD || shift==BIGEVEN      // .. very big ..
2791
0
     || abs(shift)>set->digits)              // .. or out of range
2792
0
      status=DEC_Invalid_operation;
2793
0
     else {                                  // rhs is OK
2794
0
      decNumberCopy(res, lhs);
2795
0
      if (shift!=0 && !decNumberIsInfinite(res)) { // something to do
2796
0
        if (shift>0) {                       // to left
2797
0
          if (shift==set->digits) {          // removing all
2798
0
            *res->lsu=0;                     // so place 0
2799
0
            res->digits=1;                   // ..
2800
0
            }
2801
0
           else {                            //
2802
            // first remove leading digits if necessary
2803
0
            if (res->digits+shift>set->digits) {
2804
0
              decDecap(res, res->digits+shift-set->digits);
2805
              // that updated res->digits; may have gone to 1 (for a
2806
              // single digit or for zero
2807
0
              }
2808
0
            if (res->digits>1 || *res->lsu)  // if non-zero..
2809
0
              res->digits=decShiftToMost(res->lsu, res->digits, shift);
2810
0
            } // partial left
2811
0
          } // left
2812
0
         else { // to right
2813
0
          if (-shift>=res->digits) {         // discarding all
2814
0
            *res->lsu=0;                     // so place 0
2815
0
            res->digits=1;                   // ..
2816
0
            }
2817
0
           else {
2818
0
            decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2819
0
            res->digits-=(-shift);
2820
0
            }
2821
0
          } // to right
2822
0
        } // non-0 non-Inf shift
2823
0
      } // rhs OK
2824
0
    } // numerics
2825
0
  if (status!=0) decStatus(res, status, set);
2826
0
  return res;
2827
0
  } // decNumberShift
2828
2829
/* ------------------------------------------------------------------ */
2830
/* decNumberSquareRoot -- square root operator                        */
2831
/*                                                                    */
2832
/*   This computes C = squareroot(A)                                  */
2833
/*                                                                    */
2834
/*   res is C, the result.  C may be A                                */
2835
/*   rhs is A                                                         */
2836
/*   set is the context; note that rounding mode has no effect        */
2837
/*                                                                    */
2838
/* C must have space for set->digits digits.                          */
2839
/* ------------------------------------------------------------------ */
2840
/* This uses the following varying-precision algorithm in:            */
2841
/*                                                                    */
2842
/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2843
/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2844
/*   pp229-237, ACM, September 1985.                                  */
2845
/*                                                                    */
2846
/* The square-root is calculated using Newton's method, after which   */
2847
/* a check is made to ensure the result is correctly rounded.         */
2848
/*                                                                    */
2849
/* % [Reformatted original Numerical Turing source code follows.]     */
2850
/* function sqrt(x : real) : real                                     */
2851
/* % sqrt(x) returns the properly rounded approximation to the square */
2852
/* % root of x, in the precision of the calling environment, or it    */
2853
/* % fails if x < 0.                                                  */
2854
/* % t e hull and a abrham, august, 1984                              */
2855
/* if x <= 0 then                                                     */
2856
/*   if x < 0 then                                                    */
2857
/*     assert false                                                   */
2858
/*   else                                                             */
2859
/*     result 0                                                       */
2860
/*   end if                                                           */
2861
/* end if                                                             */
2862
/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2863
/* var e := getexp(x)     % exponent part of x                        */
2864
/* var approx : real                                                  */
2865
/* if e mod 2 = 0  then                                               */
2866
/*   approx := .259 + .819 * f   % approx to root of f                */
2867
/* else                                                               */
2868
/*   f := f/l0                   % adjustments                        */
2869
/*   e := e + 1                  %   for odd                          */
2870
/*   approx := .0819 + 2.59 * f  %   exponent                         */
2871
/* end if                                                             */
2872
/*                                                                    */
2873
/* var p:= 3                                                          */
2874
/* const maxp := currentprecision + 2                                 */
2875
/* loop                                                               */
2876
/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2877
/*   precision p                                                      */
2878
/*   approx := .5 * (approx + f/approx)                               */
2879
/*   exit when p = maxp                                               */
2880
/* end loop                                                           */
2881
/*                                                                    */
2882
/* % approx is now within 1 ulp of the properly rounded square root   */
2883
/* % of f; to ensure proper rounding, compare squares of (approx -    */
2884
/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2885
/* p := currentprecision                                              */
2886
/* begin                                                              */
2887
/*   precision p + 2                                                  */
2888
/*   const approxsubhalf := approx - setexp(.5, -p)                   */
2889
/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2890
/*     approx := approx - setexp(.l, -p + 1)                          */
2891
/*   else                                                             */
2892
/*     const approxaddhalf := approx + setexp(.5, -p)                 */
2893
/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2894
/*       approx := approx + setexp(.l, -p + 1)                        */
2895
/*     end if                                                         */
2896
/*   end if                                                           */
2897
/* end                                                                */
2898
/* result setexp(approx, e div 2)  % fix exponent                     */
2899
/* end sqrt                                                           */
2900
/* ------------------------------------------------------------------ */
2901
decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2902
0
                                decContext *set) {
2903
0
  decContext workset, approxset;   // work contexts
2904
0
  decNumber dzero;                 // used for constant zero
2905
0
  Int  maxp;                       // largest working precision
2906
0
  Int  workp;                      // working precision
2907
0
  Int  residue=0;                  // rounding residue
2908
0
  uInt status=0, ignore=0;         // status accumulators
2909
0
  uInt rstatus;                    // ..
2910
0
  Int  exp;                        // working exponent
2911
0
  Int  ideal;                      // ideal (preferred) exponent
2912
0
  Int  needbytes;                  // work
2913
0
  Int  dropped;                    // ..
2914
2915
  #if DECSUBSET
2916
  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2917
  #endif
2918
  // buffer for f [needs +1 in case DECBUFFER 0]
2919
0
  decNumber buff[D2N(DECBUFFER+1)];
2920
  // buffer for a [needs +2 to match likely maxp]
2921
0
  decNumber bufa[D2N(DECBUFFER+2)];
2922
  // buffer for temporary, b [must be same size as a]
2923
0
  decNumber bufb[D2N(DECBUFFER+2)];
2924
0
  decNumber *allocbuff=NULL;       // -> allocated buff, iff allocated
2925
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
2926
0
  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
2927
0
  decNumber *f=buff;               // reduced fraction
2928
0
  decNumber *a=bufa;               // approximation to result
2929
0
  decNumber *b=bufb;               // intermediate result
2930
  // buffer for temporary variable, up to 3 digits
2931
0
  decNumber buft[D2N(3)];
2932
0
  decNumber *t=buft;               // up-to-3-digit constant or work
2933
2934
  #if DECCHECK
2935
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2936
  #endif
2937
2938
0
  do {                             // protect allocated storage
2939
    #if DECSUBSET
2940
    if (!set->extended) {
2941
      // reduce operand and set lostDigits status, as needed
2942
      if (rhs->digits>set->digits) {
2943
        allocrhs=decRoundOperand(rhs, set, &status);
2944
        if (allocrhs==NULL) break;
2945
        // [Note: 'f' allocation below could reuse this buffer if
2946
        // used, but as this is rare they are kept separate for clarity.]
2947
        rhs=allocrhs;
2948
        }
2949
      }
2950
    #endif
2951
    // [following code does not require input rounding]
2952
2953
    // handle infinities and NaNs
2954
0
    if (SPECIALARG) {
2955
0
      if (decNumberIsInfinite(rhs)) {         // an infinity
2956
0
        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2957
0
         else decNumberCopy(res, rhs);        // +Infinity
2958
0
        }
2959
0
       else decNaNs(res, rhs, NULL, set, &status); // a NaN
2960
0
      break;
2961
0
      }
2962
2963
    // calculate the ideal (preferred) exponent [floor(exp/2)]
2964
    // [It would be nicer to write: ideal=rhs->exponent>>1, but this
2965
    // generates a compiler warning.  Generated code is the same.]
2966
0
    ideal=(rhs->exponent&~1)/2;         // target
2967
2968
    // handle zeros
2969
0
    if (ISZERO(rhs)) {
2970
0
      decNumberCopy(res, rhs);          // could be 0 or -0
2971
0
      res->exponent=ideal;              // use the ideal [safe]
2972
      // use decFinish to clamp any out-of-range exponent, etc.
2973
0
      decFinish(res, set, &residue, &status);
2974
0
      break;
2975
0
      }
2976
2977
    // any other -x is an oops
2978
0
    if (decNumberIsNegative(rhs)) {
2979
0
      status|=DEC_Invalid_operation;
2980
0
      break;
2981
0
      }
2982
2983
    // space is needed for three working variables
2984
    //   f -- the same precision as the RHS, reduced to 0.01->0.99...
2985
    //   a -- Hull's approximation -- precision, when assigned, is
2986
    //        currentprecision+1 or the input argument precision,
2987
    //        whichever is larger (+2 for use as temporary)
2988
    //   b -- intermediate temporary result (same size as a)
2989
    // if any is too long for local storage, then allocate
2990
0
    workp=MAXI(set->digits+1, rhs->digits);  // actual rounding precision
2991
0
    workp=MAXI(workp, 7);                    // at least 7 for low cases
2992
0
    maxp=workp+2;                            // largest working precision
2993
2994
0
    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2995
0
    if (needbytes>(Int)sizeof(buff)) {
2996
0
      allocbuff=(decNumber *)malloc(needbytes);
2997
0
      if (allocbuff==NULL) {  // hopeless -- abandon
2998
0
        status|=DEC_Insufficient_storage;
2999
0
        break;}
3000
0
      f=allocbuff;            // use the allocated space
3001
0
      }
3002
    // a and b both need to be able to hold a maxp-length number
3003
0
    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
3004
0
    if (needbytes>(Int)sizeof(bufa)) {            // [same applies to b]
3005
0
      allocbufa=(decNumber *)malloc(needbytes);
3006
0
      allocbufb=(decNumber *)malloc(needbytes);
3007
0
      if (allocbufa==NULL || allocbufb==NULL) {   // hopeless
3008
0
        status|=DEC_Insufficient_storage;
3009
0
        break;}
3010
0
      a=allocbufa;            // use the allocated spaces
3011
0
      b=allocbufb;            // ..
3012
0
      }
3013
3014
    // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1
3015
0
    decNumberCopy(f, rhs);
3016
0
    exp=f->exponent+f->digits;               // adjusted to Hull rules
3017
0
    f->exponent=-(f->digits);                // to range
3018
3019
    // set up working context
3020
0
    decContextDefault(&workset, DEC_INIT_DECIMAL64);
3021
0
    workset.emax=DEC_MAX_EMAX;
3022
0
    workset.emin=DEC_MIN_EMIN;
3023
3024
    // [Until further notice, no error is possible and status bits
3025
    // (Rounded, etc.) should be ignored, not accumulated.]
3026
3027
    // Calculate initial approximation, and allow for odd exponent
3028
0
    workset.digits=workp;                    // p for initial calculation
3029
0
    t->bits=0; t->digits=3;
3030
0
    a->bits=0; a->digits=3;
3031
0
    if ((exp & 1)==0) {                      // even exponent
3032
      // Set t=0.259, a=0.819
3033
0
      t->exponent=-3;
3034
0
      a->exponent=-3;
3035
0
      #if DECDPUN>=3
3036
0
        t->lsu[0]=259;
3037
0
        a->lsu[0]=819;
3038
      #elif DECDPUN==2
3039
        t->lsu[0]=59; t->lsu[1]=2;
3040
        a->lsu[0]=19; a->lsu[1]=8;
3041
      #else
3042
        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
3043
        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
3044
      #endif
3045
0
      }
3046
0
     else {                                  // odd exponent
3047
      // Set t=0.0819, a=2.59
3048
0
      f->exponent--;                         // f=f/10
3049
0
      exp++;                                 // e=e+1
3050
0
      t->exponent=-4;
3051
0
      a->exponent=-2;
3052
0
      #if DECDPUN>=3
3053
0
        t->lsu[0]=819;
3054
0
        a->lsu[0]=259;
3055
      #elif DECDPUN==2
3056
        t->lsu[0]=19; t->lsu[1]=8;
3057
        a->lsu[0]=59; a->lsu[1]=2;
3058
      #else
3059
        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
3060
        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
3061
      #endif
3062
0
      }
3063
3064
0
    decMultiplyOp(a, a, f, &workset, &ignore);    // a=a*f
3065
0
    decAddOp(a, a, t, &workset, 0, &ignore);      // ..+t
3066
    // [a is now the initial approximation for sqrt(f), calculated with
3067
    // currentprecision, which is also a's precision.]
3068
3069
    // the main calculation loop
3070
0
    decNumberZero(&dzero);                   // make 0
3071
0
    decNumberZero(t);                        // set t = 0.5
3072
0
    t->lsu[0]=5;                             // ..
3073
0
    t->exponent=-1;                          // ..
3074
0
    workset.digits=3;                        // initial p
3075
0
    for (; workset.digits<maxp;) {
3076
      // set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]
3077
0
      workset.digits=MINI(workset.digits*2-2, maxp);
3078
      // a = 0.5 * (a + f/a)
3079
      // [calculated at p then rounded to currentprecision]
3080
0
      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a
3081
0
      decAddOp(b, b, a, &workset, 0, &ignore);         // b=b+a
3082
0
      decMultiplyOp(a, b, t, &workset, &ignore);       // a=b*0.5
3083
0
      } // loop
3084
3085
    // Here, 0.1 <= a < 1 [Hull], and a has maxp digits
3086
    // now reduce to length, etc.; this needs to be done with a
3087
    // having the correct exponent so as to handle subnormals
3088
    // correctly
3089
0
    approxset=*set;                          // get emin, emax, etc.
3090
0
    approxset.round=DEC_ROUND_HALF_EVEN;
3091
0
    a->exponent+=exp/2;                      // set correct exponent
3092
0
    rstatus=0;                               // clear status
3093
0
    residue=0;                               // .. and accumulator
3094
0
    decCopyFit(a, a, &approxset, &residue, &rstatus);  // reduce (if needed)
3095
0
    decFinish(a, &approxset, &residue, &rstatus);      // clean and finalize
3096
3097
    // Overflow was possible if the input exponent was out-of-range,
3098
    // in which case quit
3099
0
    if (rstatus&DEC_Overflow) {
3100
0
      status=rstatus;                        // use the status as-is
3101
0
      decNumberCopy(res, a);                 // copy to result
3102
0
      break;
3103
0
      }
3104
3105
    // Preserve status except Inexact/Rounded
3106
0
    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3107
3108
    // Carry out the Hull correction
3109
0
    a->exponent-=exp/2;                      // back to 0.1->1
3110
3111
    // a is now at final precision and within 1 ulp of the properly
3112
    // rounded square root of f; to ensure proper rounding, compare
3113
    // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.
3114
    // Here workset.digits=maxp and t=0.5, and a->digits determines
3115
    // the ulp
3116
0
    workset.digits--;                             // maxp-1 is OK now
3117
0
    t->exponent=-a->digits-1;                     // make 0.5 ulp
3118
0
    decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp
3119
0
    workset.round=DEC_ROUND_UP;
3120
0
    decMultiplyOp(b, b, b, &workset, &ignore);    // b = mulru(b, b)
3121
0
    decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed
3122
0
    if (decNumberIsNegative(b)) {                 // f < b [i.e., b > f]
3123
      // this is the more common adjustment, though both are rare
3124
0
      t->exponent++;                              // make 1.0 ulp
3125
0
      t->lsu[0]=1;                                // ..
3126
0
      decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp
3127
      // assign to approx [round to length]
3128
0
      approxset.emin-=exp/2;                      // adjust to match a
3129
0
      approxset.emax-=exp/2;
3130
0
      decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3131
0
      }
3132
0
     else {
3133
0
      decAddOp(b, a, t, &workset, 0, &ignore);    // b = a + 0.5 ulp
3134
0
      workset.round=DEC_ROUND_DOWN;
3135
0
      decMultiplyOp(b, b, b, &workset, &ignore);  // b = mulrd(b, b)
3136
0
      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   // b ? f
3137
0
      if (decNumberIsNegative(b)) {               // b < f
3138
0
        t->exponent++;                            // make 1.0 ulp
3139
0
        t->lsu[0]=1;                              // ..
3140
0
        decAddOp(a, a, t, &workset, 0, &ignore);  // a = a + 1 ulp
3141
        // assign to approx [round to length]
3142
0
        approxset.emin-=exp/2;                    // adjust to match a
3143
0
        approxset.emax-=exp/2;
3144
0
        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3145
0
        }
3146
0
      }
3147
    // [no errors are possible in the above, and rounding/inexact during
3148
    // estimation are irrelevant, so status was not accumulated]
3149
3150
    // Here, 0.1 <= a < 1  (still), so adjust back
3151
0
    a->exponent+=exp/2;                      // set correct exponent
3152
3153
    // count droppable zeros [after any subnormal rounding] by
3154
    // trimming a copy
3155
0
    decNumberCopy(b, a);
3156
0
    decTrim(b, set, 1, 1, &dropped);         // [drops trailing zeros]
3157
3158
    // Set Inexact and Rounded.  The answer can only be exact if
3159
    // it is short enough so that squaring it could fit in workp
3160
    // digits, so this is the only (relatively rare) condition that
3161
    // a careful check is needed
3162
0
    if (b->digits*2-1 > workp) {             // cannot fit
3163
0
      status|=DEC_Inexact|DEC_Rounded;
3164
0
      }
3165
0
     else {                                  // could be exact/unrounded
3166
0
      uInt mstatus=0;                        // local status
3167
0
      decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply
3168
0
      if (mstatus&DEC_Overflow) {            // result just won't fit
3169
0
        status|=DEC_Inexact|DEC_Rounded;
3170
0
        }
3171
0
       else {                                // plausible
3172
0
        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs
3173
0
        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal
3174
0
         else {                              // is Exact
3175
          // here, dropped is the count of trailing zeros in 'a'
3176
          // use closest exponent to ideal...
3177
0
          Int todrop=ideal-a->exponent;      // most that can be dropped
3178
0
          if (todrop<0) status|=DEC_Rounded; // ideally would add 0s
3179
0
           else {                            // unrounded
3180
            // there are some to drop, but emax may not allow all
3181
0
            Int maxexp=set->emax-set->digits+1;
3182
0
            Int maxdrop=maxexp-a->exponent;
3183
0
            if (todrop>maxdrop && set->clamp) { // apply clamping
3184
0
              todrop=maxdrop;
3185
0
              status|=DEC_Clamped;
3186
0
              }
3187
0
            if (dropped<todrop) {            // clamp to those available
3188
0
              todrop=dropped;
3189
0
              status|=DEC_Clamped;
3190
0
              }
3191
0
            if (todrop>0) {                  // have some to drop
3192
0
              decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3193
0
              a->exponent+=todrop;           // maintain numerical value
3194
0
              a->digits-=todrop;             // new length
3195
0
              }
3196
0
            }
3197
0
          }
3198
0
        }
3199
0
      }
3200
3201
    // double-check Underflow, as perhaps the result could not have
3202
    // been subnormal (initial argument too big), or it is now Exact
3203
0
    if (status&DEC_Underflow) {
3204
0
      Int ae=rhs->exponent+rhs->digits-1;    // adjusted exponent
3205
      // check if truly subnormal
3206
      #if DECEXTFLAG                         // DEC_Subnormal too
3207
0
        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3208
      #else
3209
        if (ae>=set->emin*2) status&=~DEC_Underflow;
3210
      #endif
3211
      // check if truly inexact
3212
0
      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3213
0
      }
3214
3215
0
    decNumberCopy(res, a);                   // a is now the result
3216
0
    } while(0);                              // end protected
3217
3218
0
  if (allocbuff!=NULL) free(allocbuff);      // drop any storage used
3219
0
  if (allocbufa!=NULL) free(allocbufa);      // ..
3220
0
  if (allocbufb!=NULL) free(allocbufb);      // ..
3221
  #if DECSUBSET
3222
  if (allocrhs !=NULL) free(allocrhs);       // ..
3223
  #endif
3224
0
  if (status!=0) decStatus(res, status, set);// then report status
3225
  #if DECCHECK
3226
  decCheckInexact(res, set);
3227
  #endif
3228
0
  return res;
3229
0
  } // decNumberSquareRoot
3230
3231
/* ------------------------------------------------------------------ */
3232
/* decNumberSubtract -- subtract two Numbers                          */
3233
/*                                                                    */
3234
/*   This computes C = A - B                                          */
3235
/*                                                                    */
3236
/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3237
/*   lhs is A                                                         */
3238
/*   rhs is B                                                         */
3239
/*   set is the context                                               */
3240
/*                                                                    */
3241
/* C must have space for set->digits digits.                          */
3242
/* ------------------------------------------------------------------ */
3243
decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3244
0
                              const decNumber *rhs, decContext *set) {
3245
0
  uInt status=0;                        // accumulator
3246
3247
0
  decAddOp(res, lhs, rhs, set, DECNEG, &status);
3248
0
  if (status!=0) decStatus(res, status, set);
3249
  #if DECCHECK
3250
  decCheckInexact(res, set);
3251
  #endif
3252
0
  return res;
3253
0
  } // decNumberSubtract
3254
3255
/* ------------------------------------------------------------------ */
3256
/* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3257
/* decNumberToIntegralValue -- round-to-integral-value                */
3258
/*                                                                    */
3259
/*   res is the result                                                */
3260
/*   rhs is input number                                              */
3261
/*   set is the context                                               */
3262
/*                                                                    */
3263
/* res must have space for any value of rhs.                          */
3264
/*                                                                    */
3265
/* This implements the IEEE special operators and therefore treats    */
3266
/* special values as valid.  For finite numbers it returns            */
3267
/* rescale(rhs, 0) if rhs->exponent is <0.                            */
3268
/* Otherwise the result is rhs (so no error is possible, except for   */
3269
/* sNaN).                                                             */
3270
/*                                                                    */
3271
/* The context is used for rounding mode and status after sNaN, but   */
3272
/* the digits setting is ignored.  The Exact version will signal      */
3273
/* Inexact if the result differs numerically from rhs; the other      */
3274
/* never signals Inexact.                                             */
3275
/* ------------------------------------------------------------------ */
3276
decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3277
0
                                     decContext *set) {
3278
0
  decNumber dn;
3279
0
  decContext workset;              // working context
3280
0
  uInt status=0;                   // accumulator
3281
3282
  #if DECCHECK
3283
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3284
  #endif
3285
3286
  // handle infinities and NaNs
3287
0
  if (SPECIALARG) {
3288
0
    if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity
3289
0
     else decNaNs(res, rhs, NULL, set, &status); // a NaN
3290
0
    }
3291
0
   else { // finite
3292
    // have a finite number; no error possible (res must be big enough)
3293
0
    if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3294
    // that was easy, but if negative exponent there is work to do...
3295
0
    workset=*set;                  // clone rounding, etc.
3296
0
    workset.digits=rhs->digits;    // no length rounding
3297
0
    workset.traps=0;               // no traps
3298
0
    decNumberZero(&dn);            // make a number with exponent 0
3299
0
    decNumberQuantize(res, rhs, &dn, &workset);
3300
0
    status|=workset.status;
3301
0
    }
3302
0
  if (status!=0) decStatus(res, status, set);
3303
0
  return res;
3304
0
  } // decNumberToIntegralExact
3305
3306
decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3307
0
                                     decContext *set) {
3308
0
  decContext workset=*set;         // working context
3309
0
  workset.traps=0;                 // no traps
3310
0
  decNumberToIntegralExact(res, rhs, &workset);
3311
  // this never affects set, except for sNaNs; NaN will have been set
3312
  // or propagated already, so no need to call decStatus
3313
0
  set->status|=workset.status&DEC_Invalid_operation;
3314
0
  return res;
3315
0
  } // decNumberToIntegralValue
3316
3317
/* ------------------------------------------------------------------ */
3318
/* decNumberXor -- XOR two Numbers, digitwise                         */
3319
/*                                                                    */
3320
/*   This computes C = A ^ B                                          */
3321
/*                                                                    */
3322
/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3323
/*   lhs is A                                                         */
3324
/*   rhs is B                                                         */
3325
/*   set is the context (used for result length and error report)     */
3326
/*                                                                    */
3327
/* C must have space for set->digits digits.                          */
3328
/*                                                                    */
3329
/* Logical function restrictions apply (see above); a NaN is          */
3330
/* returned with Invalid_operation if a restriction is violated.      */
3331
/* ------------------------------------------------------------------ */
3332
decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3333
0
                         const decNumber *rhs, decContext *set) {
3334
0
  const Unit *ua, *ub;                  // -> operands
3335
0
  const Unit *msua, *msub;              // -> operand msus
3336
0
  Unit  *uc, *msuc;                     // -> result and its msu
3337
0
  Int   msudigs;                        // digits in res msu
3338
  #if DECCHECK
3339
  if (decCheckOperands(res, lhs, rhs, set)) return res;
3340
  #endif
3341
3342
0
  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3343
0
   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3344
0
    decStatus(res, DEC_Invalid_operation, set);
3345
0
    return res;
3346
0
    }
3347
  // operands are valid
3348
0
  ua=lhs->lsu;                          // bottom-up
3349
0
  ub=rhs->lsu;                          // ..
3350
0
  uc=res->lsu;                          // ..
3351
0
  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
3352
0
  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
3353
0
  msuc=uc+D2U(set->digits)-1;           // -> msu of result
3354
0
  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
3355
0
  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
3356
0
    Unit a, b;                          // extract units
3357
0
    if (ua>msua) a=0;
3358
0
     else a=*ua;
3359
0
    if (ub>msub) b=0;
3360
0
     else b=*ub;
3361
0
    *uc=0;                              // can now write back
3362
0
    if (a|b) {                          // maybe 1 bits to examine
3363
0
      Int i, j;
3364
      // This loop could be unrolled and/or use BIN2BCD tables
3365
0
      for (i=0; i<DECDPUN; i++) {
3366
0
        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     // effect XOR
3367
0
        j=a%10;
3368
0
        a=a/10;
3369
0
        j|=b%10;
3370
0
        b=b/10;
3371
0
        if (j>1) {
3372
0
          decStatus(res, DEC_Invalid_operation, set);
3373
0
          return res;
3374
0
          }
3375
0
        if (uc==msuc && i==msudigs-1) break;      // just did final digit
3376
0
        } // each digit
3377
0
      } // non-zero
3378
0
    } // each unit
3379
  // [here uc-1 is the msu of the result]
3380
0
  res->digits=decGetDigits(res->lsu, uc-res->lsu);
3381
0
  res->exponent=0;                      // integer
3382
0
  res->bits=0;                          // sign=0
3383
0
  return res;  // [no status to set]
3384
0
  } // decNumberXor
3385
3386
3387
/* ================================================================== */
3388
/* Utility routines                                                   */
3389
/* ================================================================== */
3390
3391
/* ------------------------------------------------------------------ */
3392
/* decNumberClass -- return the decClass of a decNumber               */
3393
/*   dn -- the decNumber to test                                      */
3394
/*   set -- the context to use for Emin                               */
3395
/*   returns the decClass enum                                        */
3396
/* ------------------------------------------------------------------ */
3397
0
enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3398
0
  if (decNumberIsSpecial(dn)) {
3399
0
    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3400
0
    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3401
    // must be an infinity
3402
0
    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3403
0
    return DEC_CLASS_POS_INF;
3404
0
    }
3405
  // is finite
3406
0
  if (decNumberIsNormal(dn, set)) { // most common
3407
0
    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3408
0
    return DEC_CLASS_POS_NORMAL;
3409
0
    }
3410
  // is subnormal or zero
3411
0
  if (decNumberIsZero(dn)) {    // most common
3412
0
    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3413
0
    return DEC_CLASS_POS_ZERO;
3414
0
    }
3415
0
  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3416
0
  return DEC_CLASS_POS_SUBNORMAL;
3417
0
  } // decNumberClass
3418
3419
/* ------------------------------------------------------------------ */
3420
/* decNumberClassToString -- convert decClass to a string             */
3421
/*                                                                    */
3422
/*  eclass is a valid decClass                                        */
3423
/*  returns a constant string describing the class (max 13+1 chars)   */
3424
/* ------------------------------------------------------------------ */
3425
0
const char *decNumberClassToString(enum decClass eclass) {
3426
0
  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3427
0
  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3428
0
  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3429
0
  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3430
0
  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3431
0
  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3432
0
  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3433
0
  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3434
0
  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3435
0
  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3436
0
  return DEC_ClassString_UN;           // Unknown
3437
0
  } // decNumberClassToString
3438
3439
/* ------------------------------------------------------------------ */
3440
/* decNumberCopy -- copy a number                                     */
3441
/*                                                                    */
3442
/*   dest is the target decNumber                                     */
3443
/*   src  is the source decNumber                                     */
3444
/*   returns dest                                                     */
3445
/*                                                                    */
3446
/* (dest==src is allowed and is a no-op)                              */
3447
/* All fields are updated as required.  This is a utility operation,  */
3448
/* so special values are unchanged and no error is possible.          */
3449
/* ------------------------------------------------------------------ */
3450
0
decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3451
3452
  #if DECCHECK
3453
  if (src==NULL) return decNumberZero(dest);
3454
  #endif
3455
3456
0
  if (dest==src) return dest;                // no copy required
3457
3458
  // Use explicit assignments here as structure assignment could copy
3459
  // more than just the lsu (for small DECDPUN).  This would not affect
3460
  // the value of the results, but could disturb test harness spill
3461
  // checking.
3462
0
  dest->bits=src->bits;
3463
0
  dest->exponent=src->exponent;
3464
0
  dest->digits=src->digits;
3465
0
  dest->lsu[0]=src->lsu[0];
3466
0
  if (src->digits>DECDPUN) {                 // more Units to come
3467
0
    const Unit *smsup, *s;                   // work
3468
0
    Unit  *d;                                // ..
3469
    // memcpy for the remaining Units would be safe as they cannot
3470
    // overlap.  However, this explicit loop is faster in short cases.
3471
0
    d=dest->lsu+1;                           // -> first destination
3472
0
    smsup=src->lsu+D2U(src->digits);         // -> source msu+1
3473
0
    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3474
0
    }
3475
0
  return dest;
3476
0
  } // decNumberCopy
3477
3478
/* ------------------------------------------------------------------ */
3479
/* decNumberCopyAbs -- quiet absolute value operator                  */
3480
/*                                                                    */
3481
/*   This sets C = abs(A)                                             */
3482
/*                                                                    */
3483
/*   res is C, the result.  C may be A                                */
3484
/*   rhs is A                                                         */
3485
/*                                                                    */
3486
/* C must have space for set->digits digits.                          */
3487
/* No exception or error can occur; this is a quiet bitwise operation.*/
3488
/* See also decNumberAbs for a checking version of this.              */
3489
/* ------------------------------------------------------------------ */
3490
0
decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3491
  #if DECCHECK
3492
  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3493
  #endif
3494
0
  decNumberCopy(res, rhs);
3495
0
  res->bits&=~DECNEG;                   // turn off sign
3496
0
  return res;
3497
0
  } // decNumberCopyAbs
3498
3499
/* ------------------------------------------------------------------ */
3500
/* decNumberCopyNegate -- quiet negate value operator                 */
3501
/*                                                                    */
3502
/*   This sets C = negate(A)                                          */
3503
/*                                                                    */
3504
/*   res is C, the result.  C may be A                                */
3505
/*   rhs is A                                                         */
3506
/*                                                                    */
3507
/* C must have space for set->digits digits.                          */
3508
/* No exception or error can occur; this is a quiet bitwise operation.*/
3509
/* See also decNumberMinus for a checking version of this.            */
3510
/* ------------------------------------------------------------------ */
3511
0
decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3512
  #if DECCHECK
3513
  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3514
  #endif
3515
0
  decNumberCopy(res, rhs);
3516
0
  res->bits^=DECNEG;                    // invert the sign
3517
0
  return res;
3518
0
  } // decNumberCopyNegate
3519
3520
/* ------------------------------------------------------------------ */
3521
/* decNumberCopySign -- quiet copy and set sign operator              */
3522
/*                                                                    */
3523
/*   This sets C = A with the sign of B                               */
3524
/*                                                                    */
3525
/*   res is C, the result.  C may be A                                */
3526
/*   lhs is A                                                         */
3527
/*   rhs is B                                                         */
3528
/*                                                                    */
3529
/* C must have space for set->digits digits.                          */
3530
/* No exception or error can occur; this is a quiet bitwise operation.*/
3531
/* ------------------------------------------------------------------ */
3532
decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3533
0
                              const decNumber *rhs) {
3534
0
  uByte sign;                           // rhs sign
3535
  #if DECCHECK
3536
  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3537
  #endif
3538
0
  sign=rhs->bits & DECNEG;              // save sign bit
3539
0
  decNumberCopy(res, lhs);
3540
0
  res->bits&=~DECNEG;                   // clear the sign
3541
0
  res->bits|=sign;                      // set from rhs
3542
0
  return res;
3543
0
  } // decNumberCopySign
3544
3545
/* ------------------------------------------------------------------ */
3546
/* decNumberGetBCD -- get the coefficient in BCD8                     */
3547
/*   dn is the source decNumber                                       */
3548
/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3549
/*     most-significant at offset 0                                   */
3550
/*   returns bcd                                                      */
3551
/*                                                                    */
3552
/* bcd must have at least dn->digits bytes.  No error is possible; if */
3553
/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3554
/* ------------------------------------------------------------------ */
3555
0
uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3556
0
  uByte *ub=bcd+dn->digits-1;      // -> lsd
3557
0
  const Unit *up=dn->lsu;          // Unit pointer, -> lsu
3558
3559
  #if DECDPUN==1                   // trivial simple copy
3560
    for (; ub>=bcd; ub--, up++) *ub=*up;
3561
  #else                            // chopping needed
3562
0
    uInt u=*up;                    // work
3563
0
    uInt cut=DECDPUN;              // downcounter through unit
3564
0
    for (; ub>=bcd; ub--) {
3565
0
      *ub=(uByte)(u%10);           // [*6554 trick inhibits, here]
3566
0
      u=u/10;
3567
0
      cut--;
3568
0
      if (cut>0) continue;         // more in this unit
3569
0
      up++;
3570
0
      u=*up;
3571
0
      cut=DECDPUN;
3572
0
      }
3573
0
  #endif
3574
0
  return bcd;
3575
0
  } // decNumberGetBCD
3576
3577
/* ------------------------------------------------------------------ */
3578
/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3579
/*   dn is the target decNumber                                       */
3580
/*   bcd is the uInt array that will source n BCD bytes, most-        */
3581
/*     significant at offset 0                                        */
3582
/*   n is the number of digits in the source BCD array (bcd)          */
3583
/*   returns dn                                                       */
3584
/*                                                                    */
3585
/* dn must have space for at least n digits.  No error is possible;   */
3586
/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3587
/* and bcd[0] zero.                                                   */
3588
/* ------------------------------------------------------------------ */
3589
0
decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3590
0
  Unit *up=dn->lsu+D2U(dn->digits)-1;   // -> msu [target pointer]
3591
0
  const uByte *ub=bcd;                  // -> source msd
3592
3593
  #if DECDPUN==1                        // trivial simple copy
3594
    for (; ub<bcd+n; ub++, up--) *up=*ub;
3595
  #else                                 // some assembly needed
3596
    // calculate how many digits in msu, and hence first cut
3597
0
    Int cut=MSUDIGITS(n);               // [faster than remainder]
3598
0
    for (;up>=dn->lsu; up--) {          // each Unit from msu
3599
0
      *up=0;                            // will take <=DECDPUN digits
3600
0
      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3601
0
      cut=DECDPUN;                      // next Unit has all digits
3602
0
      }
3603
0
  #endif
3604
0
  dn->digits=n;                         // set digit count
3605
0
  return dn;
3606
0
  } // decNumberSetBCD
3607
3608
/* ------------------------------------------------------------------ */
3609
/* decNumberIsNormal -- test normality of a decNumber                 */
3610
/*   dn is the decNumber to test                                      */
3611
/*   set is the context to use for Emin                               */
3612
/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3613
/* ------------------------------------------------------------------ */
3614
0
Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3615
0
  Int ae;                               // adjusted exponent
3616
  #if DECCHECK
3617
  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3618
  #endif
3619
3620
0
  if (decNumberIsSpecial(dn)) return 0; // not finite
3621
0
  if (decNumberIsZero(dn)) return 0;    // not non-zero
3622
3623
0
  ae=dn->exponent+dn->digits-1;         // adjusted exponent
3624
0
  if (ae<set->emin) return 0;           // is subnormal
3625
0
  return 1;
3626
0
  } // decNumberIsNormal
3627
3628
/* ------------------------------------------------------------------ */
3629
/* decNumberIsSubnormal -- test subnormality of a decNumber           */
3630
/*   dn is the decNumber to test                                      */
3631
/*   set is the context to use for Emin                               */
3632
/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3633
/* ------------------------------------------------------------------ */
3634
0
Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3635
0
  Int ae;                               // adjusted exponent
3636
  #if DECCHECK
3637
  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3638
  #endif
3639
3640
0
  if (decNumberIsSpecial(dn)) return 0; // not finite
3641
0
  if (decNumberIsZero(dn)) return 0;    // not non-zero
3642
3643
0
  ae=dn->exponent+dn->digits-1;         // adjusted exponent
3644
0
  if (ae<set->emin) return 1;           // is subnormal
3645
0
  return 0;
3646
0
  } // decNumberIsSubnormal
3647
3648
/* ------------------------------------------------------------------ */
3649
/* decNumberTrim -- remove insignificant zeros                        */
3650
/*                                                                    */
3651
/*   dn is the number to trim                                         */
3652
/*   returns dn                                                       */
3653
/*                                                                    */
3654
/* All fields are updated as required.  This is a utility operation,  */
3655
/* so special values are unchanged and no error is possible.  The     */
3656
/* zeros are removed unconditionally.                                 */
3657
/* ------------------------------------------------------------------ */
3658
0
decNumber * decNumberTrim(decNumber *dn) {
3659
0
  Int  dropped;                    // work
3660
0
  decContext set;                  // ..
3661
  #if DECCHECK
3662
  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3663
  #endif
3664
0
  decContextDefault(&set, DEC_INIT_BASE);    // clamp=0
3665
0
  return decTrim(dn, &set, 0, 1, &dropped);
3666
0
  } // decNumberTrim
3667
3668
/* ------------------------------------------------------------------ */
3669
/* decNumberVersion -- return the name and version of this module     */
3670
/*                                                                    */
3671
/* No error is possible.                                              */
3672
/* ------------------------------------------------------------------ */
3673
0
const char * decNumberVersion(void) {
3674
0
  return DECVERSION;
3675
0
  } // decNumberVersion
3676
3677
/* ------------------------------------------------------------------ */
3678
/* decNumberZero -- set a number to 0                                 */
3679
/*                                                                    */
3680
/*   dn is the number to set, with space for one digit                */
3681
/*   returns dn                                                       */
3682
/*                                                                    */
3683
/* No error is possible.                                              */
3684
/* ------------------------------------------------------------------ */
3685
// Memset is not used as it is much slower in some environments.
3686
2.43k
decNumber * decNumberZero(decNumber *dn) {
3687
3688
  #if DECCHECK
3689
  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3690
  #endif
3691
3692
2.43k
  dn->bits=0;
3693
2.43k
  dn->exponent=0;
3694
2.43k
  dn->digits=1;
3695
2.43k
  dn->lsu[0]=0;
3696
2.43k
  return dn;
3697
2.43k
  } // decNumberZero
3698
3699
/* ================================================================== */
3700
/* Local routines                                                     */
3701
/* ================================================================== */
3702
3703
/* ------------------------------------------------------------------ */
3704
/* decToString -- lay out a number into a string                      */
3705
/*                                                                    */
3706
/*   dn     is the number to lay out                                  */
3707
/*   string is where to lay out the number                            */
3708
/*   eng    is 1 if Engineering, 0 if Scientific                      */
3709
/*                                                                    */
3710
/* string must be at least dn->digits+14 characters long              */
3711
/* No error is possible.                                              */
3712
/*                                                                    */
3713
/* Note that this routine can generate a -0 or 0.000.  These are      */
3714
/* never generated in subset to-number or arithmetic, but can occur   */
3715
/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3716
/* ------------------------------------------------------------------ */
3717
// If DECCHECK is enabled the string "?" is returned if a number is
3718
// invalid.
3719
0
static void decToString(const decNumber *dn, char *string, Flag eng) {
3720
0
  Int exp=dn->exponent;       // local copy
3721
0
  Int e;                      // E-part value
3722
0
  Int pre;                    // digits before the '.'
3723
0
  Int cut;                    // for counting digits in a Unit
3724
0
  char *c=string;             // work [output pointer]
3725
0
  const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]
3726
0
  uInt u, pow;                // work
3727
3728
  #if DECCHECK
3729
  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3730
    strcpy(string, "?");
3731
    return;}
3732
  #endif
3733
3734
0
  if (decNumberIsNegative(dn)) {   // Negatives get a minus
3735
0
    *c='-';
3736
0
    c++;
3737
0
    }
3738
0
  if (dn->bits&DECSPECIAL) {       // Is a special value
3739
0
    if (decNumberIsInfinite(dn)) {
3740
0
      strcpy(c,   "Inf");
3741
0
      strcpy(c+3, "inity");
3742
0
      return;}
3743
    // a NaN
3744
0
    if (dn->bits&DECSNAN) {        // signalling NaN
3745
0
      *c='s';
3746
0
      c++;
3747
0
      }
3748
0
    strcpy(c, "NaN");
3749
0
    c+=3;                          // step past
3750
    // if not a clean non-zero coefficient, that's all there is in a
3751
    // NaN string
3752
0
    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3753
    // [drop through to add integer]
3754
0
    }
3755
3756
  // calculate how many digits in msu, and hence first cut
3757
0
  cut=MSUDIGITS(dn->digits);       // [faster than remainder]
3758
0
  cut--;                           // power of ten for digit
3759
3760
0
  if (exp==0) {                    // simple integer [common fastpath]
3761
0
    for (;up>=dn->lsu; up--) {     // each Unit from msu
3762
0
      u=*up;                       // contains DECDPUN digits to lay out
3763
0
      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3764
0
      cut=DECDPUN-1;               // next Unit has all digits
3765
0
      }
3766
0
    *c='\0';                       // terminate the string
3767
0
    return;}
3768
3769
  /* non-0 exponent -- assume plain form */
3770
0
  pre=dn->digits+exp;              // digits before '.'
3771
0
  e=0;                             // no E
3772
0
  if ((exp>0) || (pre<-5)) {       // need exponential form
3773
0
    e=exp+dn->digits-1;            // calculate E value
3774
0
    pre=1;                         // assume one digit before '.'
3775
0
    if (eng && (e!=0)) {           // engineering: may need to adjust
3776
0
      Int adj;                     // adjustment
3777
      // The C remainder operator is undefined for negative numbers, so
3778
      // a positive remainder calculation must be used here
3779
0
      if (e<0) {
3780
0
        adj=(-e)%3;
3781
0
        if (adj!=0) adj=3-adj;
3782
0
        }
3783
0
       else { // e>0
3784
0
        adj=e%3;
3785
0
        }
3786
0
      e=e-adj;
3787
      // if dealing with zero still produce an exponent which is a
3788
      // multiple of three, as expected, but there will only be the
3789
      // one zero before the E, still.  Otherwise note the padding.
3790
0
      if (!ISZERO(dn)) pre+=adj;
3791
0
       else {  // is zero
3792
0
        if (adj!=0) {              // 0.00Esnn needed
3793
0
          e=e+3;
3794
0
          pre=-(2-adj);
3795
0
          }
3796
0
        } // zero
3797
0
      } // eng
3798
0
    } // need exponent
3799
3800
  /* lay out the digits of the coefficient, adding 0s and . as needed */
3801
0
  u=*up;
3802
0
  if (pre>0) {                     // xxx.xxx or xx00 (engineering) form
3803
0
    Int n=pre;
3804
0
    for (; pre>0; pre--, c++, cut--) {
3805
0
      if (cut<0) {                 // need new Unit
3806
0
        if (up==dn->lsu) break;    // out of input digits (pre>digits)
3807
0
        up--;
3808
0
        cut=DECDPUN-1;
3809
0
        u=*up;
3810
0
        }
3811
0
      TODIGIT(u, cut, c, pow);
3812
0
      }
3813
0
    if (n<dn->digits) {            // more to come, after '.'
3814
0
      *c='.'; c++;
3815
0
      for (;; c++, cut--) {
3816
0
        if (cut<0) {               // need new Unit
3817
0
          if (up==dn->lsu) break;  // out of input digits
3818
0
          up--;
3819
0
          cut=DECDPUN-1;
3820
0
          u=*up;
3821
0
          }
3822
0
        TODIGIT(u, cut, c, pow);
3823
0
        }
3824
0
      }
3825
0
     else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed
3826
0
    }
3827
0
   else {                          // 0.xxx or 0.000xxx form
3828
0
    *c='0'; c++;
3829
0
    *c='.'; c++;
3830
0
    for (; pre<0; pre++, c++) *c='0';   // add any 0's after '.'
3831
0
    for (; ; c++, cut--) {
3832
0
      if (cut<0) {                 // need new Unit
3833
0
        if (up==dn->lsu) break;    // out of input digits
3834
0
        up--;
3835
0
        cut=DECDPUN-1;
3836
0
        u=*up;
3837
0
        }
3838
0
      TODIGIT(u, cut, c, pow);
3839
0
      }
3840
0
    }
3841
3842
  /* Finally add the E-part, if needed.  It will never be 0, has a
3843
     base maximum and minimum of +999999999 through -999999999, but
3844
     could range down to -1999999998 for anormal numbers */
3845
0
  if (e!=0) {
3846
0
    Flag had=0;               // 1=had non-zero
3847
0
    *c='E'; c++;
3848
0
    *c='+'; c++;              // assume positive
3849
0
    u=e;                      // ..
3850
0
    if (e<0) {
3851
0
      *(c-1)='-';             // oops, need -
3852
0
      u=-e;                   // uInt, please
3853
0
      }
3854
    // lay out the exponent [_itoa or equivalent is not ANSI C]
3855
0
    for (cut=9; cut>=0; cut--) {
3856
0
      TODIGIT(u, cut, c, pow);
3857
0
      if (*c=='0' && !had) continue;    // skip leading zeros
3858
0
      had=1;                            // had non-0
3859
0
      c++;                              // step for next
3860
0
      } // cut
3861
0
    }
3862
0
  *c='\0';          // terminate the string (all paths)
3863
0
  return;
3864
0
  } // decToString
3865
3866
/* ------------------------------------------------------------------ */
3867
/* decAddOp -- add/subtract operation                                 */
3868
/*                                                                    */
3869
/*   This computes C = A + B                                          */
3870
/*                                                                    */
3871
/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3872
/*   lhs is A                                                         */
3873
/*   rhs is B                                                         */
3874
/*   set is the context                                               */
3875
/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3876
/*   status accumulates status for the caller                         */
3877
/*                                                                    */
3878
/* C must have space for set->digits digits.                          */
3879
/* Inexact in status must be 0 for correct Exact zero sign in result  */
3880
/* ------------------------------------------------------------------ */
3881
/* If possible, the coefficient is calculated directly into C.        */
3882
/* However, if:                                                       */
3883
/*   -- a digits+1 calculation is needed because the numbers are      */
3884
/*      unaligned and span more than set->digits digits               */
3885
/*   -- a carry to digits+1 digits looks possible                     */
3886
/*   -- C is the same as A or B, and the result would destructively   */
3887
/*      overlap the A or B coefficient                                */
3888
/* then the result must be calculated into a temporary buffer.  In    */
3889
/* this case a local (stack) buffer is used if possible, and only if  */
3890
/* too long for that does malloc become the final resort.             */
3891
/*                                                                    */
3892
/* Misalignment is handled as follows:                                */
3893
/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3894
/*   BPad: Apply the padding by a combination of shifting (whole      */
3895
/*         units) and multiplication (part units).                    */
3896
/*                                                                    */
3897
/* Addition, especially x=x+1, is speed-critical.                     */
3898
/* The static buffer is larger than might be expected to allow for    */
3899
/* calls from higher-level funtions (notable exp).                    */
3900
/* ------------------------------------------------------------------ */
3901
static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3902
                            const decNumber *rhs, decContext *set,
3903
1.87k
                            uByte negate, uInt *status) {
3904
  #if DECSUBSET
3905
  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
3906
  decNumber *allocrhs=NULL;        // .., rhs
3907
  #endif
3908
1.87k
  Int   rhsshift;                  // working shift (in Units)
3909
1.87k
  Int   maxdigits;                 // longest logical length
3910
1.87k
  Int   mult;                      // multiplier
3911
1.87k
  Int   residue;                   // rounding accumulator
3912
1.87k
  uByte bits;                      // result bits
3913
1.87k
  Flag  diffsign;                  // non-0 if arguments have different sign
3914
1.87k
  Unit  *acc;                      // accumulator for result
3915
1.87k
  Unit  accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many
3916
                                   // allocations when called from
3917
                                   // other operations, notable exp]
3918
1.87k
  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
3919
1.87k
  Int   reqdigits=set->digits;     // local copy; requested DIGITS
3920
1.87k
  Int   padding;                   // work
3921
3922
  #if DECCHECK
3923
  if (decCheckOperands(res, lhs, rhs, set)) return res;
3924
  #endif
3925
3926
1.87k
  do {                             // protect allocated storage
3927
    #if DECSUBSET
3928
    if (!set->extended) {
3929
      // reduce operands and set lostDigits status, as needed
3930
      if (lhs->digits>reqdigits) {
3931
        alloclhs=decRoundOperand(lhs, set, status);
3932
        if (alloclhs==NULL) break;
3933
        lhs=alloclhs;
3934
        }
3935
      if (rhs->digits>reqdigits) {
3936
        allocrhs=decRoundOperand(rhs, set, status);
3937
        if (allocrhs==NULL) break;
3938
        rhs=allocrhs;
3939
        }
3940
      }
3941
    #endif
3942
    // [following code does not require input rounding]
3943
3944
    // note whether signs differ [used all paths]
3945
1.87k
    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3946
3947
    // handle infinities and NaNs
3948
1.87k
    if (SPECIALARGS) {                  // a special bit set
3949
0
      if (SPECIALARGS & (DECSNAN | DECNAN))  // a NaN
3950
0
        decNaNs(res, lhs, rhs, set, status);
3951
0
       else { // one or two infinities
3952
0
        if (decNumberIsInfinite(lhs)) { // LHS is infinity
3953
          // two infinities with different signs is invalid
3954
0
          if (decNumberIsInfinite(rhs) && diffsign) {
3955
0
            *status|=DEC_Invalid_operation;
3956
0
            break;
3957
0
            }
3958
0
          bits=lhs->bits & DECNEG;      // get sign from LHS
3959
0
          }
3960
0
         else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity
3961
0
        bits|=DECINF;
3962
0
        decNumberZero(res);
3963
0
        res->bits=bits;                 // set +/- infinity
3964
0
        } // an infinity
3965
0
      break;
3966
0
      }
3967
3968
    // Quick exit for add 0s; return the non-0, modified as need be
3969
1.87k
    if (ISZERO(lhs)) {
3970
1.87k
      Int adjust;                       // work
3971
1.87k
      Int lexp=lhs->exponent;           // save in case LHS==RES
3972
1.87k
      bits=lhs->bits;                   // ..
3973
1.87k
      residue=0;                        // clear accumulator
3974
1.87k
      decCopyFit(res, rhs, set, &residue, status); // copy (as needed)
3975
1.87k
      res->bits^=negate;                // flip if rhs was negated
3976
      #if DECSUBSET
3977
      if (set->extended) {              // exponents on zeros count
3978
      #endif
3979
        // exponent will be the lower of the two
3980
1.87k
        adjust=lexp-res->exponent;      // adjustment needed [if -ve]
3981
1.87k
        if (ISZERO(res)) {              // both 0: special IEEE 754 rules
3982
748
          if (adjust<0) res->exponent=lexp;  // set exponent
3983
          // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0
3984
748
          if (diffsign) {
3985
748
            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3986
0
             else res->bits=DECNEG;     // preserve 0 sign
3987
748
            }
3988
748
          }
3989
1.12k
         else { // non-0 res
3990
1.12k
          if (adjust<0) {     // 0-padding needed
3991
0
            if ((res->digits-adjust)>set->digits) {
3992
0
              adjust=res->digits-set->digits;     // to fit exactly
3993
0
              *status|=DEC_Rounded;               // [but exact]
3994
0
              }
3995
0
            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3996
0
            res->exponent+=adjust;                // set the exponent.
3997
0
            }
3998
1.12k
          } // non-0 res
3999
      #if DECSUBSET
4000
        } // extended
4001
      #endif
4002
1.87k
      decFinish(res, set, &residue, status);      // clean and finalize
4003
1.87k
      break;}
4004
4005
0
    if (ISZERO(rhs)) {                  // [lhs is non-zero]
4006
0
      Int adjust;                       // work
4007
0
      Int rexp=rhs->exponent;           // save in case RHS==RES
4008
0
      bits=rhs->bits;                   // be clean
4009
0
      residue=0;                        // clear accumulator
4010
0
      decCopyFit(res, lhs, set, &residue, status); // copy (as needed)
4011
      #if DECSUBSET
4012
      if (set->extended) {              // exponents on zeros count
4013
      #endif
4014
        // exponent will be the lower of the two
4015
        // [0-0 case handled above]
4016
0
        adjust=rexp-res->exponent;      // adjustment needed [if -ve]
4017
0
        if (adjust<0) {     // 0-padding needed
4018
0
          if ((res->digits-adjust)>set->digits) {
4019
0
            adjust=res->digits-set->digits;     // to fit exactly
4020
0
            *status|=DEC_Rounded;               // [but exact]
4021
0
            }
4022
0
          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
4023
0
          res->exponent+=adjust;                // set the exponent.
4024
0
          }
4025
      #if DECSUBSET
4026
        } // extended
4027
      #endif
4028
0
      decFinish(res, set, &residue, status);      // clean and finalize
4029
0
      break;}
4030
4031
    // [NB: both fastpath and mainpath code below assume these cases
4032
    // (notably 0-0) have already been handled]
4033
4034
    // calculate the padding needed to align the operands
4035
0
    padding=rhs->exponent-lhs->exponent;
4036
4037
    // Fastpath cases where the numbers are aligned and normal, the RHS
4038
    // is all in one unit, no operand rounding is needed, and no carry,
4039
    // lengthening, or borrow is needed
4040
0
    if (padding==0
4041
0
        && rhs->digits<=DECDPUN
4042
0
        && rhs->exponent>=set->emin     // [some normals drop through]
4043
0
        && rhs->exponent<=set->emax-set->digits+1 // [could clamp]
4044
0
        && rhs->digits<=reqdigits
4045
0
        && lhs->digits<=reqdigits) {
4046
0
      Int partial=*lhs->lsu;
4047
0
      if (!diffsign) {                  // adding
4048
0
        partial+=*rhs->lsu;
4049
0
        if ((partial<=DECDPUNMAX)       // result fits in unit
4050
0
         && (lhs->digits>=DECDPUN ||    // .. and no digits-count change
4051
0
             partial<(Int)powers[lhs->digits])) { // ..
4052
0
          if (res!=lhs) decNumberCopy(res, lhs);  // not in place
4053
0
          *res->lsu=(Unit)partial;      // [copy could have overwritten RHS]
4054
0
          break;
4055
0
          }
4056
        // else drop out for careful add
4057
0
        }
4058
0
       else {                           // signs differ
4059
0
        partial-=*rhs->lsu;
4060
0
        if (partial>0) { // no borrow needed, and non-0 result
4061
0
          if (res!=lhs) decNumberCopy(res, lhs);  // not in place
4062
0
          *res->lsu=(Unit)partial;
4063
          // this could have reduced digits [but result>0]
4064
0
          res->digits=decGetDigits(res->lsu, D2U(res->digits));
4065
0
          break;
4066
0
          }
4067
        // else drop out for careful subtract
4068
0
        }
4069
0
      }
4070
4071
    // Now align (pad) the lhs or rhs so they can be added or
4072
    // subtracted, as necessary.  If one number is much larger than
4073
    // the other (that is, if in plain form there is a least one
4074
    // digit between the lowest digit of one and the highest of the
4075
    // other) padding with up to DIGITS-1 trailing zeros may be
4076
    // needed; then apply rounding (as exotic rounding modes may be
4077
    // affected by the residue).
4078
0
    rhsshift=0;               // rhs shift to left (padding) in Units
4079
0
    bits=lhs->bits;           // assume sign is that of LHS
4080
0
    mult=1;                   // likely multiplier
4081
4082
    // [if padding==0 the operands are aligned; no padding is needed]
4083
0
    if (padding!=0) {
4084
      // some padding needed; always pad the RHS, as any required
4085
      // padding can then be effected by a simple combination of
4086
      // shifts and a multiply
4087
0
      Flag swapped=0;
4088
0
      if (padding<0) {                  // LHS needs the padding
4089
0
        const decNumber *t;
4090
0
        padding=-padding;               // will be +ve
4091
0
        bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS
4092
0
        t=lhs; lhs=rhs; rhs=t;
4093
0
        swapped=1;
4094
0
        }
4095
4096
      // If, after pad, rhs would be longer than lhs by digits+1 or
4097
      // more then lhs cannot affect the answer, except as a residue,
4098
      // so only need to pad up to a length of DIGITS+1.
4099
0
      if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4100
        // The RHS is sufficient
4101
        // for residue use the relative sign indication...
4102
0
        Int shift=reqdigits-rhs->digits;     // left shift needed
4103
0
        residue=1;                           // residue for rounding
4104
0
        if (diffsign) residue=-residue;      // signs differ
4105
        // copy, shortening if necessary
4106
0
        decCopyFit(res, rhs, set, &residue, status);
4107
        // if it was already shorter, then need to pad with zeros
4108
0
        if (shift>0) {
4109
0
          res->digits=decShiftToMost(res->lsu, res->digits, shift);
4110
0
          res->exponent-=shift;              // adjust the exponent.
4111
0
          }
4112
        // flip the result sign if unswapped and rhs was negated
4113
0
        if (!swapped) res->bits^=negate;
4114
0
        decFinish(res, set, &residue, status);    // done
4115
0
        break;}
4116
4117
      // LHS digits may affect result
4118
0
      rhsshift=D2U(padding+1)-1;        // this much by Unit shift ..
4119
0
      mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication
4120
0
      } // padding needed
4121
4122
0
    if (diffsign) mult=-mult;           // signs differ
4123
4124
    // determine the longer operand
4125
0
    maxdigits=rhs->digits+padding;      // virtual length of RHS
4126
0
    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4127
4128
    // Decide on the result buffer to use; if possible place directly
4129
    // into result.
4130
0
    acc=res->lsu;                       // assume add direct to result
4131
    // If destructive overlap, or the number is too long, or a carry or
4132
    // borrow to DIGITS+1 might be possible, a buffer must be used.
4133
    // [Might be worth more sophisticated tests when maxdigits==reqdigits]
4134
0
    if ((maxdigits>=reqdigits)          // is, or could be, too large
4135
0
     || (res==rhs && rhsshift>0)) {     // destructive overlap
4136
      // buffer needed, choose it; units for maxdigits digits will be
4137
      // needed, +1 Unit for carry or borrow
4138
0
      Int need=D2U(maxdigits)+1;
4139
0
      acc=accbuff;                      // assume use local buffer
4140
0
      if (need*sizeof(Unit)>sizeof(accbuff)) {
4141
        // printf("malloc add %ld %ld\n", need, sizeof(accbuff));
4142
0
        allocacc=(Unit *)malloc(need*sizeof(Unit));
4143
0
        if (allocacc==NULL) {           // hopeless -- abandon
4144
0
          *status|=DEC_Insufficient_storage;
4145
0
          break;}
4146
0
        acc=allocacc;
4147
0
        }
4148
0
      }
4149
4150
0
    res->bits=(uByte)(bits&DECNEG);     // it's now safe to overwrite..
4151
0
    res->exponent=lhs->exponent;        // .. operands (even if aliased)
4152
4153
    #if DECTRACE
4154
      decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4155
      decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4156
      printf("  :h: %ld %ld\n", rhsshift, mult);
4157
    #endif
4158
4159
    // add [A+B*m] or subtract [A+B*(-m)]
4160
0
    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4161
0
                              rhs->lsu, D2U(rhs->digits),
4162
0
                              rhsshift, acc, mult)
4163
0
               *DECDPUN;           // [units -> digits]
4164
0
    if (res->digits<0) {           // borrowed...
4165
0
      res->digits=-res->digits;
4166
0
      res->bits^=DECNEG;           // flip the sign
4167
0
      }
4168
    #if DECTRACE
4169
      decDumpAr('+', acc, D2U(res->digits));
4170
    #endif
4171
4172
    // If a buffer was used the result must be copied back, possibly
4173
    // shortening.  (If no buffer was used then the result must have
4174
    // fit, so can't need rounding and residue must be 0.)
4175
0
    residue=0;                     // clear accumulator
4176
0
    if (acc!=res->lsu) {
4177
      #if DECSUBSET
4178
      if (set->extended) {         // round from first significant digit
4179
      #endif
4180
        // remove leading zeros that were added due to rounding up to
4181
        // integral Units -- before the test for rounding.
4182
0
        if (res->digits>reqdigits)
4183
0
          res->digits=decGetDigits(acc, D2U(res->digits));
4184
0
        decSetCoeff(res, set, acc, res->digits, &residue, status);
4185
      #if DECSUBSET
4186
        }
4187
       else { // subset arithmetic rounds from original significant digit
4188
        // May have an underestimate.  This only occurs when both
4189
        // numbers fit in DECDPUN digits and are padding with a
4190
        // negative multiple (-10, -100...) and the top digit(s) become
4191
        // 0.  (This only matters when using X3.274 rules where the
4192
        // leading zero could be included in the rounding.)
4193
        if (res->digits<maxdigits) {
4194
          *(acc+D2U(res->digits))=0; // ensure leading 0 is there
4195
          res->digits=maxdigits;
4196
          }
4197
         else {
4198
          // remove leading zeros that added due to rounding up to
4199
          // integral Units (but only those in excess of the original
4200
          // maxdigits length, unless extended) before test for rounding.
4201
          if (res->digits>reqdigits) {
4202
            res->digits=decGetDigits(acc, D2U(res->digits));
4203
            if (res->digits<maxdigits) res->digits=maxdigits;
4204
            }
4205
          }
4206
        decSetCoeff(res, set, acc, res->digits, &residue, status);
4207
        // Now apply rounding if needed before removing leading zeros.
4208
        // This is safe because subnormals are not a possibility
4209
        if (residue!=0) {
4210
          decApplyRound(res, set, residue, status);
4211
          residue=0;                 // did what needed to be done
4212
          }
4213
        } // subset
4214
      #endif
4215
0
      } // used buffer
4216
4217
    // strip leading zeros [these were left on in case of subset subtract]
4218
0
    res->digits=decGetDigits(res->lsu, D2U(res->digits));
4219
4220
    // apply checks and rounding
4221
0
    decFinish(res, set, &residue, status);
4222
4223
    // "When the sum of two operands with opposite signs is exactly
4224
    // zero, the sign of that sum shall be '+' in all rounding modes
4225
    // except round toward -Infinity, in which mode that sign shall be
4226
    // '-'."  [Subset zeros also never have '-', set by decFinish.]
4227
0
    if (ISZERO(res) && diffsign
4228
     #if DECSUBSET
4229
     && set->extended
4230
     #endif
4231
0
     && (*status&DEC_Inexact)==0) {
4232
0
      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   // sign -
4233
0
                                  else res->bits&=~DECNEG;  // sign +
4234
0
      }
4235
0
    } while(0);                              // end protected
4236
4237
1.87k
  if (allocacc!=NULL) free(allocacc);        // drop any storage used
4238
  #if DECSUBSET
4239
  if (allocrhs!=NULL) free(allocrhs);        // ..
4240
  if (alloclhs!=NULL) free(alloclhs);        // ..
4241
  #endif
4242
1.87k
  return res;
4243
1.87k
  } // decAddOp
4244
4245
/* ------------------------------------------------------------------ */
4246
/* decDivideOp -- division operation                                  */
4247
/*                                                                    */
4248
/*  This routine performs the calculations for all four division      */
4249
/*  operators (divide, divideInteger, remainder, remainderNear).      */
4250
/*                                                                    */
4251
/*  C=A op B                                                          */
4252
/*                                                                    */
4253
/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4254
/*   lhs is A                                                         */
4255
/*   rhs is B                                                         */
4256
/*   set is the context                                               */
4257
/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4258
/*   status is the usual accumulator                                  */
4259
/*                                                                    */
4260
/* C must have space for set->digits digits.                          */
4261
/*                                                                    */
4262
/* ------------------------------------------------------------------ */
4263
/*   The underlying algorithm of this routine is the same as in the   */
4264
/*   1981 S/370 implementation, that is, non-restoring long division  */
4265
/*   with bi-unit (rather than bi-digit) estimation for each unit     */
4266
/*   multiplier.  In this pseudocode overview, complications for the  */
4267
/*   Remainder operators and division residues for exact rounding are */
4268
/*   omitted for clarity.                                             */
4269
/*                                                                    */
4270
/*     Prepare operands and handle special values                     */
4271
/*     Test for x/0 and then 0/x                                      */
4272
/*     Exp =Exp1 - Exp2                                               */
4273
/*     Exp =Exp +len(var1) -len(var2)                                 */
4274
/*     Sign=Sign1 * Sign2                                             */
4275
/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4276
/*     Pad Var2 to same length as Var1                                */
4277
/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4278
/*     have=0                                                         */
4279
/*     Do until (have=digits+1 OR residue=0)                          */
4280
/*       if exp<0 then if integer divide/residue then leave           */
4281
/*       this_unit=0                                                  */
4282
/*       Do forever                                                   */
4283
/*          compare numbers                                           */
4284
/*          if <0 then leave inner_loop                               */
4285
/*          if =0 then (* quick exit without subtract *) do           */
4286
/*             this_unit=this_unit+1; output this_unit                */
4287
/*             leave outer_loop; end                                  */
4288
/*          Compare lengths of numbers (mantissae):                   */
4289
/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4290
/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4291
/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4292
/*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4293
/*          if mult=0 then mult=1                                     */
4294
/*          this_unit=this_unit+mult                                  */
4295
/*          subtract                                                  */
4296
/*          end inner_loop                                            */
4297
/*        if have\=0 | this_unit\=0 then do                           */
4298
/*          output this_unit                                          */
4299
/*          have=have+1; end                                          */
4300
/*        var2=var2/10                                                */
4301
/*        exp=exp-1                                                   */
4302
/*        end outer_loop                                              */
4303
/*     exp=exp+1   -- set the proper exponent                         */
4304
/*     if have=0 then generate answer=0                               */
4305
/*     Return (Result is defined by Var1)                             */
4306
/*                                                                    */
4307
/* ------------------------------------------------------------------ */
4308
/* Two working buffers are needed during the division; one (digits+   */
4309
/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4310
/* long subtractions.  These are acc and var1 respectively.           */
4311
/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4312
/* The static buffers may be larger than might be expected to allow   */
4313
/* for calls from higher-level funtions (notable exp).                */
4314
/* ------------------------------------------------------------------ */
4315
static decNumber * decDivideOp(decNumber *res,
4316
                               const decNumber *lhs, const decNumber *rhs,
4317
0
                               decContext *set, Flag op, uInt *status) {
4318
  #if DECSUBSET
4319
  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
4320
  decNumber *allocrhs=NULL;        // .., rhs
4321
  #endif
4322
0
  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer
4323
0
  Unit  *acc=accbuff;              // -> accumulator array for result
4324
0
  Unit  *allocacc=NULL;            // -> allocated buffer, iff allocated
4325
0
  Unit  *accnext;                  // -> where next digit will go
4326
0
  Int   acclength;                 // length of acc needed [Units]
4327
0
  Int   accunits;                  // count of units accumulated
4328
0
  Int   accdigits;                 // count of digits accumulated
4329
4330
0
  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  // buffer for var1
4331
0
  Unit  *var1=varbuff;             // -> var1 array for long subtraction
4332
0
  Unit  *varalloc=NULL;            // -> allocated buffer, iff used
4333
0
  Unit  *msu1;                     // -> msu of var1
4334
4335
0
  const Unit *var2;                // -> var2 array
4336
0
  const Unit *msu2;                // -> msu of var2
4337
0
  Int   msu2plus;                  // msu2 plus one [does not vary]
4338
0
  eInt  msu2pair;                  // msu2 pair plus one [does not vary]
4339
4340
0
  Int   var1units, var2units;      // actual lengths
4341
0
  Int   var2ulen;                  // logical length (units)
4342
0
  Int   var1initpad=0;             // var1 initial padding (digits)
4343
0
  Int   maxdigits;                 // longest LHS or required acc length
4344
0
  Int   mult;                      // multiplier for subtraction
4345
0
  Unit  thisunit;                  // current unit being accumulated
4346
0
  Int   residue;                   // for rounding
4347
0
  Int   reqdigits=set->digits;     // requested DIGITS
4348
0
  Int   exponent;                  // working exponent
4349
0
  Int   maxexponent=0;             // DIVIDE maximum exponent if unrounded
4350
0
  uByte bits;                      // working sign
4351
0
  Unit  *target;                   // work
4352
0
  const Unit *source;              // ..
4353
0
  uInt  const *pow;                // ..
4354
0
  Int   shift, cut;                // ..
4355
  #if DECSUBSET
4356
  Int   dropped;                   // work
4357
  #endif
4358
4359
  #if DECCHECK
4360
  if (decCheckOperands(res, lhs, rhs, set)) return res;
4361
  #endif
4362
4363
0
  do {                             // protect allocated storage
4364
    #if DECSUBSET
4365
    if (!set->extended) {
4366
      // reduce operands and set lostDigits status, as needed
4367
      if (lhs->digits>reqdigits) {
4368
        alloclhs=decRoundOperand(lhs, set, status);
4369
        if (alloclhs==NULL) break;
4370
        lhs=alloclhs;
4371
        }
4372
      if (rhs->digits>reqdigits) {
4373
        allocrhs=decRoundOperand(rhs, set, status);
4374
        if (allocrhs==NULL) break;
4375
        rhs=allocrhs;
4376
        }
4377
      }
4378
    #endif
4379
    // [following code does not require input rounding]
4380
4381
0
    bits=(lhs->bits^rhs->bits)&DECNEG;  // assumed sign for divisions
4382
4383
    // handle infinities and NaNs
4384
0
    if (SPECIALARGS) {                  // a special bit set
4385
0
      if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
4386
0
        decNaNs(res, lhs, rhs, set, status);
4387
0
        break;
4388
0
        }
4389
      // one or two infinities
4390
0
      if (decNumberIsInfinite(lhs)) {   // LHS (dividend) is infinite
4391
0
        if (decNumberIsInfinite(rhs) || // two infinities are invalid ..
4392
0
            (op&(REMAINDER | REMNEAR))) { // as is remainder of infinity
4393
0
          *status|=DEC_Invalid_operation;
4394
0
          break;
4395
0
          }
4396
        // [Note that infinity/0 raises no exceptions]
4397
0
        decNumberZero(res);
4398
0
        res->bits=bits|DECINF;          // set +/- infinity
4399
0
        break;
4400
0
        }
4401
0
       else {                           // RHS (divisor) is infinite
4402
0
        residue=0;
4403
0
        if (op&(REMAINDER|REMNEAR)) {
4404
          // result is [finished clone of] lhs
4405
0
          decCopyFit(res, lhs, set, &residue, status);
4406
0
          }
4407
0
         else {  // a division
4408
0
          decNumberZero(res);
4409
0
          res->bits=bits;               // set +/- zero
4410
          // for DIVIDEINT the exponent is always 0.  For DIVIDE, result
4411
          // is a 0 with infinitely negative exponent, clamped to minimum
4412
0
          if (op&DIVIDE) {
4413
0
            res->exponent=set->emin-set->digits+1;
4414
0
            *status|=DEC_Clamped;
4415
0
            }
4416
0
          }
4417
0
        decFinish(res, set, &residue, status);
4418
0
        break;
4419
0
        }
4420
0
      }
4421
4422
    // handle 0 rhs (x/0)
4423
0
    if (ISZERO(rhs)) {                  // x/0 is always exceptional
4424
0
      if (ISZERO(lhs)) {
4425
0
        decNumberZero(res);             // [after lhs test]
4426
0
        *status|=DEC_Division_undefined;// 0/0 will become NaN
4427
0
        }
4428
0
       else {
4429
0
        decNumberZero(res);
4430
0
        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4431
0
         else {
4432
0
          *status|=DEC_Division_by_zero; // x/0
4433
0
          res->bits=bits|DECINF;         // .. is +/- Infinity
4434
0
          }
4435
0
        }
4436
0
      break;}
4437
4438
    // handle 0 lhs (0/x)
4439
0
    if (ISZERO(lhs)) {                  // 0/x [x!=0]
4440
      #if DECSUBSET
4441
      if (!set->extended) decNumberZero(res);
4442
       else {
4443
      #endif
4444
0
        if (op&DIVIDE) {
4445
0
          residue=0;
4446
0
          exponent=lhs->exponent-rhs->exponent; // ideal exponent
4447
0
          decNumberCopy(res, lhs);      // [zeros always fit]
4448
0
          res->bits=bits;               // sign as computed
4449
0
          res->exponent=exponent;       // exponent, too
4450
0
          decFinalize(res, set, &residue, status);   // check exponent
4451
0
          }
4452
0
         else if (op&DIVIDEINT) {
4453
0
          decNumberZero(res);           // integer 0
4454
0
          res->bits=bits;               // sign as computed
4455
0
          }
4456
0
         else {                         // a remainder
4457
0
          exponent=rhs->exponent;       // [save in case overwrite]
4458
0
          decNumberCopy(res, lhs);      // [zeros always fit]
4459
0
          if (exponent<res->exponent) res->exponent=exponent; // use lower
4460
0
          }
4461
      #if DECSUBSET
4462
        }
4463
      #endif
4464
0
      break;}
4465
4466
    // Precalculate exponent.  This starts off adjusted (and hence fits
4467
    // in 31 bits) and becomes the usual unadjusted exponent as the
4468
    // division proceeds.  The order of evaluation is important, here,
4469
    // to avoid wrap.
4470
0
    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4471
4472
    // If the working exponent is -ve, then some quick exits are
4473
    // possible because the quotient is known to be <1
4474
    // [for REMNEAR, it needs to be < -1, as -0.5 could need work]
4475
0
    if (exponent<0 && !(op==DIVIDE)) {
4476
0
      if (op&DIVIDEINT) {
4477
0
        decNumberZero(res);                  // integer part is 0
4478
        #if DECSUBSET
4479
        if (set->extended)
4480
        #endif
4481
0
          res->bits=bits;                    // set +/- zero
4482
0
        break;}
4483
      // fastpath remainders so long as the lhs has the smaller
4484
      // (or equal) exponent
4485
0
      if (lhs->exponent<=rhs->exponent) {
4486
0
        if ((op&REMAINDER) || exponent<-1) {
4487
          // It is REMAINDER or safe REMNEAR; result is [finished
4488
          // clone of] lhs  (r = x - 0*y)
4489
0
          residue=0;
4490
0
          decCopyFit(res, lhs, set, &residue, status);
4491
0
          decFinish(res, set, &residue, status);
4492
0
          break;
4493
0
          }
4494
        // [unsafe REMNEAR drops through]
4495
0
        }
4496
0
      } // fastpaths
4497
4498
    /* Long (slow) division is needed; roll up the sleeves... */
4499
4500
    // The accumulator will hold the quotient of the division.
4501
    // If it needs to be too long for stack storage, then allocate.
4502
0
    acclength=D2U(reqdigits+DECDPUN);   // in Units
4503
0
    if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4504
      // printf("malloc dvacc %ld units\n", acclength);
4505
0
      allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4506
0
      if (allocacc==NULL) {             // hopeless -- abandon
4507
0
        *status|=DEC_Insufficient_storage;
4508
0
        break;}
4509
0
      acc=allocacc;                     // use the allocated space
4510
0
      }
4511
4512
    // var1 is the padded LHS ready for subtractions.
4513
    // If it needs to be too long for stack storage, then allocate.
4514
    // The maximum units needed for var1 (long subtraction) is:
4515
    // Enough for
4516
    //     (rhs->digits+reqdigits-1) -- to allow full slide to right
4517
    // or  (lhs->digits)             -- to allow for long lhs
4518
    // whichever is larger
4519
    //   +1                -- for rounding of slide to right
4520
    //   +1                -- for leading 0s
4521
    //   +1                -- for pre-adjust if a remainder or DIVIDEINT
4522
    // [Note: unused units do not participate in decUnitAddSub data]
4523
0
    maxdigits=rhs->digits+reqdigits-1;
4524
0
    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4525
0
    var1units=D2U(maxdigits)+2;
4526
    // allocate a guard unit above msu1 for REMAINDERNEAR
4527
0
    if (!(op&DIVIDE)) var1units++;
4528
0
    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4529
      // printf("malloc dvvar %ld units\n", var1units+1);
4530
0
      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4531
0
      if (varalloc==NULL) {             // hopeless -- abandon
4532
0
        *status|=DEC_Insufficient_storage;
4533
0
        break;}
4534
0
      var1=varalloc;                    // use the allocated space
4535
0
      }
4536
4537
    // Extend the lhs and rhs to full long subtraction length.  The lhs
4538
    // is truly extended into the var1 buffer, with 0 padding, so a
4539
    // subtract in place is always possible.  The rhs (var2) has
4540
    // virtual padding (implemented by decUnitAddSub).
4541
    // One guard unit was allocated above msu1 for rem=rem+rem in
4542
    // REMAINDERNEAR.
4543
0
    msu1=var1+var1units-1;              // msu of var1
4544
0
    source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array
4545
0
    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4546
0
    for (; target>=var1; target--) *target=0;
4547
4548
    // rhs (var2) is left-aligned with var1 at the start
4549
0
    var2ulen=var1units;                 // rhs logical length (units)
4550
0
    var2units=D2U(rhs->digits);         // rhs actual length (units)
4551
0
    var2=rhs->lsu;                      // -> rhs array
4552
0
    msu2=var2+var2units-1;              // -> msu of var2 [never changes]
4553
    // now set up the variables which will be used for estimating the
4554
    // multiplication factor.  If these variables are not exact, add
4555
    // 1 to make sure that the multiplier is never overestimated.
4556
0
    msu2plus=*msu2;                     // it's value ..
4557
0
    if (var2units>1) msu2plus++;        // .. +1 if any more
4558
0
    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..
4559
0
    if (var2units>1) {                  // .. [else treat 2nd as 0]
4560
0
      msu2pair+=*(msu2-1);              // ..
4561
0
      if (var2units>2) msu2pair++;      // .. +1 if any more
4562
0
      }
4563
4564
    // The calculation is working in units, which may have leading zeros,
4565
    // but the exponent was calculated on the assumption that they are
4566
    // both left-aligned.  Adjust the exponent to compensate: add the
4567
    // number of leading zeros in var1 msu and subtract those in var2 msu.
4568
    // [This is actually done by counting the digits and negating, as
4569
    // lead1=DECDPUN-digits1, and similarly for lead2.]
4570
0
    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4571
0
    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4572
4573
    // Now, if doing an integer divide or remainder, ensure that
4574
    // the result will be Unit-aligned.  To do this, shift the var1
4575
    // accumulator towards least if need be.  (It's much easier to
4576
    // do this now than to reassemble the residue afterwards, if
4577
    // doing a remainder.)  Also ensure the exponent is not negative.
4578
0
    if (!(op&DIVIDE)) {
4579
0
      Unit *u;                          // work
4580
      // save the initial 'false' padding of var1, in digits
4581
0
      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4582
      // Determine the shift to do.
4583
0
      if (exponent<0) cut=-exponent;
4584
0
       else cut=DECDPUN-exponent%DECDPUN;
4585
0
      decShiftToLeast(var1, var1units, cut);
4586
0
      exponent+=cut;                    // maintain numerical value
4587
0
      var1initpad-=cut;                 // .. and reduce padding
4588
      // clean any most-significant units which were just emptied
4589
0
      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4590
0
      } // align
4591
0
     else { // is DIVIDE
4592
0
      maxexponent=lhs->exponent-rhs->exponent;    // save
4593
      // optimization: if the first iteration will just produce 0,
4594
      // preadjust to skip it [valid for DIVIDE only]
4595
0
      if (*msu1<*msu2) {
4596
0
        var2ulen--;                     // shift down
4597
0
        exponent-=DECDPUN;              // update the exponent
4598
0
        }
4599
0
      }
4600
4601
    // ---- start the long-division loops ------------------------------
4602
0
    accunits=0;                         // no units accumulated yet
4603
0
    accdigits=0;                        // .. or digits
4604
0
    accnext=acc+acclength-1;            // -> msu of acc [NB: allows digits+1]
4605
0
    for (;;) {                          // outer forever loop
4606
0
      thisunit=0;                       // current unit assumed 0
4607
      // find the next unit
4608
0
      for (;;) {                        // inner forever loop
4609
        // strip leading zero units [from either pre-adjust or from
4610
        // subtract last time around].  Leave at least one unit.
4611
0
        for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4612
4613
0
        if (var1units<var2ulen) break;       // var1 too low for subtract
4614
0
        if (var1units==var2ulen) {           // unit-by-unit compare needed
4615
          // compare the two numbers, from msu
4616
0
          const Unit *pv1, *pv2;
4617
0
          Unit v2;                           // units to compare
4618
0
          pv2=msu2;                          // -> msu
4619
0
          for (pv1=msu1; ; pv1--, pv2--) {
4620
            // v1=*pv1 -- always OK
4621
0
            v2=0;                            // assume in padding
4622
0
            if (pv2>=var2) v2=*pv2;          // in range
4623
0
            if (*pv1!=v2) break;             // no longer the same
4624
0
            if (pv1==var1) break;            // done; leave pv1 as is
4625
0
            }
4626
          // here when all inspected or a difference seen
4627
0
          if (*pv1<v2) break;                // var1 too low to subtract
4628
0
          if (*pv1==v2) {                    // var1 == var2
4629
            // reach here if var1 and var2 are identical; subtraction
4630
            // would increase digit by one, and the residue will be 0 so
4631
            // the calculation is done; leave the loop with residue=0.
4632
0
            thisunit++;                      // as though subtracted
4633
0
            *var1=0;                         // set var1 to 0
4634
0
            var1units=1;                     // ..
4635
0
            break;  // from inner
4636
0
            } // var1 == var2
4637
          // *pv1>v2.  Prepare for real subtraction; the lengths are equal
4638
          // Estimate the multiplier (there's always a msu1-1)...
4639
          // Bring in two units of var2 to provide a good estimate.
4640
0
          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4641
0
          } // lengths the same
4642
0
         else { // var1units > var2ulen, so subtraction is safe
4643
          // The var2 msu is one unit towards the lsu of the var1 msu,
4644
          // so only one unit for var2 can be used.
4645
0
          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4646
0
          }
4647
0
        if (mult==0) mult=1;                 // must always be at least 1
4648
        // subtraction needed; var1 is > var2
4649
0
        thisunit=(Unit)(thisunit+mult);      // accumulate
4650
        // subtract var1-var2, into var1; only the overlap needs
4651
        // processing, as this is an in-place calculation
4652
0
        shift=var2ulen-var2units;
4653
        #if DECTRACE
4654
          decDumpAr('1', &var1[shift], var1units-shift);
4655
          decDumpAr('2', var2, var2units);
4656
          printf("m=%ld\n", -mult);
4657
        #endif
4658
0
        decUnitAddSub(&var1[shift], var1units-shift,
4659
0
                      var2, var2units, 0,
4660
0
                      &var1[shift], -mult);
4661
        #if DECTRACE
4662
          decDumpAr('#', &var1[shift], var1units-shift);
4663
        #endif
4664
        // var1 now probably has leading zeros; these are removed at the
4665
        // top of the inner loop.
4666
0
        } // inner loop
4667
4668
      // The next unit has been calculated in full; unless it's a
4669
      // leading zero, add to acc
4670
0
      if (accunits!=0 || thisunit!=0) {      // is first or non-zero
4671
0
        *accnext=thisunit;                   // store in accumulator
4672
        // account exactly for the new digits
4673
0
        if (accunits==0) {
4674
0
          accdigits++;                       // at least one
4675
0
          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4676
0
          }
4677
0
         else accdigits+=DECDPUN;
4678
0
        accunits++;                          // update count
4679
0
        accnext--;                           // ready for next
4680
0
        if (accdigits>reqdigits) break;      // have enough digits
4681
0
        }
4682
4683
      // if the residue is zero, the operation is done (unless divide
4684
      // or divideInteger and still not enough digits yet)
4685
0
      if (*var1==0 && var1units==1) {        // residue is 0
4686
0
        if (op&(REMAINDER|REMNEAR)) break;
4687
0
        if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4688
        // [drop through if divideInteger]
4689
0
        }
4690
      // also done enough if calculating remainder or integer
4691
      // divide and just did the last ('units') unit
4692
0
      if (exponent==0 && !(op&DIVIDE)) break;
4693
4694
      // to get here, var1 is less than var2, so divide var2 by the per-
4695
      // Unit power of ten and go for the next digit
4696
0
      var2ulen--;                            // shift down
4697
0
      exponent-=DECDPUN;                     // update the exponent
4698
0
      } // outer loop
4699
4700
    // ---- division is complete ---------------------------------------
4701
    // here: acc      has at least reqdigits+1 of good results (or fewer
4702
    //                if early stop), starting at accnext+1 (its lsu)
4703
    //       var1     has any residue at the stopping point
4704
    //       accunits is the number of digits collected in acc
4705
0
    if (accunits==0) {             // acc is 0
4706
0
      accunits=1;                  // show have a unit ..
4707
0
      accdigits=1;                 // ..
4708
0
      *accnext=0;                  // .. whose value is 0
4709
0
      }
4710
0
     else accnext++;               // back to last placed
4711
    // accnext now -> lowest unit of result
4712
4713
0
    residue=0;                     // assume no residue
4714
0
    if (op&DIVIDE) {
4715
      // record the presence of any residue, for rounding
4716
0
      if (*var1!=0 || var1units>1) residue=1;
4717
0
       else { // no residue
4718
        // Had an exact division; clean up spurious trailing 0s.
4719
        // There will be at most DECDPUN-1, from the final multiply,
4720
        // and then only if the result is non-0 (and even) and the
4721
        // exponent is 'loose'.
4722
0
        #if DECDPUN>1
4723
0
        Unit lsu=*accnext;
4724
0
        if (!(lsu&0x01) && (lsu!=0)) {
4725
          // count the trailing zeros
4726
0
          Int drop=0;
4727
0
          for (;; drop++) {    // [will terminate because lsu!=0]
4728
0
            if (exponent>=maxexponent) break;     // don't chop real 0s
4729
0
            #if DECDPUN<=4
4730
0
              if ((lsu-QUOT10(lsu, drop+1)
4731
0
                  *powers[drop+1])!=0) break;     // found non-0 digit
4732
            #else
4733
              if (lsu%powers[drop+1]!=0) break;   // found non-0 digit
4734
            #endif
4735
0
            exponent++;
4736
0
            }
4737
0
          if (drop>0) {
4738
0
            accunits=decShiftToLeast(accnext, accunits, drop);
4739
0
            accdigits=decGetDigits(accnext, accunits);
4740
0
            accunits=D2U(accdigits);
4741
            // [exponent was adjusted in the loop]
4742
0
            }
4743
0
          } // neither odd nor 0
4744
0
        #endif
4745
0
        } // exact divide
4746
0
      } // divide
4747
0
     else /* op!=DIVIDE */ {
4748
      // check for coefficient overflow
4749
0
      if (accdigits+exponent>reqdigits) {
4750
0
        *status|=DEC_Division_impossible;
4751
0
        break;
4752
0
        }
4753
0
      if (op & (REMAINDER|REMNEAR)) {
4754
        // [Here, the exponent will be 0, because var1 was adjusted
4755
        // appropriately.]
4756
0
        Int postshift;                       // work
4757
0
        Flag wasodd=0;                       // integer was odd
4758
0
        Unit *quotlsu;                       // for save
4759
0
        Int  quotdigits;                     // ..
4760
4761
0
        bits=lhs->bits;                      // remainder sign is always as lhs
4762
4763
        // Fastpath when residue is truly 0 is worthwhile [and
4764
        // simplifies the code below]
4765
0
        if (*var1==0 && var1units==1) {      // residue is 0
4766
0
          Int exp=lhs->exponent;             // save min(exponents)
4767
0
          if (rhs->exponent<exp) exp=rhs->exponent;
4768
0
          decNumberZero(res);                // 0 coefficient
4769
          #if DECSUBSET
4770
          if (set->extended)
4771
          #endif
4772
0
          res->exponent=exp;                 // .. with proper exponent
4773
0
          res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4774
0
          decFinish(res, set, &residue, status);   // might clamp
4775
0
          break;
4776
0
          }
4777
        // note if the quotient was odd
4778
0
        if (*accnext & 0x01) wasodd=1;       // acc is odd
4779
0
        quotlsu=accnext;                     // save in case need to reinspect
4780
0
        quotdigits=accdigits;                // ..
4781
4782
        // treat the residue, in var1, as the value to return, via acc
4783
        // calculate the unused zero digits.  This is the smaller of:
4784
        //   var1 initial padding (saved above)
4785
        //   var2 residual padding, which happens to be given by:
4786
0
        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4787
        // [the 'exponent' term accounts for the shifts during divide]
4788
0
        if (var1initpad<postshift) postshift=var1initpad;
4789
4790
        // shift var1 the requested amount, and adjust its digits
4791
0
        var1units=decShiftToLeast(var1, var1units, postshift);
4792
0
        accnext=var1;
4793
0
        accdigits=decGetDigits(var1, var1units);
4794
0
        accunits=D2U(accdigits);
4795
4796
0
        exponent=lhs->exponent;         // exponent is smaller of lhs & rhs
4797
0
        if (rhs->exponent<exponent) exponent=rhs->exponent;
4798
4799
        // Now correct the result if doing remainderNear; if it
4800
        // (looking just at coefficients) is > rhs/2, or == rhs/2 and
4801
        // the integer was odd then the result should be rem-rhs.
4802
0
        if (op&REMNEAR) {
4803
0
          Int compare, tarunits;        // work
4804
0
          Unit *up;                     // ..
4805
          // calculate remainder*2 into the var1 buffer (which has
4806
          // 'headroom' of an extra unit and hence enough space)
4807
          // [a dedicated 'double' loop would be faster, here]
4808
0
          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4809
0
                                 0, accnext, 1);
4810
          // decDumpAr('r', accnext, tarunits);
4811
4812
          // Here, accnext (var1) holds tarunits Units with twice the
4813
          // remainder's coefficient, which must now be compared to the
4814
          // RHS.  The remainder's exponent may be smaller than the RHS's.
4815
0
          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4816
0
                                 rhs->exponent-exponent);
4817
0
          if (compare==BADINT) {             // deep trouble
4818
0
            *status|=DEC_Insufficient_storage;
4819
0
            break;}
4820
4821
          // now restore the remainder by dividing by two; the lsu
4822
          // is known to be even.
4823
0
          for (up=accnext; up<accnext+tarunits; up++) {
4824
0
            Int half;              // half to add to lower unit
4825
0
            half=*up & 0x01;
4826
0
            *up/=2;                // [shift]
4827
0
            if (!half) continue;
4828
0
            *(up-1)+=(DECDPUNMAX+1)/2;
4829
0
            }
4830
          // [accunits still describes the original remainder length]
4831
4832
0
          if (compare>0 || (compare==0 && wasodd)) { // adjustment needed
4833
0
            Int exp, expunits, exprem;       // work
4834
            // This is effectively causing round-up of the quotient,
4835
            // so if it was the rare case where it was full and all
4836
            // nines, it would overflow and hence division-impossible
4837
            // should be raised
4838
0
            Flag allnines=0;                 // 1 if quotient all nines
4839
0
            if (quotdigits==reqdigits) {     // could be borderline
4840
0
              for (up=quotlsu; ; up++) {
4841
0
                if (quotdigits>DECDPUN) {
4842
0
                  if (*up!=DECDPUNMAX) break;// non-nines
4843
0
                  }
4844
0
                 else {                      // this is the last Unit
4845
0
                  if (*up==powers[quotdigits]-1) allnines=1;
4846
0
                  break;
4847
0
                  }
4848
0
                quotdigits-=DECDPUN;         // checked those digits
4849
0
                } // up
4850
0
              } // borderline check
4851
0
            if (allnines) {
4852
0
              *status|=DEC_Division_impossible;
4853
0
              break;}
4854
4855
            // rem-rhs is needed; the sign will invert.  Again, var1
4856
            // can safely be used for the working Units array.
4857
0
            exp=rhs->exponent-exponent;      // RHS padding needed
4858
            // Calculate units and remainder from exponent.
4859
0
            expunits=exp/DECDPUN;
4860
0
            exprem=exp%DECDPUN;
4861
            // subtract [A+B*(-m)]; the result will always be negative
4862
0
            accunits=-decUnitAddSub(accnext, accunits,
4863
0
                                    rhs->lsu, D2U(rhs->digits),
4864
0
                                    expunits, accnext, -(Int)powers[exprem]);
4865
0
            accdigits=decGetDigits(accnext, accunits); // count digits exactly
4866
0
            accunits=D2U(accdigits);    // and recalculate the units for copy
4867
            // [exponent is as for original remainder]
4868
0
            bits^=DECNEG;               // flip the sign
4869
0
            }
4870
0
          } // REMNEAR
4871
0
        } // REMAINDER or REMNEAR
4872
0
      } // not DIVIDE
4873
4874
    // Set exponent and bits
4875
0
    res->exponent=exponent;
4876
0
    res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4877
4878
    // Now the coefficient.
4879
0
    decSetCoeff(res, set, accnext, accdigits, &residue, status);
4880
4881
0
    decFinish(res, set, &residue, status);   // final cleanup
4882
4883
    #if DECSUBSET
4884
    // If a divide then strip trailing zeros if subset [after round]
4885
    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4886
    #endif
4887
0
    } while(0);                              // end protected
4888
4889
0
  if (varalloc!=NULL) free(varalloc);   // drop any storage used
4890
0
  if (allocacc!=NULL) free(allocacc);   // ..
4891
  #if DECSUBSET
4892
  if (allocrhs!=NULL) free(allocrhs);   // ..
4893
  if (alloclhs!=NULL) free(alloclhs);   // ..
4894
  #endif
4895
0
  return res;
4896
0
  } // decDivideOp
4897
4898
/* ------------------------------------------------------------------ */
4899
/* decMultiplyOp -- multiplication operation                          */
4900
/*                                                                    */
4901
/*  This routine performs the multiplication C=A x B.                 */
4902
/*                                                                    */
4903
/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4904
/*   lhs is A                                                         */
4905
/*   rhs is B                                                         */
4906
/*   set is the context                                               */
4907
/*   status is the usual accumulator                                  */
4908
/*                                                                    */
4909
/* C must have space for set->digits digits.                          */
4910
/*                                                                    */
4911
/* ------------------------------------------------------------------ */
4912
/* 'Classic' multiplication is used rather than Karatsuba, as the     */
4913
/* latter would give only a minor improvement for the short numbers   */
4914
/* expected to be handled most (and uses much more memory).           */
4915
/*                                                                    */
4916
/* There are two major paths here: the general-purpose ('old code')   */
4917
/* path which handles all DECDPUN values, and a fastpath version      */
4918
/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4919
/* than two calls to decUnitAddSub would be made.                     */
4920
/*                                                                    */
4921
/* The fastpath version lumps units together into 8-digit or 9-digit  */
4922
/* chunks, and also uses a lazy carry strategy to minimise expensive  */
4923
/* 64-bit divisions.  The chunks are then broken apart again into     */
4924
/* units for continuing processing.  Despite this overhead, the       */
4925
/* fastpath can speed up some 16-digit operations by 10x (and much    */
4926
/* more for higher-precision calculations).                           */
4927
/*                                                                    */
4928
/* A buffer always has to be used for the accumulator; in the         */
4929
/* fastpath, buffers are also always needed for the chunked copies of */
4930
/* of the operand coefficients.                                       */
4931
/* Static buffers are larger than needed just for multiply, to allow  */
4932
/* for calls from other operations (notably exp).                     */
4933
/* ------------------------------------------------------------------ */
4934
#define FASTMUL (DECUSE64 && DECDPUN<5)
4935
static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4936
                                 const decNumber *rhs, decContext *set,
4937
0
                                 uInt *status) {
4938
0
  Int    accunits;                 // Units of accumulator in use
4939
0
  Int    exponent;                 // work
4940
0
  Int    residue=0;                // rounding residue
4941
0
  uByte  bits;                     // result sign
4942
0
  Unit  *acc;                      // -> accumulator Unit array
4943
0
  Int    needbytes;                // size calculator
4944
0
  void  *allocacc=NULL;            // -> allocated accumulator, iff allocated
4945
0
  Unit  accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,
4946
                                   // *4 for calls from other operations)
4947
0
  const Unit *mer, *mermsup;       // work
4948
0
  Int   madlength;                 // Units in multiplicand
4949
0
  Int   shift;                     // Units to shift multiplicand by
4950
4951
0
  #if FASTMUL
4952
    // if DECDPUN is 1 or 3 work in base 10**9, otherwise
4953
    // (DECDPUN is 2 or 4) then work in base 10**8
4954
0
    #if DECDPUN & 1                // odd
4955
0
      #define FASTBASE 1000000000  // base
4956
0
      #define FASTDIGS          9  // digits in base
4957
0
      #define FASTLAZY         18  // carry resolution point [1->18]
4958
    #else
4959
      #define FASTBASE  100000000
4960
      #define FASTDIGS          8
4961
      #define FASTLAZY       1844  // carry resolution point [1->1844]
4962
    #endif
4963
    // three buffers are used, two for chunked copies of the operands
4964
    // (base 10**8 or base 10**9) and one base 2**64 accumulator with
4965
    // lazy carry evaluation
4966
0
    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4967
0
    uInt  *zlhi=zlhibuff;                 // -> lhs array
4968
0
    uInt  *alloclhi=NULL;                 // -> allocated buffer, iff allocated
4969
0
    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4970
0
    uInt  *zrhi=zrhibuff;                 // -> rhs array
4971
0
    uInt  *allocrhi=NULL;                 // -> allocated buffer, iff allocated
4972
0
    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)
4973
    // [allocacc is shared for both paths, as only one will run]
4974
0
    uLong *zacc=zaccbuff;          // -> accumulator array for exact result
4975
    #if DECDPUN==1
4976
    Int    zoff;                   // accumulator offset
4977
    #endif
4978
0
    uInt  *lip, *rip;              // item pointers
4979
0
    uInt  *lmsi, *rmsi;            // most significant items
4980
0
    Int    ilhs, irhs, iacc;       // item counts in the arrays
4981
0
    Int    lazy;                   // lazy carry counter
4982
0
    uLong  lcarry;                 // uLong carry
4983
0
    uInt   carry;                  // carry (NB not uLong)
4984
0
    Int    count;                  // work
4985
0
    const  Unit *cup;              // ..
4986
0
    Unit  *up;                     // ..
4987
0
    uLong *lp;                     // ..
4988
0
    Int    p;                      // ..
4989
0
  #endif
4990
4991
  #if DECSUBSET
4992
    decNumber *alloclhs=NULL;      // -> allocated buffer, iff allocated
4993
    decNumber *allocrhs=NULL;      // -> allocated buffer, iff allocated
4994
  #endif
4995
4996
  #if DECCHECK
4997
  if (decCheckOperands(res, lhs, rhs, set)) return res;
4998
  #endif
4999
5000
  // precalculate result sign
5001
0
  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
5002
5003
  // handle infinities and NaNs
5004
0
  if (SPECIALARGS) {               // a special bit set
5005
0
    if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
5006
0
      decNaNs(res, lhs, rhs, set, status);
5007
0
      return res;}
5008
    // one or two infinities; Infinity * 0 is invalid
5009
0
    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
5010
0
      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
5011
0
      *status|=DEC_Invalid_operation;
5012
0
      return res;}
5013
0
    decNumberZero(res);
5014
0
    res->bits=bits|DECINF;         // infinity
5015
0
    return res;}
5016
5017
  // For best speed, as in DMSRCN [the original Rexx numerics
5018
  // module], use the shorter number as the multiplier (rhs) and
5019
  // the longer as the multiplicand (lhs) to minimise the number of
5020
  // adds (partial products)
5021
0
  if (lhs->digits<rhs->digits) {   // swap...
5022
0
    const decNumber *hold=lhs;
5023
0
    lhs=rhs;
5024
0
    rhs=hold;
5025
0
    }
5026
5027
0
  do {                             // protect allocated storage
5028
    #if DECSUBSET
5029
    if (!set->extended) {
5030
      // reduce operands and set lostDigits status, as needed
5031
      if (lhs->digits>set->digits) {
5032
        alloclhs=decRoundOperand(lhs, set, status);
5033
        if (alloclhs==NULL) break;
5034
        lhs=alloclhs;
5035
        }
5036
      if (rhs->digits>set->digits) {
5037
        allocrhs=decRoundOperand(rhs, set, status);
5038
        if (allocrhs==NULL) break;
5039
        rhs=allocrhs;
5040
        }
5041
      }
5042
    #endif
5043
    // [following code does not require input rounding]
5044
5045
    #if FASTMUL                    // fastpath can be used
5046
    // use the fast path if there are enough digits in the shorter
5047
    // operand to make the setup and takedown worthwhile
5048
0
    #define NEEDTWO (DECDPUN*2)    // within two decUnitAddSub calls
5049
0
    if (rhs->digits>NEEDTWO) {     // use fastpath...
5050
      // calculate the number of elements in each array
5051
0
      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]
5052
0
      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..
5053
0
      iacc=ilhs+irhs;
5054
5055
      // allocate buffers if required, as usual
5056
0
      needbytes=ilhs*sizeof(uInt);
5057
0
      if (needbytes>(Int)sizeof(zlhibuff)) {
5058
0
        alloclhi=(uInt *)malloc(needbytes);
5059
0
        zlhi=alloclhi;}
5060
0
      needbytes=irhs*sizeof(uInt);
5061
0
      if (needbytes>(Int)sizeof(zrhibuff)) {
5062
0
        allocrhi=(uInt *)malloc(needbytes);
5063
0
        zrhi=allocrhi;}
5064
5065
      // Allocating the accumulator space needs a special case when
5066
      // DECDPUN=1 because when converting the accumulator to Units
5067
      // after the multiplication each 8-byte item becomes 9 1-byte
5068
      // units.  Therefore iacc extra bytes are needed at the front
5069
      // (rounded up to a multiple of 8 bytes), and the uLong
5070
      // accumulator starts offset the appropriate number of units
5071
      // to the right to avoid overwrite during the unchunking.
5072
0
      needbytes=iacc*sizeof(uLong);
5073
      #if DECDPUN==1
5074
      zoff=(iacc+7)/8;        // items to offset by
5075
      needbytes+=zoff*8;
5076
      #endif
5077
0
      if (needbytes>(Int)sizeof(zaccbuff)) {
5078
0
        allocacc=(uLong *)malloc(needbytes);
5079
0
        zacc=(uLong *)allocacc;}
5080
0
      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
5081
0
        *status|=DEC_Insufficient_storage;
5082
0
        break;}
5083
5084
0
      acc=(Unit *)zacc;       // -> target Unit array
5085
      #if DECDPUN==1
5086
      zacc+=zoff;             // start uLong accumulator to right
5087
      #endif
5088
5089
      // assemble the chunked copies of the left and right sides
5090
0
      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5091
0
        for (p=0, *lip=0; p<FASTDIGS && count>0;
5092
0
             p+=DECDPUN, cup++, count-=DECDPUN)
5093
0
          *lip+=*cup*powers[p];
5094
0
      lmsi=lip-1;     // save -> msi
5095
0
      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5096
0
        for (p=0, *rip=0; p<FASTDIGS && count>0;
5097
0
             p+=DECDPUN, cup++, count-=DECDPUN)
5098
0
          *rip+=*cup*powers[p];
5099
0
      rmsi=rip-1;     // save -> msi
5100
5101
      // zero the accumulator
5102
0
      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5103
5104
      /* Start the multiplication */
5105
      // Resolving carries can dominate the cost of accumulating the
5106
      // partial products, so this is only done when necessary.
5107
      // Each uLong item in the accumulator can hold values up to
5108
      // 2**64-1, and each partial product can be as large as
5109
      // (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to
5110
      // itself 18.4 times in a uLong without overflowing, so during
5111
      // the main calculation resolution is carried out every 18th
5112
      // add -- every 162 digits.  Similarly, when FASTDIGS=8, the
5113
      // partial products can be added to themselves 1844.6 times in
5114
      // a uLong without overflowing, so intermediate carry
5115
      // resolution occurs only every 14752 digits.  Hence for common
5116
      // short numbers usually only the one final carry resolution
5117
      // occurs.
5118
      // (The count is set via FASTLAZY to simplify experiments to
5119
      // measure the value of this approach: a 35% improvement on a
5120
      // [34x34] multiply.)
5121
0
      lazy=FASTLAZY;                         // carry delay count
5122
0
      for (rip=zrhi; rip<=rmsi; rip++) {     // over each item in rhs
5123
0
        lp=zacc+(rip-zrhi);                  // where to add the lhs
5124
0
        for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs
5125
0
          *lp+=(uLong)(*lip)*(*rip);         // [this should in-line]
5126
0
          } // lip loop
5127
0
        lazy--;
5128
0
        if (lazy>0 && rip!=rmsi) continue;
5129
0
        lazy=FASTLAZY;                       // reset delay count
5130
        // spin up the accumulator resolving overflows
5131
0
        for (lp=zacc; lp<zacc+iacc; lp++) {
5132
0
          if (*lp<FASTBASE) continue;        // it fits
5133
0
          lcarry=*lp/FASTBASE;               // top part [slow divide]
5134
          // lcarry can exceed 2**32-1, so check again; this check
5135
          // and occasional extra divide (slow) is well worth it, as
5136
          // it allows FASTLAZY to be increased to 18 rather than 4
5137
          // in the FASTDIGS=9 case
5138
0
          if (lcarry<FASTBASE) carry=(uInt)lcarry;  // [usual]
5139
0
           else { // two-place carry [fairly rare]
5140
0
            uInt carry2=(uInt)(lcarry/FASTBASE);    // top top part
5141
0
            *(lp+2)+=carry2;                        // add to item+2
5142
0
            *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]
5143
0
            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]
5144
0
            }
5145
0
          *(lp+1)+=carry;                    // add to item above [inline]
5146
0
          *lp-=((uLong)FASTBASE*carry);      // [inline]
5147
0
          } // carry resolution
5148
0
        } // rip loop
5149
5150
      // The multiplication is complete; time to convert back into
5151
      // units.  This can be done in-place in the accumulator and in
5152
      // 32-bit operations, because carries were resolved after the
5153
      // final add.  This needs N-1 divides and multiplies for
5154
      // each item in the accumulator (which will become up to N
5155
      // units, where 2<=N<=9).
5156
0
      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5157
0
        uInt item=(uInt)*lp;                 // decapitate to uInt
5158
0
        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5159
0
          uInt part=item/(DECDPUNMAX+1);
5160
0
          *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5161
0
          item=part;
5162
0
          } // p
5163
0
        *up=(Unit)item; up++;                // [final needs no division]
5164
0
        } // lp
5165
0
      accunits=up-acc;                       // count of units
5166
0
      }
5167
0
     else { // here to use units directly, without chunking ['old code']
5168
0
    #endif
5169
5170
      // if accumulator will be too long for local storage, then allocate
5171
0
      acc=accbuff;                 // -> assume buffer for accumulator
5172
0
      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5173
0
      if (needbytes>(Int)sizeof(accbuff)) {
5174
0
        allocacc=(Unit *)malloc(needbytes);
5175
0
        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5176
0
        acc=(Unit *)allocacc;                // use the allocated space
5177
0
        }
5178
5179
      /* Now the main long multiplication loop */
5180
      // Unlike the equivalent in the IBM Java implementation, there
5181
      // is no advantage in calculating from msu to lsu.  So, do it
5182
      // by the book, as it were.
5183
      // Each iteration calculates ACC=ACC+MULTAND*MULT
5184
0
      accunits=1;                  // accumulator starts at '0'
5185
0
      *acc=0;                      // .. (lsu=0)
5186
0
      shift=0;                     // no multiplicand shift at first
5187
0
      madlength=D2U(lhs->digits);  // this won't change
5188
0
      mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier
5189
5190
0
      for (mer=rhs->lsu; mer<mermsup; mer++) {
5191
        // Here, *mer is the next Unit in the multiplier to use
5192
        // If non-zero [optimization] add it...
5193
0
        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5194
0
                                            lhs->lsu, madlength, 0,
5195
0
                                            &acc[shift], *mer)
5196
0
                                            + shift;
5197
0
         else { // extend acc with a 0; it will be used shortly
5198
0
          *(acc+accunits)=0;       // [this avoids length of <=0 later]
5199
0
          accunits++;
5200
0
          }
5201
        // multiply multiplicand by 10**DECDPUN for next Unit to left
5202
0
        shift++;                   // add this for 'logical length'
5203
0
        } // n
5204
0
    #if FASTMUL
5205
0
      } // unchunked units
5206
0
    #endif
5207
    // common end-path
5208
    #if DECTRACE
5209
      decDumpAr('*', acc, accunits);         // Show exact result
5210
    #endif
5211
5212
    // acc now contains the exact result of the multiplication,
5213
    // possibly with a leading zero unit; build the decNumber from
5214
    // it, noting if any residue
5215
0
    res->bits=bits;                          // set sign
5216
0
    res->digits=decGetDigits(acc, accunits); // count digits exactly
5217
5218
    // There can be a 31-bit wrap in calculating the exponent.
5219
    // This can only happen if both input exponents are negative and
5220
    // both their magnitudes are large.  If there was a wrap, set a
5221
    // safe very negative exponent, from which decFinalize() will
5222
    // raise a hard underflow shortly.
5223
0
    exponent=lhs->exponent+rhs->exponent;    // calculate exponent
5224
0
    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5225
0
      exponent=-2*DECNUMMAXE;                // force underflow
5226
0
    res->exponent=exponent;                  // OK to overwrite now
5227
5228
5229
    // Set the coefficient.  If any rounding, residue records
5230
0
    decSetCoeff(res, set, acc, res->digits, &residue, status);
5231
0
    decFinish(res, set, &residue, status);   // final cleanup
5232
0
    } while(0);                         // end protected
5233
5234
0
  if (allocacc!=NULL) free(allocacc);   // drop any storage used
5235
  #if DECSUBSET
5236
  if (allocrhs!=NULL) free(allocrhs);   // ..
5237
  if (alloclhs!=NULL) free(alloclhs);   // ..
5238
  #endif
5239
0
  #if FASTMUL
5240
0
  if (allocrhi!=NULL) free(allocrhi);   // ..
5241
0
  if (alloclhi!=NULL) free(alloclhi);   // ..
5242
0
  #endif
5243
0
  return res;
5244
0
  } // decMultiplyOp
5245
5246
/* ------------------------------------------------------------------ */
5247
/* decExpOp -- effect exponentiation                                  */
5248
/*                                                                    */
5249
/*   This computes C = exp(A)                                         */
5250
/*                                                                    */
5251
/*   res is C, the result.  C may be A                                */
5252
/*   rhs is A                                                         */
5253
/*   set is the context; note that rounding mode has no effect        */
5254
/*                                                                    */
5255
/* C must have space for set->digits digits. status is updated but    */
5256
/* not set.                                                           */
5257
/*                                                                    */
5258
/* Restrictions:                                                      */
5259
/*                                                                    */
5260
/*   digits, emax, and -emin in the context must be less than         */
5261
/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5262
/*   bounds or a zero.  This is an internal routine, so these         */
5263
/*   restrictions are contractual and not enforced.                   */
5264
/*                                                                    */
5265
/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5266
/* almost always be correctly rounded, but may be up to 1 ulp in      */
5267
/* error in rare cases.                                               */
5268
/*                                                                    */
5269
/* Finite results will always be full precision and Inexact, except   */
5270
/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5271
/* ------------------------------------------------------------------ */
5272
/* This approach used here is similar to the algorithm described in   */
5273
/*                                                                    */
5274
/*   Variable Precision Exponential Function, T. E. Hull and          */
5275
/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5276
/*   pp79-91, ACM, June 1986.                                         */
5277
/*                                                                    */
5278
/* with the main difference being that the iterations in the series   */
5279
/* evaluation are terminated dynamically (which does not require the  */
5280
/* extra variable-precision variables which are expensive in this     */
5281
/* context).                                                          */
5282
/*                                                                    */
5283
/* The error analysis in Hull & Abrham's paper applies except for the */
5284
/* round-off error accumulation during the series evaluation.  This   */
5285
/* code does not precalculate the number of iterations and so cannot  */
5286
/* use Horner's scheme.  Instead, the accumulation is done at double- */
5287
/* precision, which ensures that the additions of the terms are exact */
5288
/* and do not accumulate round-off (and any round-off errors in the   */
5289
/* terms themselves move 'to the right' faster than they can          */
5290
/* accumulate).  This code also extends the calculation by allowing,  */
5291
/* in the spirit of other decNumber operators, the input to be more   */
5292
/* precise than the result (the precision used is based on the more   */
5293
/* precise of the input or requested result).                         */
5294
/*                                                                    */
5295
/* Implementation notes:                                              */
5296
/*                                                                    */
5297
/* 1. This is separated out as decExpOp so it can be called from      */
5298
/*    other Mathematical functions (notably Ln) with a wider range    */
5299
/*    than normal.  In particular, it can handle the slightly wider   */
5300
/*    (double) range needed by Ln (which has to be able to calculate  */
5301
/*    exp(-x) where x can be the tiniest number (Ntiny).              */
5302
/*                                                                    */
5303
/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5304
/*    iterations by appoximately a third with additional (although    */
5305
/*    diminishing) returns as the range is reduced to even smaller    */
5306
/*    fractions.  However, h (the power of 10 used to correct the     */
5307
/*    result at the end, see below) must be kept <=8 as otherwise     */
5308
/*    the final result cannot be computed.  Hence the leverage is a   */
5309
/*    sliding value (8-h), where potentially the range is reduced     */
5310
/*    more for smaller values.                                        */
5311
/*                                                                    */
5312
/*    The leverage that can be applied in this way is severely        */
5313
/*    limited by the cost of the raise-to-the power at the end,       */
5314
/*    which dominates when the number of iterations is small (less    */
5315
/*    than ten) or when rhs is short.  As an example, the adjustment  */
5316
/*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5317
/*                                                                    */
5318
/* 3. The restrictions (especially precision) could be raised with    */
5319
/*    care, but the full decNumber range seems very hard within the   */
5320
/*    32-bit limits.                                                  */
5321
/*                                                                    */
5322
/* 4. The working precisions for the static buffers are twice the     */
5323
/*    obvious size to allow for calls from decNumberPower.            */
5324
/* ------------------------------------------------------------------ */
5325
decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5326
0
                         decContext *set, uInt *status) {
5327
0
  uInt ignore=0;                   // working status
5328
0
  Int h;                           // adjusted exponent for 0.xxxx
5329
0
  Int p;                           // working precision
5330
0
  Int residue;                     // rounding residue
5331
0
  uInt needbytes;                  // for space calculations
5332
0
  const decNumber *x=rhs;          // (may point to safe copy later)
5333
0
  decContext aset, tset, dset;     // working contexts
5334
0
  Int comp;                        // work
5335
5336
  // the argument is often copied to normalize it, so (unusually) it
5337
  // is treated like other buffers, using DECBUFFER, +1 in case
5338
  // DECBUFFER is 0
5339
0
  decNumber bufr[D2N(DECBUFFER*2+1)];
5340
0
  decNumber *allocrhs=NULL;        // non-NULL if rhs buffer allocated
5341
5342
  // the working precision will be no more than set->digits+8+1
5343
  // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER
5344
  // is 0 (and twice that for the accumulator)
5345
5346
  // buffer for t, term (working precision plus)
5347
0
  decNumber buft[D2N(DECBUFFER*2+9+1)];
5348
0
  decNumber *allocbuft=NULL;       // -> allocated buft, iff allocated
5349
0
  decNumber *t=buft;               // term
5350
  // buffer for a, accumulator (working precision * 2), at least 9
5351
0
  decNumber bufa[D2N(DECBUFFER*4+18+1)];
5352
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5353
0
  decNumber *a=bufa;               // accumulator
5354
  // decNumber for the divisor term; this needs at most 9 digits
5355
  // and so can be fixed size [16 so can use standard context]
5356
0
  decNumber bufd[D2N(16)];
5357
0
  decNumber *d=bufd;               // divisor
5358
0
  decNumber numone;                // constant 1
5359
5360
  #if DECCHECK
5361
  Int iterations=0;                // for later sanity check
5362
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5363
  #endif
5364
5365
0
  do {                                  // protect allocated storage
5366
0
    if (SPECIALARG) {                   // handle infinities and NaNs
5367
0
      if (decNumberIsInfinite(rhs)) {   // an infinity
5368
0
        if (decNumberIsNegative(rhs))   // -Infinity -> +0
5369
0
          decNumberZero(res);
5370
0
         else decNumberCopy(res, rhs);  // +Infinity -> self
5371
0
        }
5372
0
       else decNaNs(res, rhs, NULL, set, status); // a NaN
5373
0
      break;}
5374
5375
0
    if (ISZERO(rhs)) {                  // zeros -> exact 1
5376
0
      decNumberZero(res);               // make clean 1
5377
0
      *res->lsu=1;                      // ..
5378
0
      break;}                           // [no status to set]
5379
5380
    // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path
5381
    // positive and negative tiny cases which will result in inexact
5382
    // 1.  This also allows the later add-accumulate to always be
5383
    // exact (because its length will never be more than twice the
5384
    // working precision).
5385
    // The comparator (tiny) needs just one digit, so use the
5386
    // decNumber d for it (reused as the divisor, etc., below); its
5387
    // exponent is such that if x is positive it will have
5388
    // set->digits-1 zeros between the decimal point and the digit,
5389
    // which is 4, and if x is negative one more zero there as the
5390
    // more precise result will be of the form 0.9999999 rather than
5391
    // 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0
5392
    // or 0.00000004 if digits=7 and x<0.  If RHS not larger than
5393
    // this then the result will be 1.000000
5394
0
    decNumberZero(d);                   // clean
5395
0
    *d->lsu=4;                          // set 4 ..
5396
0
    d->exponent=-set->digits;           // * 10**(-d)
5397
0
    if (decNumberIsNegative(rhs)) d->exponent--;  // negative case
5398
0
    comp=decCompare(d, rhs, 1);         // signless compare
5399
0
    if (comp==BADINT) {
5400
0
      *status|=DEC_Insufficient_storage;
5401
0
      break;}
5402
0
    if (comp>=0) {                      // rhs < d
5403
0
      Int shift=set->digits-1;
5404
0
      decNumberZero(res);               // set 1
5405
0
      *res->lsu=1;                      // ..
5406
0
      res->digits=decShiftToMost(res->lsu, 1, shift);
5407
0
      res->exponent=-shift;                  // make 1.0000...
5408
0
      *status|=DEC_Inexact | DEC_Rounded;    // .. inexactly
5409
0
      break;} // tiny
5410
5411
    // set up the context to be used for calculating a, as this is
5412
    // used on both paths below
5413
0
    decContextDefault(&aset, DEC_INIT_DECIMAL64);
5414
    // accumulator bounds are as requested (could underflow)
5415
0
    aset.emax=set->emax;                // usual bounds
5416
0
    aset.emin=set->emin;                // ..
5417
0
    aset.clamp=0;                       // and no concrete format
5418
5419
    // calculate the adjusted (Hull & Abrham) exponent (where the
5420
    // decimal point is just to the left of the coefficient msd)
5421
0
    h=rhs->exponent+rhs->digits;
5422
    // if h>8 then 10**h cannot be calculated safely; however, when
5423
    // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at
5424
    // least 6.59E+4342944, so (due to the restriction on Emax/Emin)
5425
    // overflow (or underflow to 0) is guaranteed -- so this case can
5426
    // be handled by simply forcing the appropriate excess
5427
0
    if (h>8) {                          // overflow/underflow
5428
      // set up here so Power call below will over or underflow to
5429
      // zero; set accumulator to either 2 or 0.02
5430
      // [stack buffer for a is always big enough for this]
5431
0
      decNumberZero(a);
5432
0
      *a->lsu=2;                        // not 1 but < exp(1)
5433
0
      if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02
5434
0
      h=8;                              // clamp so 10**h computable
5435
0
      p=9;                              // set a working precision
5436
0
      }
5437
0
     else {                             // h<=8
5438
0
      Int maxlever=(rhs->digits>8?1:0);
5439
      // [could/should increase this for precisions >40 or so, too]
5440
5441
      // if h is 8, cannot normalize to a lower upper limit because
5442
      // the final result will not be computable (see notes above),
5443
      // but leverage can be applied whenever h is less than 8.
5444
      // Apply as much as possible, up to a MAXLEVER digits, which
5445
      // sets the tradeoff against the cost of the later a**(10**h).
5446
      // As h is increased, the working precision below also
5447
      // increases to compensate for the "constant digits at the
5448
      // front" effect.
5449
0
      Int lever=MINI(8-h, maxlever);    // leverage attainable
5450
0
      Int use=-rhs->digits-lever;       // exponent to use for RHS
5451
0
      h+=lever;                         // apply leverage selected
5452
0
      if (h<0) {                        // clamp
5453
0
        use+=h;                         // [may end up subnormal]
5454
0
        h=0;
5455
0
        }
5456
      // Take a copy of RHS if it needs normalization (true whenever x>=1)
5457
0
      if (rhs->exponent!=use) {
5458
0
        decNumber *newrhs=bufr;         // assume will fit on stack
5459
0
        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5460
0
        if (needbytes>sizeof(bufr)) {   // need malloc space
5461
0
          allocrhs=(decNumber *)malloc(needbytes);
5462
0
          if (allocrhs==NULL) {         // hopeless -- abandon
5463
0
            *status|=DEC_Insufficient_storage;
5464
0
            break;}
5465
0
          newrhs=allocrhs;              // use the allocated space
5466
0
          }
5467
0
        decNumberCopy(newrhs, rhs);     // copy to safe space
5468
0
        newrhs->exponent=use;           // normalize; now <1
5469
0
        x=newrhs;                       // ready for use
5470
        // decNumberShow(x);
5471
0
        }
5472
5473
      // Now use the usual power series to evaluate exp(x).  The
5474
      // series starts as 1 + x + x^2/2 ... so prime ready for the
5475
      // third term by setting the term variable t=x, the accumulator
5476
      // a=1, and the divisor d=2.
5477
5478
      // First determine the working precision.  From Hull & Abrham
5479
      // this is set->digits+h+2.  However, if x is 'over-precise' we
5480
      // need to allow for all its digits to potentially participate
5481
      // (consider an x where all the excess digits are 9s) so in
5482
      // this case use x->digits+h+2
5483
0
      p=MAXI(x->digits, set->digits)+h+2;    // [h<=8]
5484
5485
      // a and t are variable precision, and depend on p, so space
5486
      // must be allocated for them if necessary
5487
5488
      // the accumulator needs to be able to hold 2p digits so that
5489
      // the additions on the second and subsequent iterations are
5490
      // sufficiently exact.
5491
0
      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5492
0
      if (needbytes>sizeof(bufa)) {     // need malloc space
5493
0
        allocbufa=(decNumber *)malloc(needbytes);
5494
0
        if (allocbufa==NULL) {          // hopeless -- abandon
5495
0
          *status|=DEC_Insufficient_storage;
5496
0
          break;}
5497
0
        a=allocbufa;                    // use the allocated space
5498
0
        }
5499
      // the term needs to be able to hold p digits (which is
5500
      // guaranteed to be larger than x->digits, so the initial copy
5501
      // is safe); it may also be used for the raise-to-power
5502
      // calculation below, which needs an extra two digits
5503
0
      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5504
0
      if (needbytes>sizeof(buft)) {     // need malloc space
5505
0
        allocbuft=(decNumber *)malloc(needbytes);
5506
0
        if (allocbuft==NULL) {          // hopeless -- abandon
5507
0
          *status|=DEC_Insufficient_storage;
5508
0
          break;}
5509
0
        t=allocbuft;                    // use the allocated space
5510
0
        }
5511
5512
0
      decNumberCopy(t, x);              // term=x
5513
0
      decNumberZero(a); *a->lsu=1;      // accumulator=1
5514
0
      decNumberZero(d); *d->lsu=2;      // divisor=2
5515
0
      decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment
5516
5517
      // set up the contexts for calculating a, t, and d
5518
0
      decContextDefault(&tset, DEC_INIT_DECIMAL64);
5519
0
      dset=tset;
5520
      // accumulator bounds are set above, set precision now
5521
0
      aset.digits=p*2;                  // double
5522
      // term bounds avoid any underflow or overflow
5523
0
      tset.digits=p;
5524
0
      tset.emin=DEC_MIN_EMIN;           // [emax is plenty]
5525
      // [dset.digits=16, etc., are sufficient]
5526
5527
      // finally ready to roll
5528
0
      for (;;) {
5529
        #if DECCHECK
5530
        iterations++;
5531
        #endif
5532
        // only the status from the accumulation is interesting
5533
        // [but it should remain unchanged after first add]
5534
0
        decAddOp(a, a, t, &aset, 0, status);           // a=a+t
5535
0
        decMultiplyOp(t, t, x, &tset, &ignore);        // t=t*x
5536
0
        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  // t=t/d
5537
        // the iteration ends when the term cannot affect the result,
5538
        // if rounded to p digits, which is when its value is smaller
5539
        // than the accumulator by p+1 digits.  There must also be
5540
        // full precision in a.
5541
0
        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5542
0
            && (a->digits>=p)) break;
5543
0
        decAddOp(d, d, &numone, &dset, 0, &ignore);    // d=d+1
5544
0
        } // iterate
5545
5546
      #if DECCHECK
5547
      // just a sanity check; comment out test to show always
5548
      if (iterations>p+3)
5549
        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5550
               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5551
      #endif
5552
0
      } // h<=8
5553
5554
    // apply postconditioning: a=a**(10**h) -- this is calculated
5555
    // at a slightly higher precision than Hull & Abrham suggest
5556
0
    if (h>0) {
5557
0
      Int seenbit=0;               // set once a 1-bit is seen
5558
0
      Int i;                       // counter
5559
0
      Int n=powers[h];             // always positive
5560
0
      aset.digits=p+2;             // sufficient precision
5561
      // avoid the overhead and many extra digits of decNumberPower
5562
      // as all that is needed is the short 'multipliers' loop; here
5563
      // accumulate the answer into t
5564
0
      decNumberZero(t); *t->lsu=1; // acc=1
5565
0
      for (i=1;;i++){              // for each bit [top bit ignored]
5566
        // abandon if have had overflow or terminal underflow
5567
0
        if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?
5568
0
          if ((*status&DEC_Overflow) || ISZERO(t)) break;}
5569
0
        n=n<<1;                    // move next bit to testable position
5570
0
        if (n<0) {                 // top bit is set
5571
0
          seenbit=1;               // OK, have a significant bit
5572
0
          decMultiplyOp(t, t, a, &aset, status); // acc=acc*x
5573
0
          }
5574
0
        if (i==31) break;          // that was the last bit
5575
0
        if (!seenbit) continue;    // no need to square 1
5576
0
        decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]
5577
0
        } /*i*/ // 32 bits
5578
      // decNumberShow(t);
5579
0
      a=t;                         // and carry on using t instead of a
5580
0
      }
5581
5582
    // Copy and round the result to res
5583
0
    residue=1;                          // indicate dirt to right ..
5584
0
    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5585
0
    aset.digits=set->digits;            // [use default rounding]
5586
0
    decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5587
0
    decFinish(res, set, &residue, status);       // cleanup/set flags
5588
0
    } while(0);                         // end protected
5589
5590
0
  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
5591
0
  if (allocbufa!=NULL) free(allocbufa); // ..
5592
0
  if (allocbuft!=NULL) free(allocbuft); // ..
5593
  // [status is handled by caller]
5594
0
  return res;
5595
0
  } // decExpOp
5596
5597
/* ------------------------------------------------------------------ */
5598
/* Initial-estimate natural logarithm table                           */
5599
/*                                                                    */
5600
/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5601
/*           The result is a 4-digit encode of the coefficient (c=the */
5602
/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5603
/*           exponent (e=the bottom 2 bits encoding 0-3)              */
5604
/*                                                                    */
5605
/*           The resulting value is given by:                         */
5606
/*                                                                    */
5607
/*             v = -c * 10**(-e-3)                                    */
5608
/*                                                                    */
5609
/*           where e and c are extracted from entry k = LNnn[x-10]    */
5610
/*           where x is truncated (NB) into the range 10 through 99,  */
5611
/*           and then c = k>>2 and e = k&3.                           */
5612
/* ------------------------------------------------------------------ */
5613
const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5614
  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5615
  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5616
 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5617
 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5618
 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5619
 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5620
 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5621
  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5622
 10130,  6046, 20055};
5623
5624
/* ------------------------------------------------------------------ */
5625
/* decLnOp -- effect natural logarithm                                */
5626
/*                                                                    */
5627
/*   This computes C = ln(A)                                          */
5628
/*                                                                    */
5629
/*   res is C, the result.  C may be A                                */
5630
/*   rhs is A                                                         */
5631
/*   set is the context; note that rounding mode has no effect        */
5632
/*                                                                    */
5633
/* C must have space for set->digits digits.                          */
5634
/*                                                                    */
5635
/* Notable cases:                                                     */
5636
/*   A<0 -> Invalid                                                   */
5637
/*   A=0 -> -Infinity (Exact)                                         */
5638
/*   A=+Infinity -> +Infinity (Exact)                                 */
5639
/*   A=1 exactly -> 0 (Exact)                                         */
5640
/*                                                                    */
5641
/* Restrictions (as for Exp):                                         */
5642
/*                                                                    */
5643
/*   digits, emax, and -emin in the context must be less than         */
5644
/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5645
/*   bounds or a zero.  This is an internal routine, so these         */
5646
/*   restrictions are contractual and not enforced.                   */
5647
/*                                                                    */
5648
/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5649
/* almost always be correctly rounded, but may be up to 1 ulp in      */
5650
/* error in rare cases.                                               */
5651
/* ------------------------------------------------------------------ */
5652
/* The result is calculated using Newton's method, with each          */
5653
/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5654
/* Epperson 1989.                                                     */
5655
/*                                                                    */
5656
/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5657
/* This has to be calculated at the sum of the precision of x and the */
5658
/* working precision.                                                 */
5659
/*                                                                    */
5660
/* Implementation notes:                                              */
5661
/*                                                                    */
5662
/* 1. This is separated out as decLnOp so it can be called from       */
5663
/*    other Mathematical functions (e.g., Log 10) with a wider range  */
5664
/*    than normal.  In particular, it can handle the slightly wider   */
5665
/*    (+9+2) range needed by a power function.                        */
5666
/*                                                                    */
5667
/* 2. The speed of this function is about 10x slower than exp, as     */
5668
/*    it typically needs 4-6 iterations for short numbers, and the    */
5669
/*    extra precision needed adds a squaring effect, twice.           */
5670
/*                                                                    */
5671
/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5672
/*    as these are common requests.  ln(10) is used by log10(x).      */
5673
/*                                                                    */
5674
/* 4. An iteration might be saved by widening the LNnn table, and     */
5675
/*    would certainly save at least one if it were made ten times     */
5676
/*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5677
/*    However, for most practical evaluations, at least four or five  */
5678
/*    iterations will be neede -- so this would only speed up by      */
5679
/*    20-25% and that probably does not justify increasing the table  */
5680
/*    size.                                                           */
5681
/*                                                                    */
5682
/* 5. The static buffers are larger than might be expected to allow   */
5683
/*    for calls from decNumberPower.                                  */
5684
/* ------------------------------------------------------------------ */
5685
decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5686
0
                    decContext *set, uInt *status) {
5687
0
  uInt ignore=0;                   // working status accumulator
5688
0
  uInt needbytes;                  // for space calculations
5689
0
  Int residue;                     // rounding residue
5690
0
  Int r;                           // rhs=f*10**r [see below]
5691
0
  Int p;                           // working precision
5692
0
  Int pp;                          // precision for iteration
5693
0
  Int t;                           // work
5694
5695
  // buffers for a (accumulator, typically precision+2) and b
5696
  // (adjustment calculator, same size)
5697
0
  decNumber bufa[D2N(DECBUFFER+12)];
5698
0
  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5699
0
  decNumber *a=bufa;               // accumulator/work
5700
0
  decNumber bufb[D2N(DECBUFFER*2+2)];
5701
0
  decNumber *allocbufb=NULL;       // -> allocated bufa, iff allocated
5702
0
  decNumber *b=bufb;               // adjustment/work
5703
5704
0
  decNumber  numone;               // constant 1
5705
0
  decNumber  cmp;                  // work
5706
0
  decContext aset, bset;           // working contexts
5707
5708
  #if DECCHECK
5709
  Int iterations=0;                // for later sanity check
5710
  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5711
  #endif
5712
5713
0
  do {                                  // protect allocated storage
5714
0
    if (SPECIALARG) {                   // handle infinities and NaNs
5715
0
      if (decNumberIsInfinite(rhs)) {   // an infinity
5716
0
        if (decNumberIsNegative(rhs))   // -Infinity -> error
5717
0
          *status|=DEC_Invalid_operation;
5718
0
         else decNumberCopy(res, rhs);  // +Infinity -> self
5719
0
        }
5720
0
       else decNaNs(res, rhs, NULL, set, status); // a NaN
5721
0
      break;}
5722
5723
0
    if (ISZERO(rhs)) {                  // +/- zeros -> -Infinity
5724
0
      decNumberZero(res);               // make clean
5725
0
      res->bits=DECINF|DECNEG;          // set - infinity
5726
0
      break;}                           // [no status to set]
5727
5728
    // Non-zero negatives are bad...
5729
0
    if (decNumberIsNegative(rhs)) {     // -x -> error
5730
0
      *status|=DEC_Invalid_operation;
5731
0
      break;}
5732
5733
    // Here, rhs is positive, finite, and in range
5734
5735
    // lookaside fastpath code for ln(2) and ln(10) at common lengths
5736
0
    if (rhs->exponent==0 && set->digits<=40) {
5737
      #if DECDPUN==1
5738
      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)
5739
      #else
5740
0
      if (rhs->lsu[0]==10 && rhs->digits==2) {                  // ln(10)
5741
0
      #endif
5742
0
        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5743
0
        #define LN10 "2.302585092994045684017991454684364207601"
5744
0
        decNumberFromString(res, LN10, &aset);
5745
0
        *status|=(DEC_Inexact | DEC_Rounded); // is inexact
5746
0
        break;}
5747
0
      if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)
5748
0
        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5749
0
        #define LN2 "0.6931471805599453094172321214581765680755"
5750
0
        decNumberFromString(res, LN2, &aset);
5751
0
        *status|=(DEC_Inexact | DEC_Rounded);
5752
0
        break;}
5753
0
      } // integer and short
5754
5755
    // Determine the working precision.  This is normally the
5756
    // requested precision + 2, with a minimum of 9.  However, if
5757
    // the rhs is 'over-precise' then allow for all its digits to
5758
    // potentially participate (consider an rhs where all the excess
5759
    // digits are 9s) so in this case use rhs->digits+2.
5760
0
    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5761
5762
    // Allocate space for the accumulator and the high-precision
5763
    // adjustment calculator, if necessary.  The accumulator must
5764
    // be able to hold p digits, and the adjustment up to
5765
    // rhs->digits+p digits.  They are also made big enough for 16
5766
    // digits so that they can be used for calculating the initial
5767
    // estimate.
5768
0
    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5769
0
    if (needbytes>sizeof(bufa)) {     // need malloc space
5770
0
      allocbufa=(decNumber *)malloc(needbytes);
5771
0
      if (allocbufa==NULL) {          // hopeless -- abandon
5772
0
        *status|=DEC_Insufficient_storage;
5773
0
        break;}
5774
0
      a=allocbufa;                    // use the allocated space
5775
0
      }
5776
0
    pp=p+rhs->digits;
5777
0
    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5778
0
    if (needbytes>sizeof(bufb)) {     // need malloc space
5779
0
      allocbufb=(decNumber *)malloc(needbytes);
5780
0
      if (allocbufb==NULL) {          // hopeless -- abandon
5781
0
        *status|=DEC_Insufficient_storage;
5782
0
        break;}
5783
0
      b=allocbufb;                    // use the allocated space
5784
0
      }
5785
5786
    // Prepare an initial estimate in acc. Calculate this by
5787
    // considering the coefficient of x to be a normalized fraction,
5788
    // f, with the decimal point at far left and multiplied by
5789
    // 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and
5790
    //   ln(x) = ln(f) + ln(10)*r
5791
    // Get the initial estimate for ln(f) from a small lookup
5792
    // table (see above) indexed by the first two digits of f,
5793
    // truncated.
5794
5795
0
    decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended
5796
0
    r=rhs->exponent+rhs->digits;        // 'normalised' exponent
5797
0
    decNumberFromInt32(a, r);           // a=r
5798
0
    decNumberFromInt32(b, 2302585);     // b=ln(10) (2.302585)
5799
0
    b->exponent=-6;                     //  ..
5800
0
    decMultiplyOp(a, a, b, &aset, &ignore);  // a=a*b
5801
    // now get top two digits of rhs into b by simple truncate and
5802
    // force to integer
5803
0
    residue=0;                          // (no residue)
5804
0
    aset.digits=2; aset.round=DEC_ROUND_DOWN;
5805
0
    decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten
5806
0
    b->exponent=0;                      // make integer
5807
0
    t=decGetInt(b);                     // [cannot fail]
5808
0
    if (t<10) t=X10(t);                 // adjust single-digit b
5809
0
    t=LNnn[t-10];                       // look up ln(b)
5810
0
    decNumberFromInt32(b, t>>2);        // b=ln(b) coefficient
5811
0
    b->exponent=-(t&3)-3;               // set exponent
5812
0
    b->bits=DECNEG;                     // ln(0.10)->ln(0.99) always -ve
5813
0
    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore
5814
0
    decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b
5815
    // the initial estimate is now in a, with up to 4 digits correct.
5816
    // When rhs is at or near Nmax the estimate will be low, so we
5817
    // will approach it from below, avoiding overflow when calling exp.
5818
5819
0
    decNumberZero(&numone); *numone.lsu=1;   // constant 1 for adjustment
5820
5821
    // accumulator bounds are as requested (could underflow, but
5822
    // cannot overflow)
5823
0
    aset.emax=set->emax;
5824
0
    aset.emin=set->emin;
5825
0
    aset.clamp=0;                       // no concrete format
5826
    // set up a context to be used for the multiply and subtract
5827
0
    bset=aset;
5828
0
    bset.emax=DEC_MAX_MATH*2;           // use double bounds for the
5829
0
    bset.emin=-DEC_MAX_MATH*2;          // adjustment calculation
5830
                                        // [see decExpOp call below]
5831
    // for each iteration double the number of digits to calculate,
5832
    // up to a maximum of p
5833
0
    pp=9;                               // initial precision
5834
    // [initially 9 as then the sequence starts 7+2, 16+2, and
5835
    // 34+2, which is ideal for standard-sized numbers]
5836
0
    aset.digits=pp;                     // working context
5837
0
    bset.digits=pp+rhs->digits;         // wider context
5838
0
    for (;;) {                          // iterate
5839
      #if DECCHECK
5840
      iterations++;
5841
      if (iterations>24) break;         // consider 9 * 2**24
5842
      #endif
5843
      // calculate the adjustment (exp(-a)*x-1) into b.  This is a
5844
      // catastrophic subtraction but it really is the difference
5845
      // from 1 that is of interest.
5846
      // Use the internal entry point to Exp as it allows the double
5847
      // range for calculating exp(-a) when a is the tiniest subnormal.
5848
0
      a->bits^=DECNEG;                  // make -a
5849
0
      decExpOp(b, a, &bset, &ignore);   // b=exp(-a)
5850
0
      a->bits^=DECNEG;                  // restore sign of a
5851
      // now multiply by rhs and subtract 1, at the wider precision
5852
0
      decMultiplyOp(b, b, rhs, &bset, &ignore);        // b=b*rhs
5853
0
      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1
5854
5855
      // the iteration ends when the adjustment cannot affect the
5856
      // result by >=0.5 ulp (at the requested digits), which
5857
      // is when its value is smaller than the accumulator by
5858
      // set->digits+1 digits (or it is zero) -- this is a looser
5859
      // requirement than for Exp because all that happens to the
5860
      // accumulator after this is the final rounding (but note that
5861
      // there must also be full precision in a, or a=0).
5862
5863
0
      if (decNumberIsZero(b) ||
5864
0
          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5865
0
        if (a->digits==p) break;
5866
0
        if (decNumberIsZero(a)) {
5867
0
          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?
5868
0
          if (cmp.lsu[0]==0) a->exponent=0;            // yes, exact 0
5869
0
           else *status|=(DEC_Inexact | DEC_Rounded);  // no, inexact
5870
0
          break;
5871
0
          }
5872
        // force padding if adjustment has gone to 0 before full length
5873
0
        if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5874
0
        }
5875
5876
      // not done yet ...
5877
0
      decAddOp(a, a, b, &aset, 0, &ignore);  // a=a+b for next estimate
5878
0
      if (pp==p) continue;                   // precision is at maximum
5879
      // lengthen the next calculation
5880
0
      pp=pp*2;                               // double precision
5881
0
      if (pp>p) pp=p;                        // clamp to maximum
5882
0
      aset.digits=pp;                        // working context
5883
0
      bset.digits=pp+rhs->digits;            // wider context
5884
0
      } // Newton's iteration
5885
5886
    #if DECCHECK
5887
    // just a sanity check; remove the test to show always
5888
    if (iterations>24)
5889
      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5890
            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5891
    #endif
5892
5893
    // Copy and round the result to res
5894
0
    residue=1;                          // indicate dirt to right
5895
0
    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5896
0
    aset.digits=set->digits;            // [use default rounding]
5897
0
    decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5898
0
    decFinish(res, set, &residue, status);       // cleanup/set flags
5899
0
    } while(0);                         // end protected
5900
5901
0
  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
5902
0
  if (allocbufb!=NULL) free(allocbufb); // ..
5903
  // [status is handled by caller]
5904
0
  return res;
5905
0
  } // decLnOp
5906
5907
/* ------------------------------------------------------------------ */
5908
/* decQuantizeOp  -- force exponent to requested value                */
5909
/*                                                                    */
5910
/*   This computes C = op(A, B), where op adjusts the coefficient     */
5911
/*   of C (by rounding or shifting) such that the exponent (-scale)   */
5912
/*   of C has the value B or matches the exponent of B.               */
5913
/*   The numerical value of C will equal A, except for the effects of */
5914
/*   any rounding that occurred.                                      */
5915
/*                                                                    */
5916
/*   res is C, the result.  C may be A or B                           */
5917
/*   lhs is A, the number to adjust                                   */
5918
/*   rhs is B, the requested exponent                                 */
5919
/*   set is the context                                               */
5920
/*   quant is 1 for quantize or 0 for rescale                         */
5921
/*   status is the status accumulator (this can be called without     */
5922
/*          risk of control loss)                                     */
5923
/*                                                                    */
5924
/* C must have space for set->digits digits.                          */
5925
/*                                                                    */
5926
/* Unless there is an error or the result is infinite, the exponent   */
5927
/* after the operation is guaranteed to be that requested.            */
5928
/* ------------------------------------------------------------------ */
5929
static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5930
                                 const decNumber *rhs, decContext *set,
5931
0
                                 Flag quant, uInt *status) {
5932
  #if DECSUBSET
5933
  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
5934
  decNumber *allocrhs=NULL;        // .., rhs
5935
  #endif
5936
0
  const decNumber *inrhs=rhs;      // save original rhs
5937
0
  Int   reqdigits=set->digits;     // requested DIGITS
5938
0
  Int   reqexp;                    // requested exponent [-scale]
5939
0
  Int   residue=0;                 // rounding residue
5940
0
  Int   etiny=set->emin-(reqdigits-1);
5941
5942
  #if DECCHECK
5943
  if (decCheckOperands(res, lhs, rhs, set)) return res;
5944
  #endif
5945
5946
0
  do {                             // protect allocated storage
5947
    #if DECSUBSET
5948
    if (!set->extended) {
5949
      // reduce operands and set lostDigits status, as needed
5950
      if (lhs->digits>reqdigits) {
5951
        alloclhs=decRoundOperand(lhs, set, status);
5952
        if (alloclhs==NULL) break;
5953
        lhs=alloclhs;
5954
        }
5955
      if (rhs->digits>reqdigits) { // [this only checks lostDigits]
5956
        allocrhs=decRoundOperand(rhs, set, status);
5957
        if (allocrhs==NULL) break;
5958
        rhs=allocrhs;
5959
        }
5960
      }
5961
    #endif
5962
    // [following code does not require input rounding]
5963
5964
    // Handle special values
5965
0
    if (SPECIALARGS) {
5966
      // NaNs get usual processing
5967
0
      if (SPECIALARGS & (DECSNAN | DECNAN))
5968
0
        decNaNs(res, lhs, rhs, set, status);
5969
      // one infinity but not both is bad
5970
0
      else if ((lhs->bits ^ rhs->bits) & DECINF)
5971
0
        *status|=DEC_Invalid_operation;
5972
      // both infinity: return lhs
5973
0
      else decNumberCopy(res, lhs);          // [nop if in place]
5974
0
      break;
5975
0
      }
5976
5977
    // set requested exponent
5978
0
    if (quant) reqexp=inrhs->exponent;  // quantize -- match exponents
5979
0
     else {                             // rescale -- use value of rhs
5980
      // Original rhs must be an integer that fits and is in range,
5981
      // which could be from -1999999997 to +999999999, thanks to
5982
      // subnormals
5983
0
      reqexp=decGetInt(inrhs);               // [cannot fail]
5984
0
      }
5985
5986
    #if DECSUBSET
5987
    if (!set->extended) etiny=set->emin;     // no subnormals
5988
    #endif
5989
5990
0
    if (reqexp==BADINT                       // bad (rescale only) or ..
5991
0
     || reqexp==BIGODD || reqexp==BIGEVEN    // very big (ditto) or ..
5992
0
     || (reqexp<etiny)                       // < lowest
5993
0
     || (reqexp>set->emax)) {                // > emax
5994
0
      *status|=DEC_Invalid_operation;
5995
0
      break;}
5996
5997
    // the RHS has been processed, so it can be overwritten now if necessary
5998
0
    if (ISZERO(lhs)) {                       // zero coefficient unchanged
5999
0
      decNumberCopy(res, lhs);               // [nop if in place]
6000
0
      res->exponent=reqexp;                  // .. just set exponent
6001
      #if DECSUBSET
6002
      if (!set->extended) res->bits=0;       // subset specification; no -0
6003
      #endif
6004
0
      }
6005
0
     else {                                  // non-zero lhs
6006
0
      Int adjust=reqexp-lhs->exponent;       // digit adjustment needed
6007
      // if adjusted coefficient will definitely not fit, give up now
6008
0
      if ((lhs->digits-adjust)>reqdigits) {
6009
0
        *status|=DEC_Invalid_operation;
6010
0
        break;
6011
0
        }
6012
6013
0
      if (adjust>0) {                        // increasing exponent
6014
        // this will decrease the length of the coefficient by adjust
6015
        // digits, and must round as it does so
6016
0
        decContext workset;                  // work
6017
0
        workset=*set;                        // clone rounding, etc.
6018
0
        workset.digits=lhs->digits-adjust;   // set requested length
6019
        // [note that the latter can be <1, here]
6020
0
        decCopyFit(res, lhs, &workset, &residue, status); // fit to result
6021
0
        decApplyRound(res, &workset, residue, status);    // .. and round
6022
0
        residue=0;                                        // [used]
6023
        // If just rounded a 999s case, exponent will be off by one;
6024
        // adjust back (after checking space), if so.
6025
0
        if (res->exponent>reqexp) {
6026
          // re-check needed, e.g., for quantize(0.9999, 0.001) under
6027
          // set->digits==3
6028
0
          if (res->digits==reqdigits) {      // cannot shift by 1
6029
0
            *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]
6030
0
            *status|=DEC_Invalid_operation;
6031
0
            break;
6032
0
            }
6033
0
          res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift
6034
0
          res->exponent--;                   // (re)adjust the exponent.
6035
0
          }
6036
        #if DECSUBSET
6037
        if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0
6038
        #endif
6039
0
        } // increase
6040
0
       else /* adjust<=0 */ {                // decreasing or = exponent
6041
        // this will increase the length of the coefficient by -adjust
6042
        // digits, by adding zero or more trailing zeros; this is
6043
        // already checked for fit, above
6044
0
        decNumberCopy(res, lhs);             // [it will fit]
6045
        // if padding needed (adjust<0), add it now...
6046
0
        if (adjust<0) {
6047
0
          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
6048
0
          res->exponent+=adjust;             // adjust the exponent
6049
0
          }
6050
0
        } // decrease
6051
0
      } // non-zero
6052
6053
    // Check for overflow [do not use Finalize in this case, as an
6054
    // overflow here is a "don't fit" situation]
6055
0
    if (res->exponent>set->emax-res->digits+1) {  // too big
6056
0
      *status|=DEC_Invalid_operation;
6057
0
      break;
6058
0
      }
6059
0
     else {
6060
0
      decFinalize(res, set, &residue, status);    // set subnormal flags
6061
0
      *status&=~DEC_Underflow;          // suppress Underflow [as per 754]
6062
0
      }
6063
0
    } while(0);                         // end protected
6064
6065
  #if DECSUBSET
6066
  if (allocrhs!=NULL) free(allocrhs);   // drop any storage used
6067
  if (alloclhs!=NULL) free(alloclhs);   // ..
6068
  #endif
6069
0
  return res;
6070
0
  } // decQuantizeOp
6071
6072
/* ------------------------------------------------------------------ */
6073
/* decCompareOp -- compare, min, or max two Numbers                   */
6074
/*                                                                    */
6075
/*   This computes C = A ? B and carries out one of four operations:  */
6076
/*     COMPARE    -- returns the signum (as a number) giving the      */
6077
/*                   result of a comparison unless one or both        */
6078
/*                   operands is a NaN (in which case a NaN results)  */
6079
/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
6080
/*                   Invalid operation.                               */
6081
/*     COMPMAX    -- returns the larger of the operands, using the    */
6082
/*                   754 maxnum operation                             */
6083
/*     COMPMAXMAG -- ditto, comparing absolute values                 */
6084
/*     COMPMIN    -- the 754 minnum operation                         */
6085
/*     COMPMINMAG -- ditto, comparing absolute values                 */
6086
/*     COMTOTAL   -- returns the signum (as a number) giving the      */
6087
/*                   result of a comparison using 754 total ordering  */
6088
/*                                                                    */
6089
/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
6090
/*   lhs is A                                                         */
6091
/*   rhs is B                                                         */
6092
/*   set is the context                                               */
6093
/*   op  is the operation flag                                        */
6094
/*   status is the usual accumulator                                  */
6095
/*                                                                    */
6096
/* C must have space for one digit for COMPARE or set->digits for     */
6097
/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6098
/* ------------------------------------------------------------------ */
6099
/* The emphasis here is on speed for common cases, and avoiding       */
6100
/* coefficient comparison if possible.                                */
6101
/* ------------------------------------------------------------------ */
6102
decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6103
                         const decNumber *rhs, decContext *set,
6104
0
                         Flag op, uInt *status) {
6105
  #if DECSUBSET
6106
  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
6107
  decNumber *allocrhs=NULL;        // .., rhs
6108
  #endif
6109
0
  Int   result=0;                  // default result value
6110
0
  uByte merged;                    // work
6111
6112
  #if DECCHECK
6113
  if (decCheckOperands(res, lhs, rhs, set)) return res;
6114
  #endif
6115
6116
0
  do {                             // protect allocated storage
6117
    #if DECSUBSET
6118
    if (!set->extended) {
6119
      // reduce operands and set lostDigits status, as needed
6120
      if (lhs->digits>set->digits) {
6121
        alloclhs=decRoundOperand(lhs, set, status);
6122
        if (alloclhs==NULL) {result=BADINT; break;}
6123
        lhs=alloclhs;
6124
        }
6125
      if (rhs->digits>set->digits) {
6126
        allocrhs=decRoundOperand(rhs, set, status);
6127
        if (allocrhs==NULL) {result=BADINT; break;}
6128
        rhs=allocrhs;
6129
        }
6130
      }
6131
    #endif
6132
    // [following code does not require input rounding]
6133
6134
    // If total ordering then handle differing signs 'up front'
6135
0
    if (op==COMPTOTAL) {                // total ordering
6136
0
      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6137
0
        result=-1;
6138
0
        break;
6139
0
        }
6140
0
      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6141
0
        result=+1;
6142
0
        break;
6143
0
        }
6144
0
      }
6145
6146
    // handle NaNs specially; let infinities drop through
6147
    // This assumes sNaN (even just one) leads to NaN.
6148
0
    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6149
0
    if (merged) {                       // a NaN bit set
6150
0
      if (op==COMPARE){;}               // result will be NaN
6151
0
       else if (op==COMPSIG)            // treat qNaN as sNaN
6152
0
        *status|=DEC_Invalid_operation | DEC_sNaN;
6153
0
       else if (op==COMPTOTAL) {        // total ordering, always finite
6154
        // signs are known to be the same; compute the ordering here
6155
        // as if the signs are both positive, then invert for negatives
6156
0
        if (!decNumberIsNaN(lhs)) result=-1;
6157
0
         else if (!decNumberIsNaN(rhs)) result=+1;
6158
         // here if both NaNs
6159
0
         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6160
0
         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6161
0
         else { // both NaN or both sNaN
6162
          // now it just depends on the payload
6163
0
          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6164
0
                                rhs->lsu, D2U(rhs->digits), 0);
6165
          // [Error not possible, as these are 'aligned']
6166
0
          } // both same NaNs
6167
0
        if (decNumberIsNegative(lhs)) result=-result;
6168
0
        break;
6169
0
        } // total order
6170
6171
0
       else if (merged & DECSNAN){;}         // sNaN -> qNaN
6172
0
       else { // here if MIN or MAX and one or two quiet NaNs
6173
        // min or max -- 754 rules ignore single NaN
6174
0
        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6175
          // just one NaN; force choice to be the non-NaN operand
6176
0
          op=COMPMAX;
6177
0
          if (lhs->bits & DECNAN) result=-1; // pick rhs
6178
0
                             else result=+1; // pick lhs
6179
0
          break;
6180
0
          }
6181
0
        } // max or min
6182
0
      op=COMPNAN;                            // use special path
6183
0
      decNaNs(res, lhs, rhs, set, status);   // propagate NaN
6184
0
      break;
6185
0
      }
6186
    // have numbers
6187
0
    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6188
0
     else result=decCompare(lhs, rhs, 0);    // sign matters
6189
0
    } while(0);                              // end protected
6190
6191
0
  if (result==BADINT) *status|=DEC_Insufficient_storage; // rare
6192
0
   else {
6193
0
    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum
6194
0
      if (op==COMPTOTAL && result==0) {
6195
        // operands are numerically equal or same NaN (and same sign,
6196
        // tested first); if identical, leave result 0
6197
0
        if (lhs->exponent!=rhs->exponent) {
6198
0
          if (lhs->exponent<rhs->exponent) result=-1;
6199
0
           else result=+1;
6200
0
          if (decNumberIsNegative(lhs)) result=-result;
6201
0
          } // lexp!=rexp
6202
0
        } // total-order by exponent
6203
0
      decNumberZero(res);               // [always a valid result]
6204
0
      if (result!=0) {                  // must be -1 or +1
6205
0
        *res->lsu=1;
6206
0
        if (result<0) res->bits=DECNEG;
6207
0
        }
6208
0
      }
6209
0
     else if (op==COMPNAN){;}           // special, drop through
6210
0
     else {                             // MAX or MIN, non-NaN result
6211
0
      Int residue=0;                    // rounding accumulator
6212
      // choose the operand for the result
6213
0
      const decNumber *choice;
6214
0
      if (result==0) { // operands are numerically equal
6215
        // choose according to sign then exponent (see 754)
6216
0
        uByte slhs=(lhs->bits & DECNEG);
6217
0
        uByte srhs=(rhs->bits & DECNEG);
6218
        #if DECSUBSET
6219
        if (!set->extended) {           // subset: force left-hand
6220
          op=COMPMAX;
6221
          result=+1;
6222
          }
6223
        else
6224
        #endif
6225
0
        if (slhs!=srhs) {          // signs differ
6226
0
          if (slhs) result=-1;     // rhs is max
6227
0
               else result=+1;     // lhs is max
6228
0
          }
6229
0
         else if (slhs && srhs) {  // both negative
6230
0
          if (lhs->exponent<rhs->exponent) result=+1;
6231
0
                                      else result=-1;
6232
          // [if equal, use lhs, technically identical]
6233
0
          }
6234
0
         else {                    // both positive
6235
0
          if (lhs->exponent>rhs->exponent) result=+1;
6236
0
                                      else result=-1;
6237
          // [ditto]
6238
0
          }
6239
0
        } // numerically equal
6240
      // here result will be non-0; reverse if looking for MIN
6241
0
      if (op==COMPMIN || op==COMPMINMAG) result=-result;
6242
0
      choice=(result>0 ? lhs : rhs);    // choose
6243
      // copy chosen to result, rounding if need be
6244
0
      decCopyFit(res, choice, set, &residue, status);
6245
0
      decFinish(res, set, &residue, status);
6246
0
      }
6247
0
    }
6248
  #if DECSUBSET
6249
  if (allocrhs!=NULL) free(allocrhs);   // free any storage used
6250
  if (alloclhs!=NULL) free(alloclhs);   // ..
6251
  #endif
6252
0
  return res;
6253
0
  } // decCompareOp
6254
6255
/* ------------------------------------------------------------------ */
6256
/* decCompare -- compare two decNumbers by numerical value            */
6257
/*                                                                    */
6258
/*  This routine compares A ? B without altering them.                */
6259
/*                                                                    */
6260
/*  Arg1 is A, a decNumber which is not a NaN                         */
6261
/*  Arg2 is B, a decNumber which is not a NaN                         */
6262
/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6263
/*                                                                    */
6264
/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6265
/*  (the only possible failure is an allocation error)                */
6266
/* ------------------------------------------------------------------ */
6267
static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6268
18
                      Flag abs) {
6269
18
  Int   result;                    // result value
6270
18
  Int   sigr;                      // rhs signum
6271
18
  Int   compare;                   // work
6272
6273
18
  result=1;                                  // assume signum(lhs)
6274
18
  if (ISZERO(lhs)) result=0;
6275
18
  if (abs) {
6276
18
    if (ISZERO(rhs)) return result;          // LHS wins or both 0
6277
    // RHS is non-zero
6278
18
    if (result==0) return -1;                // LHS is 0; RHS wins
6279
    // [here, both non-zero, result=1]
6280
18
    }
6281
0
   else {                                    // signs matter
6282
0
    if (result && decNumberIsNegative(lhs)) result=-1;
6283
0
    sigr=1;                                  // compute signum(rhs)
6284
0
    if (ISZERO(rhs)) sigr=0;
6285
0
     else if (decNumberIsNegative(rhs)) sigr=-1;
6286
0
    if (result > sigr) return +1;            // L > R, return 1
6287
0
    if (result < sigr) return -1;            // L < R, return -1
6288
0
    if (result==0) return 0;                   // both 0
6289
0
    }
6290
6291
  // signums are the same; both are non-zero
6292
18
  if ((lhs->bits | rhs->bits) & DECINF) {    // one or more infinities
6293
0
    if (decNumberIsInfinite(rhs)) {
6294
0
      if (decNumberIsInfinite(lhs)) result=0;// both infinite
6295
0
       else result=-result;                  // only rhs infinite
6296
0
      }
6297
0
    return result;
6298
0
    }
6299
  // must compare the coefficients, allowing for exponents
6300
18
  if (lhs->exponent>rhs->exponent) {         // LHS exponent larger
6301
    // swap sides, and sign
6302
0
    const decNumber *temp=lhs;
6303
0
    lhs=rhs;
6304
0
    rhs=temp;
6305
0
    result=-result;
6306
0
    }
6307
18
  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6308
18
                         rhs->lsu, D2U(rhs->digits),
6309
18
                         rhs->exponent-lhs->exponent);
6310
18
  if (compare!=BADINT) compare*=result;      // comparison succeeded
6311
18
  return compare;
6312
18
  } // decCompare
6313
6314
/* ------------------------------------------------------------------ */
6315
/* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6316
/*                                                                    */
6317
/*  This routine compares A ? B*10**E where A and B are unit arrays   */
6318
/*  A is a plain integer                                              */
6319
/*  B has an exponent of E (which must be non-negative)               */
6320
/*                                                                    */
6321
/*  Arg1 is A first Unit (lsu)                                        */
6322
/*  Arg2 is A length in Units                                         */
6323
/*  Arg3 is B first Unit (lsu)                                        */
6324
/*  Arg4 is B length in Units                                         */
6325
/*  Arg5 is E (0 if the units are aligned)                            */
6326
/*                                                                    */
6327
/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6328
/*  (the only possible failure is an allocation error, which can      */
6329
/*  only occur if E!=0)                                               */
6330
/* ------------------------------------------------------------------ */
6331
static Int decUnitCompare(const Unit *a, Int alength,
6332
18
                          const Unit *b, Int blength, Int exp) {
6333
18
  Unit  *acc;                      // accumulator for result
6334
18
  Unit  accbuff[SD2U(DECBUFFER*2+1)]; // local buffer
6335
18
  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
6336
18
  Int   accunits, need;            // units in use or needed for acc
6337
18
  const Unit *l, *r, *u;           // work
6338
18
  Int   expunits, exprem, result;  // ..
6339
6340
18
  if (exp==0) {                    // aligned; fastpath
6341
0
    if (alength>blength) return 1;
6342
0
    if (alength<blength) return -1;
6343
    // same number of units in both -- need unit-by-unit compare
6344
0
    l=a+alength-1;
6345
0
    r=b+alength-1;
6346
0
    for (;l>=a; l--, r--) {
6347
0
      if (*l>*r) return 1;
6348
0
      if (*l<*r) return -1;
6349
0
      }
6350
0
    return 0;                      // all units match
6351
0
    } // aligned
6352
6353
  // Unaligned.  If one is >1 unit longer than the other, padded
6354
  // approximately, then can return easily
6355
18
  if (alength>blength+(Int)D2U(exp)) return 1;
6356
18
  if (alength+1<blength+(Int)D2U(exp)) return -1;
6357
6358
  // Need to do a real subtract.  For this, a result buffer is needed
6359
  // even though only the sign is of interest.  Its length needs
6360
  // to be the larger of alength and padded blength, +2
6361
18
  need=blength+D2U(exp);                // maximum real length of B
6362
18
  if (need<alength) need=alength;
6363
18
  need+=2;
6364
18
  acc=accbuff;                          // assume use local buffer
6365
18
  if (need*sizeof(Unit)>sizeof(accbuff)) {
6366
18
    allocacc=(Unit *)malloc(need*sizeof(Unit));
6367
18
    if (allocacc==NULL) return BADINT;  // hopeless -- abandon
6368
18
    acc=allocacc;
6369
18
    }
6370
  // Calculate units and remainder from exponent.
6371
18
  expunits=exp/DECDPUN;
6372
18
  exprem=exp%DECDPUN;
6373
  // subtract [A+B*(-m)]
6374
18
  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6375
18
                         -(Int)powers[exprem]);
6376
  // [UnitAddSub result may have leading zeros, even on zero]
6377
18
  if (accunits<0) result=-1;            // negative result
6378
18
   else {                               // non-negative result
6379
    // check units of the result before freeing any storage
6380
109
    for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6381
18
    result=(*u==0 ? 0 : +1);
6382
18
    }
6383
  // clean up and return the result
6384
18
  if (allocacc!=NULL) free(allocacc);   // drop any storage used
6385
18
  return result;
6386
18
  } // decUnitCompare
6387
6388
/* ------------------------------------------------------------------ */
6389
/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6390
/*                                                                    */
6391
/*  This routine performs the calculation:                            */
6392
/*                                                                    */
6393
/*  C=A+(B*M)                                                         */
6394
/*                                                                    */
6395
/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6396
/*                                                                    */
6397
/*  A may be shorter or longer than B.                                */
6398
/*                                                                    */
6399
/*  Leading zeros are not removed after a calculation.  The result is */
6400
/*  either the same length as the longer of A and B (adding any       */
6401
/*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6402
/*                                                                    */
6403
/*  A and B content are not altered unless C is also A or B.          */
6404
/*  C may be the same array as A or B, but only if no zero padding is */
6405
/*  requested (that is, C may be B only if bshift==0).                */
6406
/*  C is filled from the lsu; only those units necessary to complete  */
6407
/*  the calculation are referenced.                                   */
6408
/*                                                                    */
6409
/*  Arg1 is A first Unit (lsu)                                        */
6410
/*  Arg2 is A length in Units                                         */
6411
/*  Arg3 is B first Unit (lsu)                                        */
6412
/*  Arg4 is B length in Units                                         */
6413
/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6414
/*  Arg6 is C first Unit (lsu)                                        */
6415
/*  Arg7 is M, the multiplier                                         */
6416
/*                                                                    */
6417
/*  returns the count of Units written to C, which will be non-zero   */
6418
/*  and negated if the result is negative.  That is, the sign of the  */
6419
/*  returned Int is the sign of the result (positive for zero) and    */
6420
/*  the absolute value of the Int is the count of Units.              */
6421
/*                                                                    */
6422
/*  It is the caller's responsibility to make sure that C size is     */
6423
/*  safe, allowing space if necessary for a one-Unit carry.           */
6424
/*                                                                    */
6425
/*  This routine is severely performance-critical; *any* change here  */
6426
/*  must be measured (timed) to assure no performance degradation.    */
6427
/*  In particular, trickery here tends to be counter-productive, as   */
6428
/*  increased complexity of code hurts register optimizations on      */
6429
/*  register-poor architectures.  Avoiding divisions is nearly        */
6430
/*  always a Good Idea, however.                                      */
6431
/*                                                                    */
6432
/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6433
/* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6434
/* ------------------------------------------------------------------ */
6435
static Int decUnitAddSub(const Unit *a, Int alength,
6436
                         const Unit *b, Int blength, Int bshift,
6437
2.30k
                         Unit *c, Int m) {
6438
2.30k
  const Unit *alsu=a;              // A lsu [need to remember it]
6439
2.30k
  Unit *clsu=c;                    // C ditto
6440
2.30k
  Unit *minC;                      // low water mark for C
6441
2.30k
  Unit *maxC;                      // high water mark for C
6442
2.30k
  eInt carry=0;                    // carry integer (could be Long)
6443
2.30k
  Int  add;                        // work
6444
2.30k
  #if DECDPUN<=4                   // myriadal, millenary, etc.
6445
2.30k
  Int  est;                        // estimated quotient
6446
2.30k
  #endif
6447
6448
  #if DECTRACE
6449
  if (alength<1 || blength<1)
6450
    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6451
  #endif
6452
6453
2.30k
  maxC=c+alength;                  // A is usually the longer
6454
2.30k
  minC=c+blength;                  // .. and B the shorter
6455
2.30k
  if (bshift!=0) {                 // B is shifted; low As copy across
6456
18
    minC+=bshift;
6457
    // if in place [common], skip copy unless there's a gap [rare]
6458
18
    if (a==c && bshift<=alength) {
6459
0
      c+=bshift;
6460
0
      a+=bshift;
6461
0
      }
6462
468
     else for (; c<clsu+bshift; a++, c++) {  // copy needed
6463
450
      if (a<alsu+alength) *c=*a;
6464
0
       else *c=0;
6465
450
      }
6466
18
    }
6467
2.30k
  if (minC>maxC) { // swap
6468
0
    Unit *hold=minC;
6469
0
    minC=maxC;
6470
0
    maxC=hold;
6471
0
    }
6472
6473
  // For speed, do the addition as two loops; the first where both A
6474
  // and B contribute, and the second (if necessary) where only one or
6475
  // other of the numbers contribute.
6476
  // Carry handling is the same (i.e., duplicated) in each case.
6477
4.61k
  for (; c<minC; c++) {
6478
2.30k
    carry+=*a;
6479
2.30k
    a++;
6480
2.30k
    carry+=((eInt)*b)*m;                // [special-casing m=1/-1
6481
2.30k
    b++;                                // here is not a win]
6482
    // here carry is new Unit of digits; it could be +ve or -ve
6483
2.30k
    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6484
1.80k
      *c=(Unit)carry;
6485
1.80k
      carry=0;
6486
1.80k
      continue;
6487
1.80k
      }
6488
    #if DECDPUN==4                           // use divide-by-multiply
6489
      if (carry>=0) {
6490
        est=(((ueInt)carry>>11)*53687)>>18;
6491
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6492
        carry=est;                           // likely quotient [89%]
6493
        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6494
        carry++;
6495
        *c-=DECDPUNMAX+1;
6496
        continue;
6497
        }
6498
      // negative case
6499
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6500
      est=(((ueInt)carry>>11)*53687)>>18;
6501
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6502
      carry=est-(DECDPUNMAX+1);              // correctly negative
6503
      if (*c<DECDPUNMAX+1) continue;         // was OK
6504
      carry++;
6505
      *c-=DECDPUNMAX+1;
6506
    #elif DECDPUN==3
6507
500
      if (carry>=0) {
6508
500
        est=(((ueInt)carry>>3)*16777)>>21;
6509
500
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6510
500
        carry=est;                           // likely quotient [99%]
6511
500
        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6512
500
        carry++;
6513
500
        *c-=DECDPUNMAX+1;
6514
500
        continue;
6515
500
        }
6516
      // negative case
6517
0
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6518
0
      est=(((ueInt)carry>>3)*16777)>>21;
6519
0
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6520
0
      carry=est-(DECDPUNMAX+1);              // correctly negative
6521
0
      if (*c<DECDPUNMAX+1) continue;         // was OK
6522
0
      carry++;
6523
0
      *c-=DECDPUNMAX+1;
6524
    #elif DECDPUN<=2
6525
      // Can use QUOT10 as carry <= 4 digits
6526
      if (carry>=0) {
6527
        est=QUOT10(carry, DECDPUN);
6528
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6529
        carry=est;                           // quotient
6530
        continue;
6531
        }
6532
      // negative case
6533
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6534
      est=QUOT10(carry, DECDPUN);
6535
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6536
      carry=est-(DECDPUNMAX+1);              // correctly negative
6537
    #else
6538
      // remainder operator is undefined if negative, so must test
6539
      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   // fastpath carry +1
6540
        *c=(Unit)(carry-(DECDPUNMAX+1));     // [helps additions]
6541
        carry=1;
6542
        continue;
6543
        }
6544
      if (carry>=0) {
6545
        *c=(Unit)(carry%(DECDPUNMAX+1));
6546
        carry=carry/(DECDPUNMAX+1);
6547
        continue;
6548
        }
6549
      // negative case
6550
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6551
      *c=(Unit)(carry%(DECDPUNMAX+1));
6552
      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6553
    #endif
6554
0
    } // c
6555
6556
  // now may have one or other to complete
6557
  // [pretest to avoid loop setup/shutdown]
6558
56.9k
  if (c<maxC) for (; c<maxC; c++) {
6559
54.7k
    if (a<alsu+alength) {               // still in A
6560
54.7k
      carry+=*a;
6561
54.7k
      a++;
6562
54.7k
      }
6563
0
     else {                             // inside B
6564
0
      carry+=((eInt)*b)*m;
6565
0
      b++;
6566
0
      }
6567
    // here carry is new Unit of digits; it could be +ve or -ve and
6568
    // magnitude up to DECDPUNMAX squared
6569
54.7k
    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6570
54.4k
      *c=(Unit)carry;
6571
54.4k
      carry=0;
6572
54.4k
      continue;
6573
54.4k
      }
6574
    // result for this unit is negative or >DECDPUNMAX
6575
    #if DECDPUN==4                           // use divide-by-multiply
6576
      if (carry>=0) {
6577
        est=(((ueInt)carry>>11)*53687)>>18;
6578
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6579
        carry=est;                           // likely quotient [79.7%]
6580
        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6581
        carry++;
6582
        *c-=DECDPUNMAX+1;
6583
        continue;
6584
        }
6585
      // negative case
6586
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6587
      est=(((ueInt)carry>>11)*53687)>>18;
6588
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6589
      carry=est-(DECDPUNMAX+1);              // correctly negative
6590
      if (*c<DECDPUNMAX+1) continue;         // was OK
6591
      carry++;
6592
      *c-=DECDPUNMAX+1;
6593
    #elif DECDPUN==3
6594
322
      if (carry>=0) {
6595
322
        est=(((ueInt)carry>>3)*16777)>>21;
6596
322
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6597
322
        carry=est;                           // likely quotient [99%]
6598
322
        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6599
322
        carry++;
6600
322
        *c-=DECDPUNMAX+1;
6601
322
        continue;
6602
322
        }
6603
      // negative case
6604
0
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6605
0
      est=(((ueInt)carry>>3)*16777)>>21;
6606
0
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6607
0
      carry=est-(DECDPUNMAX+1);              // correctly negative
6608
0
      if (*c<DECDPUNMAX+1) continue;         // was OK
6609
0
      carry++;
6610
0
      *c-=DECDPUNMAX+1;
6611
    #elif DECDPUN<=2
6612
      if (carry>=0) {
6613
        est=QUOT10(carry, DECDPUN);
6614
        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6615
        carry=est;                           // quotient
6616
        continue;
6617
        }
6618
      // negative case
6619
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6620
      est=QUOT10(carry, DECDPUN);
6621
      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6622
      carry=est-(DECDPUNMAX+1);              // correctly negative
6623
    #else
6624
      if ((ueInt)carry<(DECDPUNMAX+1)*2){    // fastpath carry 1
6625
        *c=(Unit)(carry-(DECDPUNMAX+1));
6626
        carry=1;
6627
        continue;
6628
        }
6629
      // remainder operator is undefined if negative, so must test
6630
      if (carry>=0) {
6631
        *c=(Unit)(carry%(DECDPUNMAX+1));
6632
        carry=carry/(DECDPUNMAX+1);
6633
        continue;
6634
        }
6635
      // negative case
6636
      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6637
      *c=(Unit)(carry%(DECDPUNMAX+1));
6638
      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6639
    #endif
6640
0
    } // c
6641
6642
  // OK, all A and B processed; might still have carry or borrow
6643
  // return number of Units in the result, negated if a borrow
6644
2.30k
  if (carry==0) return c-clsu;     // no carry, so no more to do
6645
0
  if (carry>0) {                   // positive carry
6646
0
    *c=(Unit)carry;                // place as new unit
6647
0
    c++;                           // ..
6648
0
    return c-clsu;
6649
0
    }
6650
  // -ve carry: it's a borrow; complement needed
6651
0
  add=1;                           // temporary carry...
6652
0
  for (c=clsu; c<maxC; c++) {
6653
0
    add=DECDPUNMAX+add-*c;
6654
0
    if (add<=DECDPUNMAX) {
6655
0
      *c=(Unit)add;
6656
0
      add=0;
6657
0
      }
6658
0
     else {
6659
0
      *c=0;
6660
0
      add=1;
6661
0
      }
6662
0
    }
6663
  // add an extra unit iff it would be non-zero
6664
  #if DECTRACE
6665
    printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6666
  #endif
6667
0
  if ((add-carry-1)!=0) {
6668
0
    *c=(Unit)(add-carry-1);
6669
0
    c++;                      // interesting, include it
6670
0
    }
6671
0
  return clsu-c;              // -ve result indicates borrowed
6672
0
  } // decUnitAddSub
6673
6674
/* ------------------------------------------------------------------ */
6675
/* decTrim -- trim trailing zeros or normalize                        */
6676
/*                                                                    */
6677
/*   dn is the number to trim or normalize                            */
6678
/*   set is the context to use to check for clamp                     */
6679
/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6680
/*   noclamp is 1 to unconditional (unclamped) trim                   */
6681
/*   dropped returns the number of discarded trailing zeros           */
6682
/*   returns dn                                                       */
6683
/*                                                                    */
6684
/* If clamp is set in the context then the number of zeros trimmed    */
6685
/* may be limited if the exponent is high.                            */
6686
/* All fields are updated as required.  This is a utility operation,  */
6687
/* so special values are unchanged and no error is possible.          */
6688
/* ------------------------------------------------------------------ */
6689
static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6690
0
                           Flag noclamp, Int *dropped) {
6691
0
  Int   d, exp;                    // work
6692
0
  uInt  cut;                       // ..
6693
0
  Unit  *up;                       // -> current Unit
6694
6695
  #if DECCHECK
6696
  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6697
  #endif
6698
6699
0
  *dropped=0;                           // assume no zeros dropped
6700
0
  if ((dn->bits & DECSPECIAL)           // fast exit if special ..
6701
0
    || (*dn->lsu & 0x01)) return dn;    // .. or odd
6702
0
  if (ISZERO(dn)) {                     // .. or 0
6703
0
    dn->exponent=0;                     // (sign is preserved)
6704
0
    return dn;
6705
0
    }
6706
6707
  // have a finite number which is even
6708
0
  exp=dn->exponent;
6709
0
  cut=1;                           // digit (1-DECDPUN) in Unit
6710
0
  up=dn->lsu;                      // -> current Unit
6711
0
  for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]
6712
    // slice by powers
6713
0
    #if DECDPUN<=4
6714
0
      uInt quot=QUOT10(*up, cut);
6715
0
      if ((*up-quot*powers[cut])!=0) break;  // found non-0 digit
6716
    #else
6717
      if (*up%powers[cut]!=0) break;         // found non-0 digit
6718
    #endif
6719
    // have a trailing 0
6720
0
    if (!all) {                    // trimming
6721
      // [if exp>0 then all trailing 0s are significant for trim]
6722
0
      if (exp<=0) {                // if digit might be significant
6723
0
        if (exp==0) break;         // then quit
6724
0
        exp++;                     // next digit might be significant
6725
0
        }
6726
0
      }
6727
0
    cut++;                         // next power
6728
0
    if (cut>DECDPUN) {             // need new Unit
6729
0
      up++;
6730
0
      cut=1;
6731
0
      }
6732
0
    } // d
6733
0
  if (d==0) return dn;             // none to drop
6734
6735
  // may need to limit drop if clamping
6736
0
  if (set->clamp && !noclamp) {
6737
0
    Int maxd=set->emax-set->digits+1-dn->exponent;
6738
0
    if (maxd<=0) return dn;        // nothing possible
6739
0
    if (d>maxd) d=maxd;
6740
0
    }
6741
6742
  // effect the drop
6743
0
  decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6744
0
  dn->exponent+=d;                 // maintain numerical value
6745
0
  dn->digits-=d;                   // new length
6746
0
  *dropped=d;                      // report the count
6747
0
  return dn;
6748
0
  } // decTrim
6749
6750
/* ------------------------------------------------------------------ */
6751
/* decReverse -- reverse a Unit array in place                        */
6752
/*                                                                    */
6753
/*   ulo    is the start of the array                                 */
6754
/*   uhi    is the end of the array (highest Unit to include)         */
6755
/*                                                                    */
6756
/* The units ulo through uhi are reversed in place (if the number     */
6757
/* of units is odd, the middle one is untouched).  Note that the      */
6758
/* digit(s) in each unit are unaffected.                              */
6759
/* ------------------------------------------------------------------ */
6760
0
static void decReverse(Unit *ulo, Unit *uhi) {
6761
0
  Unit temp;
6762
0
  for (; ulo<uhi; ulo++, uhi--) {
6763
0
    temp=*ulo;
6764
0
    *ulo=*uhi;
6765
0
    *uhi=temp;
6766
0
    }
6767
0
  return;
6768
0
  } // decReverse
6769
6770
/* ------------------------------------------------------------------ */
6771
/* decShiftToMost -- shift digits in array towards most significant   */
6772
/*                                                                    */
6773
/*   uar    is the array                                              */
6774
/*   digits is the count of digits in use in the array                */
6775
/*   shift  is the number of zeros to pad with (least significant);   */
6776
/*     it must be zero or positive                                    */
6777
/*                                                                    */
6778
/*   returns the new length of the integer in the array, in digits    */
6779
/*                                                                    */
6780
/* No overflow is permitted (that is, the uar array must be known to  */
6781
/* be large enough to hold the result, after shifting).               */
6782
/* ------------------------------------------------------------------ */
6783
41
static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6784
41
  Unit  *target, *source, *first;  // work
6785
41
  Int   cut;                       // odd 0's to add
6786
41
  uInt  next;                      // work
6787
6788
41
  if (shift==0) return digits;     // [fastpath] nothing to do
6789
41
  if ((digits+shift)<=DECDPUN) {   // [fastpath] single-unit case
6790
2
    *uar=(Unit)(*uar*powers[shift]);
6791
2
    return digits+shift;
6792
2
    }
6793
6794
39
  next=0;                          // all paths
6795
39
  source=uar+D2U(digits)-1;        // where msu comes from
6796
39
  target=source+D2U(shift);        // where upper part of first cut goes
6797
39
  cut=DECDPUN-MSUDIGITS(shift);    // where to slice
6798
39
  if (cut==0) {                    // unit-boundary case
6799
0
    for (; source>=uar; source--, target--) *target=*source;
6800
0
    }
6801
39
   else {
6802
39
    first=uar+D2U(digits+shift)-1; // where msu of source will end up
6803
406
    for (; source>=uar; source--, target--) {
6804
      // split the source Unit and accumulate remainder for next
6805
367
      #if DECDPUN<=4
6806
367
        uInt quot=QUOT10(*source, cut);
6807
367
        uInt rem=*source-quot*powers[cut];
6808
367
        next+=quot;
6809
      #else
6810
        uInt rem=*source%powers[cut];
6811
        next+=*source/powers[cut];
6812
      #endif
6813
367
      if (target<=first) *target=(Unit)next;   // write to target iff valid
6814
367
      next=rem*powers[DECDPUN-cut];            // save remainder for next Unit
6815
367
      }
6816
39
    } // shift-move
6817
6818
  // propagate any partial unit to one below and clear the rest
6819
78
  for (; target>=uar; target--) {
6820
39
    *target=(Unit)next;
6821
39
    next=0;
6822
39
    }
6823
39
  return digits+shift;
6824
41
  } // decShiftToMost
6825
6826
/* ------------------------------------------------------------------ */
6827
/* decShiftToLeast -- shift digits in array towards least significant */
6828
/*                                                                    */
6829
/*   uar   is the array                                               */
6830
/*   units is length of the array, in units                           */
6831
/*   shift is the number of digits to remove from the lsu end; it     */
6832
/*     must be zero or positive and <= than units*DECDPUN.            */
6833
/*                                                                    */
6834
/*   returns the new length of the integer in the array, in units     */
6835
/*                                                                    */
6836
/* Removed digits are discarded (lost).  Units not required to hold   */
6837
/* the final result are unchanged.                                    */
6838
/* ------------------------------------------------------------------ */
6839
0
static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6840
0
  Unit  *target, *up;              // work
6841
0
  Int   cut, count;                // work
6842
0
  Int   quot, rem;                 // for division
6843
6844
0
  if (shift==0) return units;      // [fastpath] nothing to do
6845
0
  if (shift==units*DECDPUN) {      // [fastpath] little to do
6846
0
    *uar=0;                        // all digits cleared gives zero
6847
0
    return 1;                      // leaves just the one
6848
0
    }
6849
6850
0
  target=uar;                      // both paths
6851
0
  cut=MSUDIGITS(shift);
6852
0
  if (cut==DECDPUN) {              // unit-boundary case; easy
6853
0
    up=uar+D2U(shift);
6854
0
    for (; up<uar+units; target++, up++) *target=*up;
6855
0
    return target-uar;
6856
0
    }
6857
6858
  // messier
6859
0
  up=uar+D2U(shift-cut);           // source; correct to whole Units
6860
0
  count=units*DECDPUN-shift;       // the maximum new length
6861
0
  #if DECDPUN<=4
6862
0
    quot=QUOT10(*up, cut);
6863
  #else
6864
    quot=*up/powers[cut];
6865
  #endif
6866
0
  for (; ; target++) {
6867
0
    *target=(Unit)quot;
6868
0
    count-=(DECDPUN-cut);
6869
0
    if (count<=0) break;
6870
0
    up++;
6871
0
    quot=*up;
6872
0
    #if DECDPUN<=4
6873
0
      quot=QUOT10(quot, cut);
6874
0
      rem=*up-quot*powers[cut];
6875
    #else
6876
      rem=quot%powers[cut];
6877
      quot=quot/powers[cut];
6878
    #endif
6879
0
    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6880
0
    count-=cut;
6881
0
    if (count<=0) break;
6882
0
    }
6883
0
  return target-uar+1;
6884
0
  } // decShiftToLeast
6885
6886
#if DECSUBSET
6887
/* ------------------------------------------------------------------ */
6888
/* decRoundOperand -- round an operand  [used for subset only]        */
6889
/*                                                                    */
6890
/*   dn is the number to round (dn->digits is > set->digits)          */
6891
/*   set is the relevant context                                      */
6892
/*   status is the status accumulator                                 */
6893
/*                                                                    */
6894
/*   returns an allocated decNumber with the rounded result.          */
6895
/*                                                                    */
6896
/* lostDigits and other status may be set by this.                    */
6897
/*                                                                    */
6898
/* Since the input is an operand, it must not be modified.            */
6899
/* Instead, return an allocated decNumber, rounded as required.       */
6900
/* It is the caller's responsibility to free the allocated storage.   */
6901
/*                                                                    */
6902
/* If no storage is available then the result cannot be used, so NULL */
6903
/* is returned.                                                       */
6904
/* ------------------------------------------------------------------ */
6905
static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6906
                                  uInt *status) {
6907
  decNumber *res;                       // result structure
6908
  uInt newstatus=0;                     // status from round
6909
  Int  residue=0;                       // rounding accumulator
6910
6911
  // Allocate storage for the returned decNumber, big enough for the
6912
  // length specified by the context
6913
  res=(decNumber *)malloc(sizeof(decNumber)
6914
                          +(D2U(set->digits)-1)*sizeof(Unit));
6915
  if (res==NULL) {
6916
    *status|=DEC_Insufficient_storage;
6917
    return NULL;
6918
    }
6919
  decCopyFit(res, dn, set, &residue, &newstatus);
6920
  decApplyRound(res, set, residue, &newstatus);
6921
6922
  // If that set Inexact then "lost digits" is raised...
6923
  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6924
  *status|=newstatus;
6925
  return res;
6926
  } // decRoundOperand
6927
#endif
6928
6929
/* ------------------------------------------------------------------ */
6930
/* decCopyFit -- copy a number, truncating the coefficient if needed  */
6931
/*                                                                    */
6932
/*   dest is the target decNumber                                     */
6933
/*   src  is the source decNumber                                     */
6934
/*   set is the context [used for length (digits) and rounding mode]  */
6935
/*   residue is the residue accumulator                               */
6936
/*   status contains the current status to be updated                 */
6937
/*                                                                    */
6938
/* (dest==src is allowed and will be a no-op if fits)                 */
6939
/* All fields are updated as required.                                */
6940
/* ------------------------------------------------------------------ */
6941
static void decCopyFit(decNumber *dest, const decNumber *src,
6942
1.87k
                       decContext *set, Int *residue, uInt *status) {
6943
1.87k
  dest->bits=src->bits;
6944
1.87k
  dest->exponent=src->exponent;
6945
1.87k
  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6946
1.87k
  } // decCopyFit
6947
6948
/* ------------------------------------------------------------------ */
6949
/* decSetCoeff -- set the coefficient of a number                     */
6950
/*                                                                    */
6951
/*   dn    is the number whose coefficient array is to be set.        */
6952
/*         It must have space for set->digits digits                  */
6953
/*   set   is the context [for size]                                  */
6954
/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6955
/*   len   is digits in the source coefficient [may be dn->digits]    */
6956
/*   residue is the residue accumulator.  This has values as in       */
6957
/*         decApplyRound, and will be unchanged unless the            */
6958
/*         target size is less than len.  In this case, the           */
6959
/*         coefficient is truncated and the residue is updated to     */
6960
/*         reflect the previous residue and the dropped digits.       */
6961
/*   status is the status accumulator, as usual                       */
6962
/*                                                                    */
6963
/* The coefficient may already be in the number, or it can be an      */
6964
/* external intermediate array.  If it is in the number, lsu must ==  */
6965
/* dn->lsu and len must == dn->digits.                                */
6966
/*                                                                    */
6967
/* Note that the coefficient length (len) may be < set->digits, and   */
6968
/* in this case this merely copies the coefficient (or is a no-op     */
6969
/* if dn->lsu==lsu).                                                  */
6970
/*                                                                    */
6971
/* Note also that (only internally, from decQuantizeOp and            */
6972
/* decSetSubnormal) the value of set->digits may be less than one,    */
6973
/* indicating a round to left.  This routine handles that case        */
6974
/* correctly; caller ensures space.                                   */
6975
/*                                                                    */
6976
/* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6977
/* updated as necessary.   dn->bits (sign) is unchanged.              */
6978
/*                                                                    */
6979
/* DEC_Rounded status is set if any digits are discarded.             */
6980
/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6981
/*                       incoming residue was non-0 (implies rounded) */
6982
/* ------------------------------------------------------------------ */
6983
// mapping array: maps 0-9 to canonical residues, so that a residue
6984
// can be adjusted in the range [-1, +1] and achieve correct rounding
6985
//                             0  1  2  3  4  5  6  7  8  9
6986
static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6987
static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6988
5.74k
                        Int len, Int *residue, uInt *status) {
6989
5.74k
  Int   discard;              // number of digits to discard
6990
5.74k
  uInt  cut;                  // cut point in Unit
6991
5.74k
  const Unit *up;             // work
6992
5.74k
  Unit  *target;              // ..
6993
5.74k
  Int   count;                // ..
6994
5.74k
  #if DECDPUN<=4
6995
5.74k
  uInt  temp;                 // ..
6996
5.74k
  #endif
6997
6998
5.74k
  discard=len-set->digits;    // digits to discard
6999
5.74k
  if (discard<=0) {           // no digits are being discarded
7000
1.87k
    if (dn->lsu!=lsu) {       // copy needed
7001
      // copy the coefficient array to the result number; no shift needed
7002
1.87k
      count=len;              // avoids D2U
7003
1.87k
      up=lsu;
7004
26.3k
      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
7005
24.4k
        *target=*up;
7006
1.87k
      dn->digits=len;         // set the new length
7007
1.87k
      }
7008
    // dn->exponent and residue are unchanged, record any inexactitude
7009
1.87k
    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
7010
1.87k
    return;
7011
1.87k
    }
7012
7013
  // some digits must be discarded ...
7014
3.86k
  dn->exponent+=discard;      // maintain numerical value
7015
3.86k
  *status|=DEC_Rounded;       // accumulate Rounded status
7016
3.86k
  if (*residue>1) *residue=1; // previous residue now to right, so reduce
7017
7018
3.86k
  if (discard>len) {          // everything, +1, is being discarded
7019
    // guard digit is 0
7020
    // residue is all the number [NB could be all 0s]
7021
82
    if (*residue<=0) {        // not already positive
7022
79
      count=len;              // avoids D2U
7023
136
      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0
7024
79
        *residue=1;
7025
79
        break;                // no need to check any others
7026
79
        }
7027
79
      }
7028
82
    if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
7029
82
    *dn->lsu=0;               // coefficient will now be 0
7030
82
    dn->digits=1;             // ..
7031
82
    return;
7032
82
    } // total discard
7033
7034
  // partial discard [most common case]
7035
  // here, at least the first (most significant) discarded digit exists
7036
7037
  // spin up the number, noting residue during the spin, until get to
7038
  // the Unit with the first discarded digit.  When reach it, extract
7039
  // it and remember its position
7040
3.78k
  count=0;
7041
3.34M
  for (up=lsu;; up++) {
7042
3.34M
    count+=DECDPUN;
7043
3.34M
    if (count>=discard) break; // full ones all checked
7044
3.34M
    if (*up!=0) *residue=1;
7045
3.34M
    } // up
7046
7047
  // here up -> Unit with first discarded digit
7048
3.78k
  cut=discard-(count-DECDPUN)-1;
7049
3.78k
  if (cut==DECDPUN-1) {       // unit-boundary case (fast)
7050
2.08k
    Unit half=(Unit)powers[DECDPUN]>>1;
7051
    // set residue directly
7052
2.08k
    if (*up>=half) {
7053
1.22k
      if (*up>half) *residue=7;
7054
306
      else *residue+=5;       // add sticky bit
7055
1.22k
      }
7056
861
     else { // <half
7057
861
      if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]
7058
861
      }
7059
2.08k
    if (set->digits<=0) {     // special for Quantize/Subnormal :-(
7060
23
      *dn->lsu=0;             // .. result is 0
7061
23
      dn->digits=1;           // ..
7062
23
      }
7063
2.06k
     else {                   // shift to least
7064
2.06k
      count=set->digits;      // now digits to end up with
7065
2.06k
      dn->digits=count;       // set the new length
7066
2.06k
      up++;                   // move to next
7067
      // on unit boundary, so shift-down copy loop is simple
7068
55.5k
      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
7069
53.4k
        *target=*up;
7070
2.06k
      }
7071
2.08k
    } // unit-boundary case
7072
7073
1.69k
   else { // discard digit is in low digit(s), and not top digit
7074
1.69k
    uInt  discard1;                // first discarded digit
7075
1.69k
    uInt  quot, rem;               // for divisions
7076
1.69k
    if (cut==0) quot=*up;          // is at bottom of unit
7077
613
     else /* cut>0 */ {            // it's not at bottom of unit
7078
613
      #if DECDPUN<=4
7079
613
        quot=QUOT10(*up, cut);
7080
613
        rem=*up-quot*powers[cut];
7081
      #else
7082
        rem=*up%powers[cut];
7083
        quot=*up/powers[cut];
7084
      #endif
7085
613
      if (rem!=0) *residue=1;
7086
613
      }
7087
    // discard digit is now at bottom of quot
7088
1.69k
    #if DECDPUN<=4
7089
1.69k
      temp=(quot*6554)>>16;        // fast /10
7090
      // Vowels algorithm here not a win (9 instructions)
7091
1.69k
      discard1=quot-X10(temp);
7092
1.69k
      quot=temp;
7093
    #else
7094
      discard1=quot%10;
7095
      quot=quot/10;
7096
    #endif
7097
    // here, discard1 is the guard digit, and residue is everything
7098
    // else [use mapping array to accumulate residue safely]
7099
1.69k
    *residue+=resmap[discard1];
7100
1.69k
    cut++;                         // update cut
7101
    // here: up -> Unit of the array with bottom digit
7102
    //       cut is the division point for each Unit
7103
    //       quot holds the uncut high-order digits for the current unit
7104
1.69k
    if (set->digits<=0) {          // special for Quantize/Subnormal :-(
7105
33
      *dn->lsu=0;                  // .. result is 0
7106
33
      dn->digits=1;                // ..
7107
33
      }
7108
1.66k
     else {                        // shift to least needed
7109
1.66k
      count=set->digits;           // now digits to end up with
7110
1.66k
      dn->digits=count;            // set the new length
7111
      // shift-copy the coefficient array to the result number
7112
41.0k
      for (target=dn->lsu; ; target++) {
7113
41.0k
        *target=(Unit)quot;
7114
41.0k
        count-=(DECDPUN-cut);
7115
41.0k
        if (count<=0) break;
7116
39.3k
        up++;
7117
39.3k
        quot=*up;
7118
39.3k
        #if DECDPUN<=4
7119
39.3k
          quot=QUOT10(quot, cut);
7120
39.3k
          rem=*up-quot*powers[cut];
7121
        #else
7122
          rem=quot%powers[cut];
7123
          quot=quot/powers[cut];
7124
        #endif
7125
39.3k
        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7126
39.3k
        count-=cut;
7127
39.3k
        if (count<=0) break;
7128
39.3k
        } // shift-copy loop
7129
1.66k
      } // shift to least
7130
1.69k
    } // not unit boundary
7131
7132
3.78k
  if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
7133
3.78k
  return;
7134
3.86k
  } // decSetCoeff
7135
7136
/* ------------------------------------------------------------------ */
7137
/* decApplyRound -- apply pending rounding to a number                */
7138
/*                                                                    */
7139
/*   dn    is the number, with space for set->digits digits           */
7140
/*   set   is the context [for size and rounding mode]                */
7141
/*   residue indicates pending rounding, being any accumulated        */
7142
/*         guard and sticky information.  It may be:                  */
7143
/*         6-9: rounding digit is >5                                  */
7144
/*         5:   rounding digit is exactly half-way                    */
7145
/*         1-4: rounding digit is <5 and >0                           */
7146
/*         0:   the coefficient is exact                              */
7147
/*        -1:   as 1, but the hidden digits are subtractive, that     */
7148
/*              is, of the opposite sign to dn.  In this case the     */
7149
/*              coefficient must be non-0.  This case occurs when     */
7150
/*              subtracting a small number (which can be reduced to   */
7151
/*              a sticky bit); see decAddOp.                          */
7152
/*   status is the status accumulator, as usual                       */
7153
/*                                                                    */
7154
/* This routine applies rounding while keeping the length of the      */
7155
/* coefficient constant.  The exponent and status are unchanged       */
7156
/* except if:                                                         */
7157
/*                                                                    */
7158
/*   -- the coefficient was increased and is all nines (in which      */
7159
/*      case Overflow could occur, and is handled directly here so    */
7160
/*      the caller does not need to re-test for overflow)             */
7161
/*                                                                    */
7162
/*   -- the coefficient was decreased and becomes all nines (in which */
7163
/*      case Underflow could occur, and is also handled directly).    */
7164
/*                                                                    */
7165
/* All fields in dn are updated as required.                          */
7166
/*                                                                    */
7167
/* ------------------------------------------------------------------ */
7168
static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7169
2.99k
                          uInt *status) {
7170
2.99k
  Int  bump;                  // 1 if coefficient needs to be incremented
7171
                              // -1 if coefficient needs to be decremented
7172
7173
2.99k
  if (residue==0) return;     // nothing to apply
7174
7175
2.98k
  bump=0;                     // assume a smooth ride
7176
7177
  // now decide whether, and how, to round, depending on mode
7178
2.98k
  switch (set->round) {
7179
0
    case DEC_ROUND_05UP: {    // round zero or five up (for reround)
7180
      // This is the same as DEC_ROUND_DOWN unless there is a
7181
      // positive residue and the lsd of dn is 0 or 5, in which case
7182
      // it is bumped; when residue is <0, the number is therefore
7183
      // bumped down unless the final digit was 1 or 6 (in which
7184
      // case it is bumped down and then up -- a no-op)
7185
0
      Int lsd5=*dn->lsu%5;     // get lsd and quintate
7186
0
      if (residue<0 && lsd5!=1) bump=-1;
7187
0
       else if (residue>0 && lsd5==0) bump=1;
7188
      // [bump==1 could be applied directly; use common path for clarity]
7189
0
      break;} // r-05
7190
7191
0
    case DEC_ROUND_DOWN: {
7192
      // no change, except if negative residue
7193
0
      if (residue<0) bump=-1;
7194
0
      break;} // r-d
7195
7196
0
    case DEC_ROUND_HALF_DOWN: {
7197
0
      if (residue>5) bump=1;
7198
0
      break;} // r-h-d
7199
7200
0
    case DEC_ROUND_HALF_EVEN: {
7201
0
      if (residue>5) bump=1;            // >0.5 goes up
7202
0
       else if (residue==5) {           // exactly 0.5000...
7203
        // 0.5 goes up iff [new] lsd is odd
7204
0
        if (*dn->lsu & 0x01) bump=1;
7205
0
        }
7206
0
      break;} // r-h-e
7207
7208
2.98k
    case DEC_ROUND_HALF_UP: {
7209
2.98k
      if (residue>=5) bump=1;
7210
2.98k
      break;} // r-h-u
7211
7212
0
    case DEC_ROUND_UP: {
7213
0
      if (residue>0) bump=1;
7214
0
      break;} // r-u
7215
7216
0
    case DEC_ROUND_CEILING: {
7217
      // same as _UP for positive numbers, and as _DOWN for negatives
7218
      // [negative residue cannot occur on 0]
7219
0
      if (decNumberIsNegative(dn)) {
7220
0
        if (residue<0) bump=-1;
7221
0
        }
7222
0
       else {
7223
0
        if (residue>0) bump=1;
7224
0
        }
7225
0
      break;} // r-c
7226
7227
0
    case DEC_ROUND_FLOOR: {
7228
      // same as _UP for negative numbers, and as _DOWN for positive
7229
      // [negative residue cannot occur on 0]
7230
0
      if (!decNumberIsNegative(dn)) {
7231
0
        if (residue<0) bump=-1;
7232
0
        }
7233
0
       else {
7234
0
        if (residue>0) bump=1;
7235
0
        }
7236
0
      break;} // r-f
7237
7238
0
    default: {      // e.g., DEC_ROUND_MAX
7239
0
      *status|=DEC_Invalid_context;
7240
      #if DECTRACE || (DECCHECK && DECVERB)
7241
      printf("Unknown rounding mode: %d\n", set->round);
7242
      #endif
7243
0
      break;}
7244
2.98k
    } // switch
7245
7246
  // now bump the number, up or down, if need be
7247
2.98k
  if (bump==0) return;                       // no action required
7248
7249
  // Simply use decUnitAddSub unless bumping up and the number is
7250
  // all nines.  In this special case set to 100... explicitly
7251
  // and adjust the exponent by one (as otherwise could overflow
7252
  // the array)
7253
  // Similarly handle all-nines result if bumping down.
7254
2.39k
  if (bump>0) {
7255
2.39k
    Unit *up;                                // work
7256
2.39k
    uInt count=dn->digits;                   // digits to be checked
7257
4.99k
    for (up=dn->lsu; ; up++) {
7258
4.99k
      if (count<=DECDPUN) {
7259
        // this is the last Unit (the msu)
7260
167
        if (*up!=powers[count]-1) break;     // not still 9s
7261
        // here if it, too, is all nines
7262
99
        *up=(Unit)powers[count-1];           // here 999 -> 100 etc.
7263
1.87k
        for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0
7264
99
        dn->exponent++;                      // and bump exponent
7265
        // [which, very rarely, could cause Overflow...]
7266
99
        if ((dn->exponent+dn->digits)>set->emax+1) {
7267
32
          decSetOverflow(dn, set, status);
7268
32
          }
7269
99
        return;                              // done
7270
167
        }
7271
      // a full unit to check, with more to come
7272
4.82k
      if (*up!=DECDPUNMAX) break;            // not still 9s
7273
2.60k
      count-=DECDPUN;
7274
2.60k
      } // up
7275
2.39k
    } // bump>0
7276
0
   else {                                    // -1
7277
    // here checking for a pre-bump of 1000... (leading 1, all
7278
    // other digits zero)
7279
0
    Unit *up, *sup;                          // work
7280
0
    uInt count=dn->digits;                   // digits to be checked
7281
0
    for (up=dn->lsu; ; up++) {
7282
0
      if (count<=DECDPUN) {
7283
        // this is the last Unit (the msu)
7284
0
        if (*up!=powers[count-1]) break;     // not 100..
7285
        // here if have the 1000... case
7286
0
        sup=up;                              // save msu pointer
7287
0
        *up=(Unit)powers[count]-1;           // here 100 in msu -> 999
7288
        // others all to all-nines, too
7289
0
        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7290
0
        dn->exponent--;                      // and bump exponent
7291
7292
        // iff the number was at the subnormal boundary (exponent=etiny)
7293
        // then the exponent is now out of range, so it will in fact get
7294
        // clamped to etiny and the final 9 dropped.
7295
        // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,
7296
        //        dn->exponent, set->digits);
7297
0
        if (dn->exponent+1==set->emin-set->digits+1) {
7298
0
          if (count==1 && dn->digits==1) *sup=0;  // here 9 -> 0[.9]
7299
0
           else {
7300
0
            *sup=(Unit)powers[count-1]-1;    // here 999.. in msu -> 99..
7301
0
            dn->digits--;
7302
0
            }
7303
0
          dn->exponent++;
7304
0
          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7305
0
          }
7306
0
        return;                              // done
7307
0
        }
7308
7309
      // a full unit to check, with more to come
7310
0
      if (*up!=0) break;                     // not still 0s
7311
0
      count-=DECDPUN;
7312
0
      } // up
7313
7314
0
    } // bump<0
7315
7316
  // Actual bump needed.  Do it.
7317
2.29k
  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7318
2.29k
  } // decApplyRound
7319
7320
#if DECSUBSET
7321
/* ------------------------------------------------------------------ */
7322
/* decFinish -- finish processing a number                            */
7323
/*                                                                    */
7324
/*   dn is the number                                                 */
7325
/*   set is the context                                               */
7326
/*   residue is the rounding accumulator (as in decApplyRound)        */
7327
/*   status is the accumulator                                        */
7328
/*                                                                    */
7329
/* This finishes off the current number by:                           */
7330
/*    1. If not extended:                                             */
7331
/*       a. Converting a zero result to clean '0'                     */
7332
/*       b. Reducing positive exponents to 0, if would fit in digits  */
7333
/*    2. Checking for overflow and subnormals (always)                */
7334
/* Note this is just Finalize when no subset arithmetic.              */
7335
/* All fields are updated as required.                                */
7336
/* ------------------------------------------------------------------ */
7337
static void decFinish(decNumber *dn, decContext *set, Int *residue,
7338
                      uInt *status) {
7339
  if (!set->extended) {
7340
    if ISZERO(dn) {                // value is zero
7341
      dn->exponent=0;              // clean exponent ..
7342
      dn->bits=0;                  // .. and sign
7343
      return;                      // no error possible
7344
      }
7345
    if (dn->exponent>=0) {         // non-negative exponent
7346
      // >0; reduce to integer if possible
7347
      if (set->digits >= (dn->exponent+dn->digits)) {
7348
        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7349
        dn->exponent=0;
7350
        }
7351
      }
7352
    } // !extended
7353
7354
  decFinalize(dn, set, residue, status);
7355
  } // decFinish
7356
#endif
7357
7358
/* ------------------------------------------------------------------ */
7359
/* decFinalize -- final check, clamp, and round of a number           */
7360
/*                                                                    */
7361
/*   dn is the number                                                 */
7362
/*   set is the context                                               */
7363
/*   residue is the rounding accumulator (as in decApplyRound)        */
7364
/*   status is the status accumulator                                 */
7365
/*                                                                    */
7366
/* This finishes off the current number by checking for subnormal     */
7367
/* results, applying any pending rounding, checking for overflow,     */
7368
/* and applying any clamping.                                         */
7369
/* Underflow and overflow conditions are raised as appropriate.       */
7370
/* All fields are updated as required.                                */
7371
/* ------------------------------------------------------------------ */
7372
static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7373
5.87k
                        uInt *status) {
7374
5.87k
  Int shift;                            // shift needed if clamping
7375
5.87k
  Int tinyexp=set->emin-dn->digits+1;   // precalculate subnormal boundary
7376
7377
  // Must be careful, here, when checking the exponent as the
7378
  // adjusted exponent could overflow 31 bits [because it may already
7379
  // be up to twice the expected].
7380
7381
  // First test for subnormal.  This must be done before any final
7382
  // round as the result could be rounded to Nmin or 0.
7383
5.87k
  if (dn->exponent<=tinyexp) {          // prefilter
7384
335
    Int comp;
7385
335
    decNumber nmin;
7386
    // A very nasty case here is dn == Nmin and residue<0
7387
335
    if (dn->exponent<tinyexp) {
7388
      // Go handle subnormals; this will apply round if needed.
7389
317
      decSetSubnormal(dn, set, residue, status);
7390
317
      return;
7391
317
      }
7392
    // Equals case: only subnormal if dn=Nmin and negative residue
7393
18
    decNumberZero(&nmin);
7394
18
    nmin.lsu[0]=1;
7395
18
    nmin.exponent=set->emin;
7396
18
    comp=decCompare(dn, &nmin, 1);                // (signless compare)
7397
18
    if (comp==BADINT) {                           // oops
7398
0
      *status|=DEC_Insufficient_storage;          // abandon...
7399
0
      return;
7400
0
      }
7401
18
    if (*residue<0 && comp==0) {                  // neg residue and dn==Nmin
7402
0
      decApplyRound(dn, set, *residue, status);   // might force down
7403
0
      decSetSubnormal(dn, set, residue, status);
7404
0
      return;
7405
0
      }
7406
18
    }
7407
7408
  // now apply any pending round (this could raise overflow).
7409
5.55k
  if (*residue!=0) decApplyRound(dn, set, *residue, status);
7410
7411
  // Check for overflow [redundant in the 'rare' case] or clamp
7412
5.55k
  if (dn->exponent<=set->emax-set->digits+1) return;   // neither needed
7413
7414
7415
  // here when might have an overflow or clamp to do
7416
103
  if (dn->exponent>set->emax-dn->digits+1) {           // too big
7417
89
    decSetOverflow(dn, set, status);
7418
89
    return;
7419
89
    }
7420
  // here when the result is normal but in clamp range
7421
14
  if (!set->clamp) return;
7422
7423
  // here when need to apply the IEEE exponent clamp (fold-down)
7424
0
  shift=dn->exponent-(set->emax-set->digits+1);
7425
7426
  // shift coefficient (if non-zero)
7427
0
  if (!ISZERO(dn)) {
7428
0
    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7429
0
    }
7430
0
  dn->exponent-=shift;   // adjust the exponent to match
7431
0
  *status|=DEC_Clamped;  // and record the dirty deed
7432
0
  return;
7433
14
  } // decFinalize
7434
7435
/* ------------------------------------------------------------------ */
7436
/* decSetOverflow -- set number to proper overflow value              */
7437
/*                                                                    */
7438
/*   dn is the number (used for sign [only] and result)               */
7439
/*   set is the context [used for the rounding mode, etc.]            */
7440
/*   status contains the current status to be updated                 */
7441
/*                                                                    */
7442
/* This sets the sign of a number and sets its value to either        */
7443
/* Infinity or the maximum finite value, depending on the sign of     */
7444
/* dn and the rounding mode, following IEEE 754 rules.                */
7445
/* ------------------------------------------------------------------ */
7446
121
static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7447
121
  Flag needmax=0;                  // result is maximum finite value
7448
121
  uByte sign=dn->bits&DECNEG;      // clean and save sign bit
7449
7450
121
  if (ISZERO(dn)) {                // zero does not overflow magnitude
7451
59
    Int emax=set->emax;                      // limit value
7452
59
    if (set->clamp) emax-=set->digits-1;     // lower if clamping
7453
59
    if (dn->exponent>emax) {                 // clamp required
7454
59
      dn->exponent=emax;
7455
59
      *status|=DEC_Clamped;
7456
59
      }
7457
59
    return;
7458
59
    }
7459
7460
62
  decNumberZero(dn);
7461
62
  switch (set->round) {
7462
0
    case DEC_ROUND_DOWN: {
7463
0
      needmax=1;                   // never Infinity
7464
0
      break;} // r-d
7465
0
    case DEC_ROUND_05UP: {
7466
0
      needmax=1;                   // never Infinity
7467
0
      break;} // r-05
7468
0
    case DEC_ROUND_CEILING: {
7469
0
      if (sign) needmax=1;         // Infinity if non-negative
7470
0
      break;} // r-c
7471
0
    case DEC_ROUND_FLOOR: {
7472
0
      if (!sign) needmax=1;        // Infinity if negative
7473
0
      break;} // r-f
7474
62
    default: break;                // Infinity in all other cases
7475
62
    }
7476
62
  if (needmax) {
7477
0
    decSetMaxValue(dn, set);
7478
0
    dn->bits=sign;                 // set sign
7479
0
    }
7480
62
   else dn->bits=sign|DECINF;      // Value is +/-Infinity
7481
62
  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7482
62
  } // decSetOverflow
7483
7484
/* ------------------------------------------------------------------ */
7485
/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7486
/*                                                                    */
7487
/*   dn is the number to set                                          */
7488
/*   set is the context [used for digits and emax]                    */
7489
/*                                                                    */
7490
/* This sets the number to the maximum positive value.                */
7491
/* ------------------------------------------------------------------ */
7492
0
static void decSetMaxValue(decNumber *dn, decContext *set) {
7493
0
  Unit *up;                        // work
7494
0
  Int count=set->digits;           // nines to add
7495
0
  dn->digits=count;
7496
  // fill in all nines to set maximum value
7497
0
  for (up=dn->lsu; ; up++) {
7498
0
    if (count>DECDPUN) *up=DECDPUNMAX;  // unit full o'nines
7499
0
     else {                             // this is the msu
7500
0
      *up=(Unit)(powers[count]-1);
7501
0
      break;
7502
0
      }
7503
0
    count-=DECDPUN;                // filled those digits
7504
0
    } // up
7505
0
  dn->bits=0;                      // + sign
7506
0
  dn->exponent=set->emax-set->digits+1;
7507
0
  } // decSetMaxValue
7508
7509
/* ------------------------------------------------------------------ */
7510
/* decSetSubnormal -- process value whose exponent is <Emin           */
7511
/*                                                                    */
7512
/*   dn is the number (used as input as well as output; it may have   */
7513
/*         an allowed subnormal value, which may need to be rounded)  */
7514
/*   set is the context [used for the rounding mode]                  */
7515
/*   residue is any pending residue                                   */
7516
/*   status contains the current status to be updated                 */
7517
/*                                                                    */
7518
/* If subset mode, set result to zero and set Underflow flags.        */
7519
/*                                                                    */
7520
/* Value may be zero with a low exponent; this does not set Subnormal */
7521
/* but the exponent will be clamped to Etiny.                         */
7522
/*                                                                    */
7523
/* Otherwise ensure exponent is not out of range, and round as        */
7524
/* necessary.  Underflow is set if the result is Inexact.             */
7525
/* ------------------------------------------------------------------ */
7526
static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7527
317
                            uInt *status) {
7528
317
  decContext workset;         // work
7529
317
  Int        etiny, adjust;   // ..
7530
7531
  #if DECSUBSET
7532
  // simple set to zero and 'hard underflow' for subset
7533
  if (!set->extended) {
7534
    decNumberZero(dn);
7535
    // always full overflow
7536
    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7537
    return;
7538
    }
7539
  #endif
7540
7541
  // Full arithmetic -- allow subnormals, rounded to minimum exponent
7542
  // (Etiny) if needed
7543
317
  etiny=set->emin-(set->digits-1);      // smallest allowed exponent
7544
7545
317
  if ISZERO(dn) {                       // value is zero
7546
    // residue can never be non-zero here
7547
    #if DECCHECK
7548
      if (*residue!=0) {
7549
        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7550
        *status|=DEC_Invalid_operation;
7551
        }
7552
    #endif
7553
38
    if (dn->exponent<etiny) {           // clamp required
7554
30
      dn->exponent=etiny;
7555
30
      *status|=DEC_Clamped;
7556
30
      }
7557
38
    return;
7558
38
    }
7559
7560
279
  *status|=DEC_Subnormal;               // have a non-zero subnormal
7561
279
  adjust=etiny-dn->exponent;            // calculate digits to remove
7562
279
  if (adjust<=0) {                      // not out of range; unrounded
7563
    // residue can never be non-zero here, except in the Nmin-residue
7564
    // case (which is a subnormal result), so can take fast-path here
7565
    // it may already be inexact (from setting the coefficient)
7566
10
    if (*status&DEC_Inexact) *status|=DEC_Underflow;
7567
10
    return;
7568
10
    }
7569
7570
  // adjust>0, so need to rescale the result so exponent becomes Etiny
7571
  // [this code is similar to that in rescale]
7572
269
  workset=*set;                         // clone rounding, etc.
7573
269
  workset.digits=dn->digits-adjust;     // set requested length
7574
269
  workset.emin-=adjust;                 // and adjust emin to match
7575
  // [note that the latter can be <1, here, similar to Rescale case]
7576
269
  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7577
269
  decApplyRound(dn, &workset, *residue, status);
7578
7579
  // Use 754 default rule: Underflow is set iff Inexact
7580
  // [independent of whether trapped]
7581
269
  if (*status&DEC_Inexact) *status|=DEC_Underflow;
7582
7583
  // if rounded up a 999s case, exponent will be off by one; adjust
7584
  // back if so [it will fit, because it was shortened earlier]
7585
269
  if (dn->exponent>etiny) {
7586
41
    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7587
41
    dn->exponent--;                     // (re)adjust the exponent.
7588
41
    }
7589
7590
  // if rounded to zero, it is by definition clamped...
7591
269
  if (ISZERO(dn)) *status|=DEC_Clamped;
7592
269
  } // decSetSubnormal
7593
7594
/* ------------------------------------------------------------------ */
7595
/* decCheckMath - check entry conditions for a math function          */
7596
/*                                                                    */
7597
/*   This checks the context and the operand                          */
7598
/*                                                                    */
7599
/*   rhs is the operand to check                                      */
7600
/*   set is the context to check                                      */
7601
/*   status is unchanged if both are good                             */
7602
/*                                                                    */
7603
/* returns non-zero if status is changed, 0 otherwise                 */
7604
/*                                                                    */
7605
/* Restrictions enforced:                                             */
7606
/*                                                                    */
7607
/*   digits, emax, and -emin in the context must be less than         */
7608
/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7609
/*   non-zero.  Invalid_operation is set in the status if a           */
7610
/*   restriction is violated.                                         */
7611
/* ------------------------------------------------------------------ */
7612
static uInt decCheckMath(const decNumber *rhs, decContext *set,
7613
0
                         uInt *status) {
7614
0
  uInt save=*status;                         // record
7615
0
  if (set->digits>DEC_MAX_MATH
7616
0
   || set->emax>DEC_MAX_MATH
7617
0
   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7618
0
   else if ((rhs->digits>DEC_MAX_MATH
7619
0
     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7620
0
     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7621
0
     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7622
0
  return (*status!=save);
7623
0
  } // decCheckMath
7624
7625
/* ------------------------------------------------------------------ */
7626
/* decGetInt -- get integer from a number                             */
7627
/*                                                                    */
7628
/*   dn is the number [which will not be altered]                     */
7629
/*                                                                    */
7630
/*   returns one of:                                                  */
7631
/*     BADINT if there is a non-zero fraction                         */
7632
/*     the converted integer                                          */
7633
/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7634
/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7635
/*                                                                    */
7636
/* This checks and gets a whole number from the input decNumber.      */
7637
/* The sign can be determined from dn by the caller when BIGEVEN or   */
7638
/* BIGODD is returned.                                                */
7639
/* ------------------------------------------------------------------ */
7640
0
static Int decGetInt(const decNumber *dn) {
7641
0
  Int  theInt;                          // result accumulator
7642
0
  const Unit *up;                       // work
7643
0
  Int  got;                             // digits (real or not) processed
7644
0
  Int  ilength=dn->digits+dn->exponent; // integral length
7645
0
  Flag neg=decNumberIsNegative(dn);     // 1 if -ve
7646
7647
  // The number must be an integer that fits in 10 digits
7648
  // Assert, here, that 10 is enough for any rescale Etiny
7649
  #if DEC_MAX_EMAX > 999999999
7650
    #error GetInt may need updating [for Emax]
7651
  #endif
7652
  #if DEC_MIN_EMIN < -999999999
7653
    #error GetInt may need updating [for Emin]
7654
  #endif
7655
0
  if (ISZERO(dn)) return 0;             // zeros are OK, with any exponent
7656
7657
0
  up=dn->lsu;                           // ready for lsu
7658
0
  theInt=0;                             // ready to accumulate
7659
0
  if (dn->exponent>=0) {                // relatively easy
7660
    // no fractional part [usual]; allow for positive exponent
7661
0
    got=dn->exponent;
7662
0
    }
7663
0
   else { // -ve exponent; some fractional part to check and discard
7664
0
    Int count=-dn->exponent;            // digits to discard
7665
    // spin up whole units until reach the Unit with the unit digit
7666
0
    for (; count>=DECDPUN; up++) {
7667
0
      if (*up!=0) return BADINT;        // non-zero Unit to discard
7668
0
      count-=DECDPUN;
7669
0
      }
7670
0
    if (count==0) got=0;                // [a multiple of DECDPUN]
7671
0
     else {                             // [not multiple of DECDPUN]
7672
0
      Int rem;                          // work
7673
      // slice off fraction digits and check for non-zero
7674
0
      #if DECDPUN<=4
7675
0
        theInt=QUOT10(*up, count);
7676
0
        rem=*up-theInt*powers[count];
7677
      #else
7678
        rem=*up%powers[count];          // slice off discards
7679
        theInt=*up/powers[count];
7680
      #endif
7681
0
      if (rem!=0) return BADINT;        // non-zero fraction
7682
      // it looks good
7683
0
      got=DECDPUN-count;                // number of digits so far
7684
0
      up++;                             // ready for next
7685
0
      }
7686
0
    }
7687
  // now it's known there's no fractional part
7688
7689
  // tricky code now, to accumulate up to 9.3 digits
7690
0
  if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there
7691
7692
0
  if (ilength<11) {
7693
0
    Int save=theInt;
7694
    // collect any remaining unit(s)
7695
0
    for (; got<ilength; up++) {
7696
0
      theInt+=*up*powers[got];
7697
0
      got+=DECDPUN;
7698
0
      }
7699
0
    if (ilength==10) {                  // need to check for wrap
7700
0
      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7701
         // [that test also disallows the BADINT result case]
7702
0
       else if (neg && theInt>1999999997) ilength=11;
7703
0
       else if (!neg && theInt>999999999) ilength=11;
7704
0
      if (ilength==11) theInt=save;     // restore correct low bit
7705
0
      }
7706
0
    }
7707
7708
0
  if (ilength>10) {                     // too big
7709
0
    if (theInt&1) return BIGODD;        // bottom bit 1
7710
0
    return BIGEVEN;                     // bottom bit 0
7711
0
    }
7712
7713
0
  if (neg) theInt=-theInt;              // apply sign
7714
0
  return theInt;
7715
0
  } // decGetInt
7716
7717
/* ------------------------------------------------------------------ */
7718
/* decDecap -- decapitate the coefficient of a number                 */
7719
/*                                                                    */
7720
/*   dn   is the number to be decapitated                             */
7721
/*   drop is the number of digits to be removed from the left of dn;  */
7722
/*     this must be <= dn->digits (if equal, the coefficient is       */
7723
/*     set to 0)                                                      */
7724
/*                                                                    */
7725
/* Returns dn; dn->digits will be <= the initial digits less drop     */
7726
/* (after removing drop digits there may be leading zero digits       */
7727
/* which will also be removed).  Only dn->lsu and dn->digits change.  */
7728
/* ------------------------------------------------------------------ */
7729
0
static decNumber *decDecap(decNumber *dn, Int drop) {
7730
0
  Unit *msu;                            // -> target cut point
7731
0
  Int cut;                              // work
7732
0
  if (drop>=dn->digits) {               // losing the whole thing
7733
    #if DECCHECK
7734
    if (drop>dn->digits)
7735
      printf("decDecap called with drop>digits [%ld>%ld]\n",
7736
             (LI)drop, (LI)dn->digits);
7737
    #endif
7738
0
    dn->lsu[0]=0;
7739
0
    dn->digits=1;
7740
0
    return dn;
7741
0
    }
7742
0
  msu=dn->lsu+D2U(dn->digits-drop)-1;   // -> likely msu
7743
0
  cut=MSUDIGITS(dn->digits-drop);       // digits to be in use in msu
7744
0
  if (cut!=DECDPUN) *msu%=powers[cut];  // clear left digits
7745
  // that may have left leading zero digits, so do a proper count...
7746
0
  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7747
0
  return dn;
7748
0
  } // decDecap
7749
7750
/* ------------------------------------------------------------------ */
7751
/* decBiStr -- compare string with pairwise options                   */
7752
/*                                                                    */
7753
/*   targ is the string to compare                                    */
7754
/*   str1 is one of the strings to compare against (length may be 0)  */
7755
/*   str2 is the other; it must be the same length as str1            */
7756
/*                                                                    */
7757
/*   returns 1 if strings compare equal, (that is, it is the same     */
7758
/*   length as str1 and str2, and each character of targ is in either */
7759
/*   str1 or str2 in the corresponding position), or 0 otherwise      */
7760
/*                                                                    */
7761
/* This is used for generic caseless compare, including the awkward   */
7762
/* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7763
/*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7764
/* ------------------------------------------------------------------ */
7765
509
static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7766
579
  for (;;targ++, str1++, str2++) {
7767
579
    if (*targ!=*str1 && *targ!=*str2) return 0;
7768
    // *targ has a match in one (or both, if terminator)
7769
73
    if (*targ=='\0') break;
7770
73
    } // forever
7771
3
  return 1;
7772
509
  } // decBiStr
7773
7774
/* ------------------------------------------------------------------ */
7775
/* decNaNs -- handle NaN operand or operands                          */
7776
/*                                                                    */
7777
/*   res     is the result number                                     */
7778
/*   lhs     is the first operand                                     */
7779
/*   rhs     is the second operand, or NULL if none                   */
7780
/*   context is used to limit payload length                          */
7781
/*   status  contains the current status                              */
7782
/*   returns res in case convenient                                   */
7783
/*                                                                    */
7784
/* Called when one or both operands is a NaN, and propagates the      */
7785
/* appropriate result to res.  When an sNaN is found, it is changed   */
7786
/* to a qNaN and Invalid operation is set.                            */
7787
/* ------------------------------------------------------------------ */
7788
static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7789
                           const decNumber *rhs, decContext *set,
7790
0
                           uInt *status) {
7791
  // This decision tree ends up with LHS being the source pointer,
7792
  // and status updated if need be
7793
0
  if (lhs->bits & DECSNAN)
7794
0
    *status|=DEC_Invalid_operation | DEC_sNaN;
7795
0
   else if (rhs==NULL){;}
7796
0
   else if (rhs->bits & DECSNAN) {
7797
0
    lhs=rhs;
7798
0
    *status|=DEC_Invalid_operation | DEC_sNaN;
7799
0
    }
7800
0
   else if (lhs->bits & DECNAN){;}
7801
0
   else lhs=rhs;
7802
7803
  // propagate the payload
7804
0
  if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy
7805
0
   else { // too long
7806
0
    const Unit *ul;
7807
0
    Unit *ur, *uresp1;
7808
    // copy safe number of units, then decapitate
7809
0
    res->bits=lhs->bits;                // need sign etc.
7810
0
    uresp1=res->lsu+D2U(set->digits);
7811
0
    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7812
0
    res->digits=D2U(set->digits)*DECDPUN;
7813
    // maybe still too long
7814
0
    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7815
0
    }
7816
7817
0
  res->bits&=~DECSNAN;        // convert any sNaN to NaN, while
7818
0
  res->bits|=DECNAN;          // .. preserving sign
7819
0
  res->exponent=0;            // clean exponent
7820
                              // [coefficient was copied/decapitated]
7821
0
  return res;
7822
0
  } // decNaNs
7823
7824
/* ------------------------------------------------------------------ */
7825
/* decStatus -- apply non-zero status                                 */
7826
/*                                                                    */
7827
/*   dn     is the number to set if error                             */
7828
/*   status contains the current status (not yet in context)          */
7829
/*   set    is the context                                            */
7830
/*                                                                    */
7831
/* If the status is an error status, the number is set to a NaN,      */
7832
/* unless the error was an overflow, divide-by-zero, or underflow,    */
7833
/* in which case the number will have already been set.               */
7834
/*                                                                    */
7835
/* The context status is then updated with the new status.  Note that */
7836
/* this may raise a signal, so control may never return from this     */
7837
/* routine (hence resources must be recovered before it is called).   */
7838
/* ------------------------------------------------------------------ */
7839
4.20k
static void decStatus(decNumber *dn, uInt status, decContext *set) {
7840
4.20k
  if (status & DEC_NaNs) {              // error status -> NaN
7841
    // if cause was an sNaN, clear and propagate [NaN is already set up]
7842
231
    if (status & DEC_sNaN) status&=~DEC_sNaN;
7843
231
     else {
7844
231
      decNumberZero(dn);                // other error: clean throughout
7845
231
      dn->bits=DECNAN;                  // and make a quiet NaN
7846
231
      }
7847
231
    }
7848
4.20k
  decContextSetStatus(set, status);     // [may not return]
7849
4.20k
  return;
7850
4.20k
  } // decStatus
7851
7852
/* ------------------------------------------------------------------ */
7853
/* decGetDigits -- count digits in a Units array                      */
7854
/*                                                                    */
7855
/*   uar is the Unit array holding the number (this is often an       */
7856
/*          accumulator of some sort)                                 */
7857
/*   len is the length of the array in units [>=1]                    */
7858
/*                                                                    */
7859
/*   returns the number of (significant) digits in the array          */
7860
/*                                                                    */
7861
/* All leading zeros are excluded, except the last if the array has   */
7862
/* only zero Units.                                                   */
7863
/* ------------------------------------------------------------------ */
7864
// This may be called twice during some operations.
7865
0
static Int decGetDigits(Unit *uar, Int len) {
7866
0
  Unit *up=uar+(len-1);            // -> msu
7867
0
  Int  digits=(len-1)*DECDPUN+1;   // possible digits excluding msu
7868
  #if DECDPUN>4
7869
  uInt const *pow;                 // work
7870
  #endif
7871
                                   // (at least 1 in final msu)
7872
  #if DECCHECK
7873
  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7874
  #endif
7875
7876
0
  for (; up>=uar; up--) {
7877
0
    if (*up==0) {                  // unit is all 0s
7878
0
      if (digits==1) break;        // a zero has one digit
7879
0
      digits-=DECDPUN;             // adjust for 0 unit
7880
0
      continue;}
7881
    // found the first (most significant) non-zero Unit
7882
0
    #if DECDPUN>1                  // not done yet
7883
0
    if (*up<10) break;             // is 1-9
7884
0
    digits++;
7885
0
    #if DECDPUN>2                  // not done yet
7886
0
    if (*up<100) break;            // is 10-99
7887
0
    digits++;
7888
    #if DECDPUN>3                  // not done yet
7889
    if (*up<1000) break;           // is 100-999
7890
    digits++;
7891
    #if DECDPUN>4                  // count the rest ...
7892
    for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7893
    #endif
7894
    #endif
7895
0
    #endif
7896
0
    #endif
7897
0
    break;
7898
0
    } // up
7899
0
  return digits;
7900
0
  } // decGetDigits
7901
7902
#if DECTRACE | DECCHECK
7903
/* ------------------------------------------------------------------ */
7904
/* decNumberShow -- display a number [debug aid]                      */
7905
/*   dn is the number to show                                         */
7906
/*                                                                    */
7907
/* Shows: sign, exponent, coefficient (msu first), digits             */
7908
/*    or: sign, special-value                                         */
7909
/* ------------------------------------------------------------------ */
7910
// this is public so other modules can use it
7911
void decNumberShow(const decNumber *dn) {
7912
  const Unit *up;                  // work
7913
  uInt u, d;                       // ..
7914
  Int cut;                         // ..
7915
  char isign='+';                  // main sign
7916
  if (dn==NULL) {
7917
    printf("NULL\n");
7918
    return;}
7919
  if (decNumberIsNegative(dn)) isign='-';
7920
  printf(" >> %c ", isign);
7921
  if (dn->bits&DECSPECIAL) {       // Is a special value
7922
    if (decNumberIsInfinite(dn)) printf("Infinity");
7923
     else {                                  // a NaN
7924
      if (dn->bits&DECSNAN) printf("sNaN");  // signalling NaN
7925
       else printf("NaN");
7926
      }
7927
    // if coefficient and exponent are 0, no more to do
7928
    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7929
      printf("\n");
7930
      return;}
7931
    // drop through to report other information
7932
    printf(" ");
7933
    }
7934
7935
  // now carefully display the coefficient
7936
  up=dn->lsu+D2U(dn->digits)-1;         // msu
7937
  printf("%ld", (LI)*up);
7938
  for (up=up-1; up>=dn->lsu; up--) {
7939
    u=*up;
7940
    printf(":");
7941
    for (cut=DECDPUN-1; cut>=0; cut--) {
7942
      d=u/powers[cut];
7943
      u-=d*powers[cut];
7944
      printf("%ld", (LI)d);
7945
      } // cut
7946
    } // up
7947
  if (dn->exponent!=0) {
7948
    char esign='+';
7949
    if (dn->exponent<0) esign='-';
7950
    printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7951
    }
7952
  printf(" [%ld]\n", (LI)dn->digits);
7953
  } // decNumberShow
7954
#endif
7955
7956
#if DECTRACE || DECCHECK
7957
/* ------------------------------------------------------------------ */
7958
/* decDumpAr -- display a unit array [debug/check aid]                */
7959
/*   name is a single-character tag name                              */
7960
/*   ar   is the array to display                                     */
7961
/*   len  is the length of the array in Units                         */
7962
/* ------------------------------------------------------------------ */
7963
static void decDumpAr(char name, const Unit *ar, Int len) {
7964
  Int i;
7965
  const char *spec;
7966
  #if DECDPUN==9
7967
    spec="%09d ";
7968
  #elif DECDPUN==8
7969
    spec="%08d ";
7970
  #elif DECDPUN==7
7971
    spec="%07d ";
7972
  #elif DECDPUN==6
7973
    spec="%06d ";
7974
  #elif DECDPUN==5
7975
    spec="%05d ";
7976
  #elif DECDPUN==4
7977
    spec="%04d ";
7978
  #elif DECDPUN==3
7979
    spec="%03d ";
7980
  #elif DECDPUN==2
7981
    spec="%02d ";
7982
  #else
7983
    spec="%d ";
7984
  #endif
7985
  printf("  :%c: ", name);
7986
  for (i=len-1; i>=0; i--) {
7987
    if (i==len-1) printf("%ld ", (LI)ar[i]);
7988
     else printf(spec, ar[i]);
7989
    }
7990
  printf("\n");
7991
  return;}
7992
#endif
7993
7994
#if DECCHECK
7995
/* ------------------------------------------------------------------ */
7996
/* decCheckOperands -- check operand(s) to a routine                  */
7997
/*   res is the result structure (not checked; it will be set to      */
7998
/*          quiet NaN if error found (and it is not NULL))            */
7999
/*   lhs is the first operand (may be DECUNRESU)                      */
8000
/*   rhs is the second (may be DECUNUSED)                             */
8001
/*   set is the context (may be DECUNCONT)                            */
8002
/*   returns 0 if both operands, and the context are clean, or 1      */
8003
/*     otherwise (in which case the context will show an error,       */
8004
/*     unless NULL).  Note that res is not cleaned; caller should     */
8005
/*     handle this so res=NULL case is safe.                          */
8006
/* The caller is expected to abandon immediately if 1 is returned.    */
8007
/* ------------------------------------------------------------------ */
8008
static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
8009
                             const decNumber *rhs, decContext *set) {
8010
  Flag bad=0;
8011
  if (set==NULL) {                 // oops; hopeless
8012
    #if DECTRACE || DECVERB
8013
    printf("Reference to context is NULL.\n");
8014
    #endif
8015
    bad=1;
8016
    return 1;}
8017
   else if (set!=DECUNCONT
8018
     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
8019
    bad=1;
8020
    #if DECTRACE || DECVERB
8021
    printf("Bad context [digits=%ld round=%ld].\n",
8022
           (LI)set->digits, (LI)set->round);
8023
    #endif
8024
    }
8025
   else {
8026
    if (res==NULL) {
8027
      bad=1;
8028
      #if DECTRACE
8029
      // this one not DECVERB as standard tests include NULL
8030
      printf("Reference to result is NULL.\n");
8031
      #endif
8032
      }
8033
    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
8034
    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
8035
    }
8036
  if (bad) {
8037
    if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
8038
    if (res!=DECUNRESU && res!=NULL) {
8039
      decNumberZero(res);
8040
      res->bits=DECNAN;       // qNaN
8041
      }
8042
    }
8043
  return bad;
8044
  } // decCheckOperands
8045
8046
/* ------------------------------------------------------------------ */
8047
/* decCheckNumber -- check a number                                   */
8048
/*   dn is the number to check                                        */
8049
/*   returns 0 if the number is clean, or 1 otherwise                 */
8050
/*                                                                    */
8051
/* The number is considered valid if it could be a result from some   */
8052
/* operation in some valid context.                                   */
8053
/* ------------------------------------------------------------------ */
8054
static Flag decCheckNumber(const decNumber *dn) {
8055
  const Unit *up;             // work
8056
  uInt maxuint;               // ..
8057
  Int ae, d, digits;          // ..
8058
  Int emin, emax;             // ..
8059
8060
  if (dn==NULL) {             // hopeless
8061
    #if DECTRACE
8062
    // this one not DECVERB as standard tests include NULL
8063
    printf("Reference to decNumber is NULL.\n");
8064
    #endif
8065
    return 1;}
8066
8067
  // check special values
8068
  if (dn->bits & DECSPECIAL) {
8069
    if (dn->exponent!=0) {
8070
      #if DECTRACE || DECVERB
8071
      printf("Exponent %ld (not 0) for a special value [%02x].\n",
8072
             (LI)dn->exponent, dn->bits);
8073
      #endif
8074
      return 1;}
8075
8076
    // 2003.09.08: NaNs may now have coefficients, so next tests Inf only
8077
    if (decNumberIsInfinite(dn)) {
8078
      if (dn->digits!=1) {
8079
        #if DECTRACE || DECVERB
8080
        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8081
        #endif
8082
        return 1;}
8083
      if (*dn->lsu!=0) {
8084
        #if DECTRACE || DECVERB
8085
        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8086
        #endif
8087
        decDumpAr('I', dn->lsu, D2U(dn->digits));
8088
        return 1;}
8089
      } // Inf
8090
    // 2002.12.26: negative NaNs can now appear through proposed IEEE
8091
    //             concrete formats (decimal64, etc.).
8092
    return 0;
8093
    }
8094
8095
  // check the coefficient
8096
  if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8097
    #if DECTRACE || DECVERB
8098
    printf("Digits %ld in number.\n", (LI)dn->digits);
8099
    #endif
8100
    return 1;}
8101
8102
  d=dn->digits;
8103
8104
  for (up=dn->lsu; d>0; up++) {
8105
    if (d>DECDPUN) maxuint=DECDPUNMAX;
8106
     else {                   // reached the msu
8107
      maxuint=powers[d]-1;
8108
      if (dn->digits>1 && *up<powers[d-1]) {
8109
        #if DECTRACE || DECVERB
8110
        printf("Leading 0 in number.\n");
8111
        decNumberShow(dn);
8112
        #endif
8113
        return 1;}
8114
      }
8115
    if (*up>maxuint) {
8116
      #if DECTRACE || DECVERB
8117
      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8118
              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8119
      #endif
8120
      return 1;}
8121
    d-=DECDPUN;
8122
    }
8123
8124
  // check the exponent.  Note that input operands can have exponents
8125
  // which are out of the set->emin/set->emax and set->digits range
8126
  // (just as they can have more digits than set->digits).
8127
  ae=dn->exponent+dn->digits-1;    // adjusted exponent
8128
  emax=DECNUMMAXE;
8129
  emin=DECNUMMINE;
8130
  digits=DECNUMMAXP;
8131
  if (ae<emin-(digits-1)) {
8132
    #if DECTRACE || DECVERB
8133
    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8134
    decNumberShow(dn);
8135
    #endif
8136
    return 1;}
8137
  if (ae>+emax) {
8138
    #if DECTRACE || DECVERB
8139
    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8140
    decNumberShow(dn);
8141
    #endif
8142
    return 1;}
8143
8144
  return 0;              // it's OK
8145
  } // decCheckNumber
8146
8147
/* ------------------------------------------------------------------ */
8148
/* decCheckInexact -- check a normal finite inexact result has digits */
8149
/*   dn is the number to check                                        */
8150
/*   set is the context (for status and precision)                    */
8151
/*   sets Invalid operation, etc., if some digits are missing         */
8152
/* [this check is not made for DECSUBSET compilation or when          */
8153
/* subnormal is not set]                                              */
8154
/* ------------------------------------------------------------------ */
8155
static void decCheckInexact(const decNumber *dn, decContext *set) {
8156
  #if !DECSUBSET && DECEXTFLAG
8157
    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8158
     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8159
      #if DECTRACE || DECVERB
8160
      printf("Insufficient digits [%ld] on normal Inexact result.\n",
8161
             (LI)dn->digits);
8162
      decNumberShow(dn);
8163
      #endif
8164
      decContextSetStatus(set, DEC_Invalid_operation);
8165
      }
8166
  #else
8167
    // next is a noop for quiet compiler
8168
    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8169
  #endif
8170
  return;
8171
  } // decCheckInexact
8172
#endif
8173
8174
#if DECALLOC
8175
#undef malloc
8176
#undef free
8177
/* ------------------------------------------------------------------ */
8178
/* decMalloc -- accountable allocation routine                        */
8179
/*   n is the number of bytes to allocate                             */
8180
/*                                                                    */
8181
/* Semantics is the same as the stdlib malloc routine, but bytes      */
8182
/* allocated are accounted for globally, and corruption fences are    */
8183
/* added before and after the 'actual' storage.                       */
8184
/* ------------------------------------------------------------------ */
8185
/* This routine allocates storage with an extra twelve bytes; 8 are   */
8186
/* at the start and hold:                                             */
8187
/*   0-3 the original length requested                                */
8188
/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8189
/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8190
/* ------------------------------------------------------------------ */
8191
static void *decMalloc(size_t n) {
8192
  uInt  size=n+12;                 // true size
8193
  void  *alloc;                    // -> allocated storage
8194
  uByte *b, *b0;                   // work
8195
  uInt  uiwork;                    // for macros
8196
8197
  alloc=malloc(size);              // -> allocated storage
8198
  if (alloc==NULL) return NULL;    // out of strorage
8199
  b0=(uByte *)alloc;               // as bytes
8200
  decAllocBytes+=n;                // account for storage
8201
  UBFROMUI(alloc, n);              // save n
8202
  // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);
8203
  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8204
  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8205
  return b0+8;                     // -> play area
8206
  } // decMalloc
8207
8208
/* ------------------------------------------------------------------ */
8209
/* decFree -- accountable free routine                                */
8210
/*   alloc is the storage to free                                     */
8211
/*                                                                    */
8212
/* Semantics is the same as the stdlib malloc routine, except that    */
8213
/* the global storage accounting is updated and the fences are        */
8214
/* checked to ensure that no routine has written 'out of bounds'.     */
8215
/* ------------------------------------------------------------------ */
8216
/* This routine first checks that the fences have not been corrupted. */
8217
/* It then frees the storage using the 'truw' storage address (that   */
8218
/* is, offset by 8).                                                  */
8219
/* ------------------------------------------------------------------ */
8220
static void decFree(void *alloc) {
8221
  uInt  n;                         // original length
8222
  uByte *b, *b0;                   // work
8223
  uInt  uiwork;                    // for macros
8224
8225
  if (alloc==NULL) return;         // allowed; it's a nop
8226
  b0=(uByte *)alloc;               // as bytes
8227
  b0-=8;                           // -> true start of storage
8228
  n=UBTOUI(b0);                    // lift length
8229
  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8230
    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8231
           b-b0-8, (LI)b0);
8232
  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8233
    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8234
           b-b0-8, (LI)b0, (LI)n);
8235
  free(b0);                        // drop the storage
8236
  decAllocBytes-=n;                // account for storage
8237
  // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);
8238
  } // decFree
8239
#define malloc(a) decMalloc(a)
8240
#define free(a) decFree(a)
8241
#endif