xref: /openbsd-src/gnu/gcc/libdecnumber/decNumber.c (revision 404b540a9034ac75a6199ad1a32d1bbc7a0d4210)
1*404b540aSrobert /* Decimal Number module for the decNumber C Library
2*404b540aSrobert    Copyright (C) 2005 Free Software Foundation, Inc.
3*404b540aSrobert    Contributed by IBM Corporation.  Author Mike Cowlishaw.
4*404b540aSrobert 
5*404b540aSrobert    This file is part of GCC.
6*404b540aSrobert 
7*404b540aSrobert    GCC is free software; you can redistribute it and/or modify it under
8*404b540aSrobert    the terms of the GNU General Public License as published by the Free
9*404b540aSrobert    Software Foundation; either version 2, or (at your option) any later
10*404b540aSrobert    version.
11*404b540aSrobert 
12*404b540aSrobert    In addition to the permissions in the GNU General Public License,
13*404b540aSrobert    the Free Software Foundation gives you unlimited permission to link
14*404b540aSrobert    the compiled version of this file into combinations with other
15*404b540aSrobert    programs, and to distribute those combinations without any
16*404b540aSrobert    restriction coming from the use of this file.  (The General Public
17*404b540aSrobert    License restrictions do apply in other respects; for example, they
18*404b540aSrobert    cover modification of the file, and distribution when not linked
19*404b540aSrobert    into a combine executable.)
20*404b540aSrobert 
21*404b540aSrobert    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22*404b540aSrobert    WARRANTY; without even the implied warranty of MERCHANTABILITY or
23*404b540aSrobert    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
24*404b540aSrobert    for more details.
25*404b540aSrobert 
26*404b540aSrobert    You should have received a copy of the GNU General Public License
27*404b540aSrobert    along with GCC; see the file COPYING.  If not, write to the Free
28*404b540aSrobert    Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29*404b540aSrobert    02110-1301, USA.  */
30*404b540aSrobert 
31*404b540aSrobert /* ------------------------------------------------------------------ */
32*404b540aSrobert /* This module comprises the routines for Standard Decimal Arithmetic */
33*404b540aSrobert /* as defined in the specification which may be found on the          */
34*404b540aSrobert /* http://www2.hursley.ibm.com/decimal web pages.  It implements both */
35*404b540aSrobert /* the full ('extended') arithmetic and the simpler ('subset')        */
36*404b540aSrobert /* arithmetic.                                                        */
37*404b540aSrobert /*                                                                    */
38*404b540aSrobert /* Usage notes:                                                       */
39*404b540aSrobert /*                                                                    */
40*404b540aSrobert /* 1. This code is ANSI C89 except:                                   */
41*404b540aSrobert /*                                                                    */
42*404b540aSrobert /*    a) Line comments (double forward slash) are used.  (Most C      */
43*404b540aSrobert /*       compilers accept these.  If yours does not, a simple script  */
44*404b540aSrobert /*       can be used to convert them to ANSI C comments.)             */
45*404b540aSrobert /*                                                                    */
46*404b540aSrobert /*    b) Types from C99 stdint.h are used.  If you do not have this   */
47*404b540aSrobert /*       header file, see the User's Guide section of the decNumber   */
48*404b540aSrobert /*       documentation; this lists the necessary definitions.         */
49*404b540aSrobert /*                                                                    */
50*404b540aSrobert /*    c) If DECDPUN>4, non-ANSI 64-bit 'long long' types are used.    */
51*404b540aSrobert /*       To avoid these, set DECDPUN <= 4 (see documentation).        */
52*404b540aSrobert /*                                                                    */
53*404b540aSrobert /* 2. The decNumber format which this library uses is optimized for   */
54*404b540aSrobert /*    efficient processing of relatively short numbers; in particular */
55*404b540aSrobert /*    it allows the use of fixed sized structures and minimizes copy  */
56*404b540aSrobert /*    and move operations.  It does, however, support arbitrary       */
57*404b540aSrobert /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
58*404b540aSrobert /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
59*404b540aSrobert /*    range -999,999,999 through 0).                                  */
60*404b540aSrobert /*                                                                    */
61*404b540aSrobert /* 3. Operands to operator functions are never modified unless they   */
62*404b540aSrobert /*    are also specified to be the result number (which is always     */
63*404b540aSrobert /*    permitted).  Other than that case, operands may not overlap.    */
64*404b540aSrobert /*                                                                    */
65*404b540aSrobert /* 4. Error handling: the type of the error is ORed into the status   */
66*404b540aSrobert /*    flags in the current context (decContext structure).  The       */
67*404b540aSrobert /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
68*404b540aSrobert /*    flag in the decContext is set (is 1).                           */
69*404b540aSrobert /*                                                                    */
70*404b540aSrobert /*    It is the responsibility of the caller to clear the status      */
71*404b540aSrobert /*    flags as required.                                              */
72*404b540aSrobert /*                                                                    */
73*404b540aSrobert /*    The result of any routine which returns a number will always    */
74*404b540aSrobert /*    be a valid number (which may be a special value, such as an     */
75*404b540aSrobert /*    Infinity or NaN).                                               */
76*404b540aSrobert /*                                                                    */
77*404b540aSrobert /* 5. The decNumber format is not an exchangeable concrete            */
78*404b540aSrobert /*    representation as it comprises fields which may be machine-     */
79*404b540aSrobert /*    dependent (big-endian or little-endian, for example).           */
80*404b540aSrobert /*    Canonical conversions to and from strings are provided; other   */
81*404b540aSrobert /*    conversions are available in separate modules.                  */
82*404b540aSrobert /*                                                                    */
83*404b540aSrobert /* 6. Normally, input operands are assumed to be valid.  Set DECCHECK */
84*404b540aSrobert /*    to 1 for extended operand checking (including NULL operands).   */
85*404b540aSrobert /*    Results are undefined if a badly-formed structure (or a NULL    */
86*404b540aSrobert /*    NULL pointer to a structure) is provided, though with DECCHECK  */
87*404b540aSrobert /*    enabled the operator routines are protected against exceptions. */
88*404b540aSrobert /*    (Except if the result pointer is NULL, which is unrecoverable.) */
89*404b540aSrobert /*                                                                    */
90*404b540aSrobert /*    However, the routines will never cause exceptions if they are   */
91*404b540aSrobert /*    given well-formed operands, even if the value of the operands   */
92*404b540aSrobert /*    is inappropriate for the operation and DECCHECK is not set.     */
93*404b540aSrobert /*                                                                    */
94*404b540aSrobert /* 7. Subset arithmetic is available only if DECSUBSET is set to 1.   */
95*404b540aSrobert /* ------------------------------------------------------------------ */
96*404b540aSrobert /* Implementation notes for maintenance of this module:               */
97*404b540aSrobert /*                                                                    */
98*404b540aSrobert /* 1. Storage leak protection:  Routines which use malloc are not     */
99*404b540aSrobert /*    permitted to use return for fastpath or error exits (i.e.,      */
100*404b540aSrobert /*    they follow strict structured programming conventions).         */
101*404b540aSrobert /*    Instead they have a do{}while(0); construct surrounding the     */
102*404b540aSrobert /*    code which is protected -- break may be used from this.         */
103*404b540aSrobert /*    Other routines are allowed to use the return statement inline.  */
104*404b540aSrobert /*                                                                    */
105*404b540aSrobert /*    Storage leak accounting can be enabled using DECALLOC.          */
106*404b540aSrobert /*                                                                    */
107*404b540aSrobert /* 2. All loops use the for(;;) construct.  Any do construct is for   */
108*404b540aSrobert /*    protection as just described.                                   */
109*404b540aSrobert /*                                                                    */
110*404b540aSrobert /* 3. Setting status in the context must always be the very last      */
111*404b540aSrobert /*    action in a routine, as non-0 status may raise a trap and hence */
112*404b540aSrobert /*    the call to set status may not return (if the handler uses long */
113*404b540aSrobert /*    jump).  Therefore all cleanup must be done first.  In general,  */
114*404b540aSrobert /*    to achieve this we accumulate status and only finally apply it  */
115*404b540aSrobert /*    by calling decContextSetStatus (via decStatus).                 */
116*404b540aSrobert /*                                                                    */
117*404b540aSrobert /*    Routines which allocate storage cannot, therefore, use the      */
118*404b540aSrobert /*    'top level' routines which could cause a non-returning          */
119*404b540aSrobert /*    transfer of control.  The decXxxxOp routines are safe (do not   */
120*404b540aSrobert /*    call decStatus even if traps are set in the context) and should */
121*404b540aSrobert /*    be used instead (they are also a little faster).                */
122*404b540aSrobert /*                                                                    */
123*404b540aSrobert /* 4. Exponent checking is minimized by allowing the exponent to      */
124*404b540aSrobert /*    grow outside its limits during calculations, provided that      */
125*404b540aSrobert /*    the decFinalize function is called later.  Multiplication and   */
126*404b540aSrobert /*    division, and intermediate calculations in exponentiation,      */
127*404b540aSrobert /*    require more careful checks because of the risk of 31-bit       */
128*404b540aSrobert /*    overflow (the most negative valid exponent is -1999999997, for  */
129*404b540aSrobert /*    a 999999999-digit number with adjusted exponent of -999999999). */
130*404b540aSrobert /*                                                                    */
131*404b540aSrobert /* 5. Rounding is deferred until finalization of results, with any    */
132*404b540aSrobert /*    'off to the right' data being represented as a single digit     */
133*404b540aSrobert /*    residue (in the range -1 through 9).  This avoids any double-   */
134*404b540aSrobert /*    rounding when more than one shortening takes place (for         */
135*404b540aSrobert /*    example, when a result is subnormal).                           */
136*404b540aSrobert /*                                                                    */
137*404b540aSrobert /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
138*404b540aSrobert /*    during many operations, so whole Units are handled and exact    */
139*404b540aSrobert /*    accounting of digits is not needed.  The correct digits value   */
140*404b540aSrobert /*    is found by decGetDigits, which accounts for leading zeros.     */
141*404b540aSrobert /*    This must be called before any rounding if the number of digits */
142*404b540aSrobert /*    is not known exactly.                                           */
143*404b540aSrobert /*                                                                    */
144*404b540aSrobert /* 7. We use the multiply-by-reciprocal 'trick' for partitioning      */
145*404b540aSrobert /*    numbers up to four digits, using appropriate constants.  This   */
146*404b540aSrobert /*    is not useful for longer numbers because overflow of 32 bits    */
147*404b540aSrobert /*    would lead to 4 multiplies, which is almost as expensive as     */
148*404b540aSrobert /*    a divide (unless we assumed floating-point multiply available). */
149*404b540aSrobert /*                                                                    */
150*404b540aSrobert /* 8. Unusual abbreviations possibly used in the commentary:          */
151*404b540aSrobert /*      lhs -- left hand side (operand, of an operation)              */
152*404b540aSrobert /*      lsd -- least significant digit (of coefficient)               */
153*404b540aSrobert /*      lsu -- least significant Unit (of coefficient)                */
154*404b540aSrobert /*      msd -- most significant digit (of coefficient)                */
155*404b540aSrobert /*      msu -- most significant Unit (of coefficient)                 */
156*404b540aSrobert /*      rhs -- right hand side (operand, of an operation)             */
157*404b540aSrobert /*      +ve -- positive                                               */
158*404b540aSrobert /*      -ve -- negative                                               */
159*404b540aSrobert /* ------------------------------------------------------------------ */
160*404b540aSrobert 
161*404b540aSrobert /* Some of glibc's string inlines cause warnings.  Plus we'd rather
162*404b540aSrobert    rely on (and therefore test) GCC's string builtins.  */
163*404b540aSrobert #define __NO_STRING_INLINES
164*404b540aSrobert 
165*404b540aSrobert #include <stdlib.h>		/* for malloc, free, etc. */
166*404b540aSrobert #include <stdio.h>		/* for printf [if needed] */
167*404b540aSrobert #include <string.h>		/* for strcpy */
168*404b540aSrobert #include <ctype.h>		/* for lower */
169*404b540aSrobert #include "config.h"
170*404b540aSrobert #include "decNumber.h"		/* base number library */
171*404b540aSrobert #include "decNumberLocal.h"	/* decNumber local types, etc. */
172*404b540aSrobert 
173*404b540aSrobert /* Constants */
174*404b540aSrobert /* Public constant array: powers of ten (powers[n]==10**n) */
175*404b540aSrobert const uInt powers[] = { 1, 10, 100, 1000, 10000, 100000, 1000000,
176*404b540aSrobert   10000000, 100000000, 1000000000
177*404b540aSrobert };
178*404b540aSrobert 
179*404b540aSrobert /* Local constants */
180*404b540aSrobert #define DIVIDE    0x80		/* Divide operators */
181*404b540aSrobert #define REMAINDER 0x40		/* .. */
182*404b540aSrobert #define DIVIDEINT 0x20		/* .. */
183*404b540aSrobert #define REMNEAR   0x10		/* .. */
184*404b540aSrobert #define COMPARE   0x01		/* Compare operators */
185*404b540aSrobert #define COMPMAX   0x02		/* .. */
186*404b540aSrobert #define COMPMIN   0x03		/* .. */
187*404b540aSrobert #define COMPNAN   0x04		/* .. [NaN processing] */
188*404b540aSrobert 
189*404b540aSrobert #define DEC_sNaN 0x40000000	/* local status: sNaN signal */
190*404b540aSrobert #define BADINT (Int)0x80000000	/* most-negative Int; error indicator */
191*404b540aSrobert 
192*404b540aSrobert static Unit one[] = { 1 };	/* Unit array of 1, used for incrementing */
193*404b540aSrobert 
194*404b540aSrobert /* Granularity-dependent code */
195*404b540aSrobert #if DECDPUN<=4
196*404b540aSrobert #define eInt  Int		/* extended integer */
197*404b540aSrobert #define ueInt uInt		/* unsigned extended integer */
198*404b540aSrobert   /* Constant multipliers for divide-by-power-of five using reciprocal */
199*404b540aSrobert   /* multiply, after removing powers of 2 by shifting, and final shift */
200*404b540aSrobert   /* of 17 [we only need up to **4] */
201*404b540aSrobert static const uInt multies[] = { 131073, 26215, 5243, 1049, 210 };
202*404b540aSrobert 
203*404b540aSrobert   /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
204*404b540aSrobert #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
205*404b540aSrobert #else
206*404b540aSrobert   /* For DECDPUN>4 we currently use non-ANSI 64-bit types.  These could */
207*404b540aSrobert   /* be replaced by subroutine calls later. */
208*404b540aSrobert #ifdef long
209*404b540aSrobert #undef long
210*404b540aSrobert #endif
211*404b540aSrobert typedef signed long long Long;
212*404b540aSrobert typedef unsigned long long uLong;
213*404b540aSrobert #define eInt  Long		/* extended integer */
214*404b540aSrobert #define ueInt uLong		/* unsigned extended integer */
215*404b540aSrobert #endif
216*404b540aSrobert 
217*404b540aSrobert /* Local routines */
218*404b540aSrobert static decNumber *decAddOp (decNumber *, const decNumber *,
219*404b540aSrobert 			    const decNumber *, decContext *,
220*404b540aSrobert 			    uByte, uInt *);
221*404b540aSrobert static void decApplyRound (decNumber *, decContext *, Int, uInt *);
222*404b540aSrobert static Int decCompare (const decNumber * lhs, const decNumber * rhs);
223*404b540aSrobert static decNumber *decCompareOp (decNumber *, const decNumber *, const decNumber *,
224*404b540aSrobert 				decContext *, Flag, uInt *);
225*404b540aSrobert static void decCopyFit (decNumber *, const decNumber *, decContext *,
226*404b540aSrobert 			Int *, uInt *);
227*404b540aSrobert static decNumber *decDivideOp (decNumber *, const decNumber *, const decNumber *,
228*404b540aSrobert 			       decContext *, Flag, uInt *);
229*404b540aSrobert static void decFinalize (decNumber *, decContext *, Int *, uInt *);
230*404b540aSrobert static Int decGetDigits (const Unit *, Int);
231*404b540aSrobert #if DECSUBSET
232*404b540aSrobert static Int decGetInt (const decNumber *, decContext *);
233*404b540aSrobert #else
234*404b540aSrobert static Int decGetInt (const decNumber *);
235*404b540aSrobert #endif
236*404b540aSrobert static decNumber *decMultiplyOp (decNumber *, const decNumber *,
237*404b540aSrobert 				 const decNumber *, decContext *, uInt *);
238*404b540aSrobert static decNumber *decNaNs (decNumber *, const decNumber *, const decNumber *, uInt *);
239*404b540aSrobert static decNumber *decQuantizeOp (decNumber *, const decNumber *,
240*404b540aSrobert 				 const decNumber *, decContext *, Flag, uInt *);
241*404b540aSrobert static void decSetCoeff (decNumber *, decContext *, const Unit *,
242*404b540aSrobert 			 Int, Int *, uInt *);
243*404b540aSrobert static void decSetOverflow (decNumber *, decContext *, uInt *);
244*404b540aSrobert static void decSetSubnormal (decNumber *, decContext *, Int *, uInt *);
245*404b540aSrobert static Int decShiftToLeast (Unit *, Int, Int);
246*404b540aSrobert static Int decShiftToMost (Unit *, Int, Int);
247*404b540aSrobert static void decStatus (decNumber *, uInt, decContext *);
248*404b540aSrobert static Flag decStrEq (const char *, const char *);
249*404b540aSrobert static void decToString (const decNumber *, char[], Flag);
250*404b540aSrobert static decNumber *decTrim (decNumber *, Flag, Int *);
251*404b540aSrobert static Int decUnitAddSub (const Unit *, Int, const Unit *, Int, Int, Unit *, Int);
252*404b540aSrobert static Int decUnitCompare (const Unit *, Int, const Unit *, Int, Int);
253*404b540aSrobert 
254*404b540aSrobert #if !DECSUBSET
255*404b540aSrobert /* decFinish == decFinalize when no subset arithmetic needed */
256*404b540aSrobert #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
257*404b540aSrobert #else
258*404b540aSrobert static void decFinish (decNumber *, decContext *, Int *, uInt *);
259*404b540aSrobert static decNumber *decRoundOperand (const decNumber *, decContext *, uInt *);
260*404b540aSrobert #endif
261*404b540aSrobert 
262*404b540aSrobert /* Diagnostic macros, etc. */
263*404b540aSrobert #if DECALLOC
264*404b540aSrobert /* Handle malloc/free accounting.  If enabled, our accountable routines */
265*404b540aSrobert /* are used; otherwise the code just goes straight to the system malloc */
266*404b540aSrobert /* and free routines. */
267*404b540aSrobert #define malloc(a) decMalloc(a)
268*404b540aSrobert #define free(a) decFree(a)
269*404b540aSrobert #define DECFENCE 0x5a		/* corruption detector */
270*404b540aSrobert /* 'Our' malloc and free: */
271*404b540aSrobert static void *decMalloc (size_t);
272*404b540aSrobert static void decFree (void *);
273*404b540aSrobert uInt decAllocBytes = 0;		/* count of bytes allocated */
274*404b540aSrobert /* Note that DECALLOC code only checks for storage buffer overflow. */
275*404b540aSrobert /* To check for memory leaks, the decAllocBytes variable should be */
276*404b540aSrobert /* checked to be 0 at appropriate times (e.g., after the test */
277*404b540aSrobert /* harness completes a set of tests).  This checking may be unreliable */
278*404b540aSrobert /* if the testing is done in a multi-thread environment. */
279*404b540aSrobert #endif
280*404b540aSrobert 
281*404b540aSrobert #if DECCHECK
282*404b540aSrobert /* Optional operand checking routines.  Enabling these means that */
283*404b540aSrobert /* decNumber and decContext operands to operator routines are checked */
284*404b540aSrobert /* for correctness.  This roughly doubles the execution time of the */
285*404b540aSrobert /* fastest routines (and adds 600+ bytes), so should not normally be */
286*404b540aSrobert /* used in 'production'. */
287*404b540aSrobert #define DECUNUSED (void *)(0xffffffff)
288*404b540aSrobert static Flag decCheckOperands (decNumber *, const decNumber *,
289*404b540aSrobert 			      const decNumber *, decContext *);
290*404b540aSrobert static Flag decCheckNumber (const decNumber *, decContext *);
291*404b540aSrobert #endif
292*404b540aSrobert 
293*404b540aSrobert #if DECTRACE || DECCHECK
294*404b540aSrobert /* Optional trace/debugging routines. */
295*404b540aSrobert void decNumberShow (const decNumber *);	/* displays the components of a number */
296*404b540aSrobert static void decDumpAr (char, const Unit *, Int);
297*404b540aSrobert #endif
298*404b540aSrobert 
299*404b540aSrobert /* ================================================================== */
300*404b540aSrobert /* Conversions                                                        */
301*404b540aSrobert /* ================================================================== */
302*404b540aSrobert 
303*404b540aSrobert /* ------------------------------------------------------------------ */
304*404b540aSrobert /* to-scientific-string -- conversion to numeric string               */
305*404b540aSrobert /* to-engineering-string -- conversion to numeric string              */
306*404b540aSrobert /*                                                                    */
307*404b540aSrobert /*   decNumberToString(dn, string);                                   */
308*404b540aSrobert /*   decNumberToEngString(dn, string);                                */
309*404b540aSrobert /*                                                                    */
310*404b540aSrobert /*  dn is the decNumber to convert                                    */
311*404b540aSrobert /*  string is the string where the result will be laid out            */
312*404b540aSrobert /*                                                                    */
313*404b540aSrobert /*  string must be at least dn->digits+14 characters long             */
314*404b540aSrobert /*                                                                    */
315*404b540aSrobert /*  No error is possible, and no status can be set.                   */
316*404b540aSrobert /* ------------------------------------------------------------------ */
317*404b540aSrobert char *
decNumberToString(const decNumber * dn,char * string)318*404b540aSrobert decNumberToString (const decNumber * dn, char *string)
319*404b540aSrobert {
320*404b540aSrobert   decToString (dn, string, 0);
321*404b540aSrobert   return string;
322*404b540aSrobert }
323*404b540aSrobert 
324*404b540aSrobert char *
decNumberToEngString(const decNumber * dn,char * string)325*404b540aSrobert decNumberToEngString (const decNumber * dn, char *string)
326*404b540aSrobert {
327*404b540aSrobert   decToString (dn, string, 1);
328*404b540aSrobert   return string;
329*404b540aSrobert }
330*404b540aSrobert 
331*404b540aSrobert /* ------------------------------------------------------------------ */
332*404b540aSrobert /* to-number -- conversion from numeric string                        */
333*404b540aSrobert /*                                                                    */
334*404b540aSrobert /* decNumberFromString -- convert string to decNumber                 */
335*404b540aSrobert /*   dn        -- the number structure to fill                        */
336*404b540aSrobert /*   chars[]   -- the string to convert ('\0' terminated)             */
337*404b540aSrobert /*   set       -- the context used for processing any error,          */
338*404b540aSrobert /*                determining the maximum precision available         */
339*404b540aSrobert /*                (set.digits), determining the maximum and minimum   */
340*404b540aSrobert /*                exponent (set.emax and set.emin), determining if    */
341*404b540aSrobert /*                extended values are allowed, and checking the       */
342*404b540aSrobert /*                rounding mode if overflow occurs or rounding is     */
343*404b540aSrobert /*                needed.                                             */
344*404b540aSrobert /*                                                                    */
345*404b540aSrobert /* The length of the coefficient and the size of the exponent are     */
346*404b540aSrobert /* checked by this routine, so the correct error (Underflow or        */
347*404b540aSrobert /* Overflow) can be reported or rounding applied, as necessary.       */
348*404b540aSrobert /*                                                                    */
349*404b540aSrobert /* If bad syntax is detected, the result will be a quiet NaN.         */
350*404b540aSrobert /* ------------------------------------------------------------------ */
351*404b540aSrobert decNumber *
decNumberFromString(decNumber * dn,const char chars[],decContext * set)352*404b540aSrobert decNumberFromString (decNumber * dn, const char chars[], decContext * set)
353*404b540aSrobert {
354*404b540aSrobert   Int exponent = 0;		/* working exponent [assume 0] */
355*404b540aSrobert   uByte bits = 0;		/* working flags [assume +ve] */
356*404b540aSrobert   Unit *res;			/* where result will be built */
357*404b540aSrobert   Unit resbuff[D2U (DECBUFFER + 1)];	/* local buffer in case need temporary */
358*404b540aSrobert   Unit *allocres = NULL;	/* -> allocated result, iff allocated */
359*404b540aSrobert   Int need;			/* units needed for result */
360*404b540aSrobert   Int d = 0;			/* count of digits found in decimal part */
361*404b540aSrobert   const char *dotchar = NULL;	/* where dot was found */
362*404b540aSrobert   const char *cfirst;		/* -> first character of decimal part */
363*404b540aSrobert   const char *last = NULL;	/* -> last digit of decimal part */
364*404b540aSrobert   const char *firstexp;		/* -> first significant exponent digit */
365*404b540aSrobert   const char *c;		/* work */
366*404b540aSrobert   Unit *up;			/* .. */
367*404b540aSrobert #if DECDPUN>1
368*404b540aSrobert   Int i;			/* .. */
369*404b540aSrobert #endif
370*404b540aSrobert   Int residue = 0;		/* rounding residue */
371*404b540aSrobert   uInt status = 0;		/* error code */
372*404b540aSrobert 
373*404b540aSrobert #if DECCHECK
374*404b540aSrobert   if (decCheckOperands (DECUNUSED, DECUNUSED, DECUNUSED, set))
375*404b540aSrobert     return decNumberZero (dn);
376*404b540aSrobert #endif
377*404b540aSrobert 
378*404b540aSrobert   do
379*404b540aSrobert     {				/* status & malloc protection */
380*404b540aSrobert       c = chars;		/* -> input character */
381*404b540aSrobert       if (*c == '-')
382*404b540aSrobert 	{			/* handle leading '-' */
383*404b540aSrobert 	  bits = DECNEG;
384*404b540aSrobert 	  c++;
385*404b540aSrobert 	}
386*404b540aSrobert       else if (*c == '+')
387*404b540aSrobert 	c++;			/* step over leading '+' */
388*404b540aSrobert       /* We're at the start of the number [we think] */
389*404b540aSrobert       cfirst = c;		/* save */
390*404b540aSrobert       for (;; c++)
391*404b540aSrobert 	{
392*404b540aSrobert 	  if (*c >= '0' && *c <= '9')
393*404b540aSrobert 	    {			/* test for Arabic digit */
394*404b540aSrobert 	      last = c;
395*404b540aSrobert 	      d++;		/* count of real digits */
396*404b540aSrobert 	      continue;		/* still in decimal part */
397*404b540aSrobert 	    }
398*404b540aSrobert 	  if (*c != '.')
399*404b540aSrobert 	    break;		/* done with decimal part */
400*404b540aSrobert 	  /* dot: record, check, and ignore */
401*404b540aSrobert 	  if (dotchar != NULL)
402*404b540aSrobert 	    {			/* two dots */
403*404b540aSrobert 	      last = NULL;	/* indicate bad */
404*404b540aSrobert 	      break;
405*404b540aSrobert 	    }			/* .. and go report */
406*404b540aSrobert 	  dotchar = c;		/* offset into decimal part */
407*404b540aSrobert 	}			/* c */
408*404b540aSrobert 
409*404b540aSrobert       if (last == NULL)
410*404b540aSrobert 	{			/* no decimal digits, or >1 . */
411*404b540aSrobert #if DECSUBSET
412*404b540aSrobert 	  /* If subset then infinities and NaNs are not allowed */
413*404b540aSrobert 	  if (!set->extended)
414*404b540aSrobert 	    {
415*404b540aSrobert 	      status = DEC_Conversion_syntax;
416*404b540aSrobert 	      break;		/* all done */
417*404b540aSrobert 	    }
418*404b540aSrobert 	  else
419*404b540aSrobert 	    {
420*404b540aSrobert #endif
421*404b540aSrobert 	      /* Infinities and NaNs are possible, here */
422*404b540aSrobert 	      decNumberZero (dn);	/* be optimistic */
423*404b540aSrobert 	      if (decStrEq (c, "Infinity") || decStrEq (c, "Inf"))
424*404b540aSrobert 		{
425*404b540aSrobert 		  dn->bits = bits | DECINF;
426*404b540aSrobert 		  break;	/* all done */
427*404b540aSrobert 		}
428*404b540aSrobert 	      else
429*404b540aSrobert 		{		/* a NaN expected */
430*404b540aSrobert 		  /* 2003.09.10 NaNs are now permitted to have a sign */
431*404b540aSrobert 		  status = DEC_Conversion_syntax;	/* assume the worst */
432*404b540aSrobert 		  dn->bits = bits | DECNAN;	/* assume simple NaN */
433*404b540aSrobert 		  if (*c == 's' || *c == 'S')
434*404b540aSrobert 		    {		/* looks like an` sNaN */
435*404b540aSrobert 		      c++;
436*404b540aSrobert 		      dn->bits = bits | DECSNAN;
437*404b540aSrobert 		    }
438*404b540aSrobert 		  if (*c != 'n' && *c != 'N')
439*404b540aSrobert 		    break;	/* check caseless "NaN" */
440*404b540aSrobert 		  c++;
441*404b540aSrobert 		  if (*c != 'a' && *c != 'A')
442*404b540aSrobert 		    break;	/* .. */
443*404b540aSrobert 		  c++;
444*404b540aSrobert 		  if (*c != 'n' && *c != 'N')
445*404b540aSrobert 		    break;	/* .. */
446*404b540aSrobert 		  c++;
447*404b540aSrobert 		  /* now nothing, or nnnn, expected */
448*404b540aSrobert 		  /* -> start of integer and skip leading 0s [including plain 0] */
449*404b540aSrobert 		  for (cfirst = c; *cfirst == '0';)
450*404b540aSrobert 		    cfirst++;
451*404b540aSrobert 		  if (*cfirst == '\0')
452*404b540aSrobert 		    {		/* "NaN" or "sNaN", maybe with all 0s */
453*404b540aSrobert 		      status = 0;	/* it's good */
454*404b540aSrobert 		      break;	/* .. */
455*404b540aSrobert 		    }
456*404b540aSrobert 		  /* something other than 0s; setup last and d as usual [no dots] */
457*404b540aSrobert 		  for (c = cfirst;; c++, d++)
458*404b540aSrobert 		    {
459*404b540aSrobert 		      if (*c < '0' || *c > '9')
460*404b540aSrobert 			break;	/* test for Arabic digit */
461*404b540aSrobert 		      last = c;
462*404b540aSrobert 		    }
463*404b540aSrobert 		  if (*c != '\0')
464*404b540aSrobert 		    break;	/* not all digits */
465*404b540aSrobert 		  if (d > set->digits)
466*404b540aSrobert 		    break;	/* too many digits */
467*404b540aSrobert 		  /* good; drop through and convert the integer */
468*404b540aSrobert 		  status = 0;
469*404b540aSrobert 		  bits = dn->bits;	/* for copy-back */
470*404b540aSrobert 		}		/* NaN expected */
471*404b540aSrobert #if DECSUBSET
472*404b540aSrobert 	    }
473*404b540aSrobert #endif
474*404b540aSrobert 	}			/* last==NULL */
475*404b540aSrobert 
476*404b540aSrobert       if (*c != '\0')
477*404b540aSrobert 	{			/* more there; exponent expected... */
478*404b540aSrobert 	  Flag nege = 0;	/* 1=negative exponent */
479*404b540aSrobert 	  if (*c != 'e' && *c != 'E')
480*404b540aSrobert 	    {
481*404b540aSrobert 	      status = DEC_Conversion_syntax;
482*404b540aSrobert 	      break;
483*404b540aSrobert 	    }
484*404b540aSrobert 
485*404b540aSrobert 	  /* Found 'e' or 'E' -- now process explicit exponent */
486*404b540aSrobert 	  /* 1998.07.11: sign no longer required */
487*404b540aSrobert 	  c++;			/* to (expected) sign */
488*404b540aSrobert 	  if (*c == '-')
489*404b540aSrobert 	    {
490*404b540aSrobert 	      nege = 1;
491*404b540aSrobert 	      c++;
492*404b540aSrobert 	    }
493*404b540aSrobert 	  else if (*c == '+')
494*404b540aSrobert 	    c++;
495*404b540aSrobert 	  if (*c == '\0')
496*404b540aSrobert 	    {
497*404b540aSrobert 	      status = DEC_Conversion_syntax;
498*404b540aSrobert 	      break;
499*404b540aSrobert 	    }
500*404b540aSrobert 
501*404b540aSrobert 	  for (; *c == '0' && *(c + 1) != '\0';)
502*404b540aSrobert 	    c++;		/* strip insignificant zeros */
503*404b540aSrobert 	  firstexp = c;		/* save exponent digit place */
504*404b540aSrobert 	  for (;; c++)
505*404b540aSrobert 	    {
506*404b540aSrobert 	      if (*c < '0' || *c > '9')
507*404b540aSrobert 		break;		/* not a digit */
508*404b540aSrobert 	      exponent = X10 (exponent) + (Int) * c - (Int) '0';
509*404b540aSrobert 	    }			/* c */
510*404b540aSrobert 	  /* if we didn't end on '\0' must not be a digit */
511*404b540aSrobert 	  if (*c != '\0')
512*404b540aSrobert 	    {
513*404b540aSrobert 	      status = DEC_Conversion_syntax;
514*404b540aSrobert 	      break;
515*404b540aSrobert 	    }
516*404b540aSrobert 
517*404b540aSrobert 	  /* (this next test must be after the syntax check) */
518*404b540aSrobert 	  /* if it was too long the exponent may have wrapped, so check */
519*404b540aSrobert 	  /* carefully and set it to a certain overflow if wrap possible */
520*404b540aSrobert 	  if (c >= firstexp + 9 + 1)
521*404b540aSrobert 	    {
522*404b540aSrobert 	      if (c > firstexp + 9 + 1 || *firstexp > '1')
523*404b540aSrobert 		exponent = DECNUMMAXE * 2;
524*404b540aSrobert 	      /* [up to 1999999999 is OK, for example 1E-1000000998] */
525*404b540aSrobert 	    }
526*404b540aSrobert 	  if (nege)
527*404b540aSrobert 	    exponent = -exponent;	/* was negative */
528*404b540aSrobert 	}			/* had exponent */
529*404b540aSrobert       /* Here when all inspected; syntax is good */
530*404b540aSrobert 
531*404b540aSrobert       /* Handle decimal point... */
532*404b540aSrobert       if (dotchar != NULL && dotchar < last)	/* embedded . found, so */
533*404b540aSrobert 	exponent = exponent - (last - dotchar);	/* .. adjust exponent */
534*404b540aSrobert       /* [we can now ignore the .] */
535*404b540aSrobert 
536*404b540aSrobert       /* strip leading zeros/dot (leave final if all 0's) */
537*404b540aSrobert       for (c = cfirst; c < last; c++)
538*404b540aSrobert 	{
539*404b540aSrobert 	  if (*c == '0')
540*404b540aSrobert 	    d--;		/* 0 stripped */
541*404b540aSrobert 	  else if (*c != '.')
542*404b540aSrobert 	    break;
543*404b540aSrobert 	  cfirst++;		/* step past leader */
544*404b540aSrobert 	}			/* c */
545*404b540aSrobert 
546*404b540aSrobert #if DECSUBSET
547*404b540aSrobert       /* We can now make a rapid exit for zeros if !extended */
548*404b540aSrobert       if (*cfirst == '0' && !set->extended)
549*404b540aSrobert 	{
550*404b540aSrobert 	  decNumberZero (dn);	/* clean result */
551*404b540aSrobert 	  break;		/* [could be return] */
552*404b540aSrobert 	}
553*404b540aSrobert #endif
554*404b540aSrobert 
555*404b540aSrobert       /* OK, the digits string is good.  Copy to the decNumber, or to
556*404b540aSrobert          a temporary decNumber if rounding is needed */
557*404b540aSrobert       if (d <= set->digits)
558*404b540aSrobert 	res = dn->lsu;		/* fits into given decNumber */
559*404b540aSrobert       else
560*404b540aSrobert 	{			/* rounding needed */
561*404b540aSrobert 	  need = D2U (d);	/* units needed */
562*404b540aSrobert 	  res = resbuff;	/* assume use local buffer */
563*404b540aSrobert 	  if (need * sizeof (Unit) > sizeof (resbuff))
564*404b540aSrobert 	    {			/* too big for local */
565*404b540aSrobert 	      allocres = (Unit *) malloc (need * sizeof (Unit));
566*404b540aSrobert 	      if (allocres == NULL)
567*404b540aSrobert 		{
568*404b540aSrobert 		  status |= DEC_Insufficient_storage;
569*404b540aSrobert 		  break;
570*404b540aSrobert 		}
571*404b540aSrobert 	      res = allocres;
572*404b540aSrobert 	    }
573*404b540aSrobert 	}
574*404b540aSrobert       /* res now -> number lsu, buffer, or allocated storage for Unit array */
575*404b540aSrobert 
576*404b540aSrobert       /* Place the coefficient into the selected Unit array */
577*404b540aSrobert #if DECDPUN>1
578*404b540aSrobert       i = d % DECDPUN;		/* digits in top unit */
579*404b540aSrobert       if (i == 0)
580*404b540aSrobert 	i = DECDPUN;
581*404b540aSrobert       up = res + D2U (d) - 1;	/* -> msu */
582*404b540aSrobert       *up = 0;
583*404b540aSrobert       for (c = cfirst;; c++)
584*404b540aSrobert 	{			/* along the digits */
585*404b540aSrobert 	  if (*c == '.')
586*404b540aSrobert 	    {			/* ignore . [don't decrement i] */
587*404b540aSrobert 	      if (c != last)
588*404b540aSrobert 		continue;
589*404b540aSrobert 	      break;
590*404b540aSrobert 	    }
591*404b540aSrobert 	  *up = (Unit) (X10 (*up) + (Int) * c - (Int) '0');
592*404b540aSrobert 	  i--;
593*404b540aSrobert 	  if (i > 0)
594*404b540aSrobert 	    continue;		/* more for this unit */
595*404b540aSrobert 	  if (up == res)
596*404b540aSrobert 	    break;		/* just filled the last unit */
597*404b540aSrobert 	  i = DECDPUN;
598*404b540aSrobert 	  up--;
599*404b540aSrobert 	  *up = 0;
600*404b540aSrobert 	}			/* c */
601*404b540aSrobert #else
602*404b540aSrobert       /* DECDPUN==1 */
603*404b540aSrobert       up = res;			/* -> lsu */
604*404b540aSrobert       for (c = last; c >= cfirst; c--)
605*404b540aSrobert 	{			/* over each character, from least */
606*404b540aSrobert 	  if (*c == '.')
607*404b540aSrobert 	    continue;		/* ignore . [don't step b] */
608*404b540aSrobert 	  *up = (Unit) ((Int) * c - (Int) '0');
609*404b540aSrobert 	  up++;
610*404b540aSrobert 	}			/* c */
611*404b540aSrobert #endif
612*404b540aSrobert 
613*404b540aSrobert       dn->bits = bits;
614*404b540aSrobert       dn->exponent = exponent;
615*404b540aSrobert       dn->digits = d;
616*404b540aSrobert 
617*404b540aSrobert       /* if not in number (too long) shorten into the number */
618*404b540aSrobert       if (d > set->digits)
619*404b540aSrobert 	decSetCoeff (dn, set, res, d, &residue, &status);
620*404b540aSrobert 
621*404b540aSrobert       /* Finally check for overflow or subnormal and round as needed */
622*404b540aSrobert       decFinalize (dn, set, &residue, &status);
623*404b540aSrobert       /* decNumberShow(dn); */
624*404b540aSrobert     }
625*404b540aSrobert   while (0);			/* [for break] */
626*404b540aSrobert 
627*404b540aSrobert   if (allocres != NULL)
628*404b540aSrobert     free (allocres);		/* drop any storage we used */
629*404b540aSrobert   if (status != 0)
630*404b540aSrobert     decStatus (dn, status, set);
631*404b540aSrobert   return dn;
632*404b540aSrobert }
633*404b540aSrobert 
634*404b540aSrobert /* ================================================================== */
635*404b540aSrobert /* Operators                                                          */
636*404b540aSrobert /* ================================================================== */
637*404b540aSrobert 
638*404b540aSrobert /* ------------------------------------------------------------------ */
639*404b540aSrobert /* decNumberAbs -- absolute value operator                            */
640*404b540aSrobert /*                                                                    */
641*404b540aSrobert /*   This computes C = abs(A)                                         */
642*404b540aSrobert /*                                                                    */
643*404b540aSrobert /*   res is C, the result.  C may be A                                */
644*404b540aSrobert /*   rhs is A                                                         */
645*404b540aSrobert /*   set is the context                                               */
646*404b540aSrobert /*                                                                    */
647*404b540aSrobert /* C must have space for set->digits digits.                          */
648*404b540aSrobert /* ------------------------------------------------------------------ */
649*404b540aSrobert /* This has the same effect as decNumberPlus unless A is negative,    */
650*404b540aSrobert /* in which case it has the same effect as decNumberMinus.            */
651*404b540aSrobert /* ------------------------------------------------------------------ */
652*404b540aSrobert decNumber *
decNumberAbs(decNumber * res,const decNumber * rhs,decContext * set)653*404b540aSrobert decNumberAbs (decNumber * res, const decNumber * rhs, decContext * set)
654*404b540aSrobert {
655*404b540aSrobert   decNumber dzero;		/* for 0 */
656*404b540aSrobert   uInt status = 0;		/* accumulator */
657*404b540aSrobert 
658*404b540aSrobert #if DECCHECK
659*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
660*404b540aSrobert     return res;
661*404b540aSrobert #endif
662*404b540aSrobert 
663*404b540aSrobert   decNumberZero (&dzero);	/* set 0 */
664*404b540aSrobert   dzero.exponent = rhs->exponent;	/* [no coefficient expansion] */
665*404b540aSrobert   decAddOp (res, &dzero, rhs, set, (uByte) (rhs->bits & DECNEG), &status);
666*404b540aSrobert   if (status != 0)
667*404b540aSrobert     decStatus (res, status, set);
668*404b540aSrobert   return res;
669*404b540aSrobert }
670*404b540aSrobert 
671*404b540aSrobert /* ------------------------------------------------------------------ */
672*404b540aSrobert /* decNumberAdd -- add two Numbers                                    */
673*404b540aSrobert /*                                                                    */
674*404b540aSrobert /*   This computes C = A + B                                          */
675*404b540aSrobert /*                                                                    */
676*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
677*404b540aSrobert /*   lhs is A                                                         */
678*404b540aSrobert /*   rhs is B                                                         */
679*404b540aSrobert /*   set is the context                                               */
680*404b540aSrobert /*                                                                    */
681*404b540aSrobert /* C must have space for set->digits digits.                          */
682*404b540aSrobert /* ------------------------------------------------------------------ */
683*404b540aSrobert /* This just calls the routine shared with Subtract                   */
684*404b540aSrobert decNumber *
decNumberAdd(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)685*404b540aSrobert decNumberAdd (decNumber * res, const decNumber * lhs,
686*404b540aSrobert 	      const decNumber * rhs, decContext * set)
687*404b540aSrobert {
688*404b540aSrobert   uInt status = 0;		/* accumulator */
689*404b540aSrobert   decAddOp (res, lhs, rhs, set, 0, &status);
690*404b540aSrobert   if (status != 0)
691*404b540aSrobert     decStatus (res, status, set);
692*404b540aSrobert   return res;
693*404b540aSrobert }
694*404b540aSrobert 
695*404b540aSrobert /* ------------------------------------------------------------------ */
696*404b540aSrobert /* decNumberCompare -- compare two Numbers                            */
697*404b540aSrobert /*                                                                    */
698*404b540aSrobert /*   This computes C = A ? B                                          */
699*404b540aSrobert /*                                                                    */
700*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
701*404b540aSrobert /*   lhs is A                                                         */
702*404b540aSrobert /*   rhs is B                                                         */
703*404b540aSrobert /*   set is the context                                               */
704*404b540aSrobert /*                                                                    */
705*404b540aSrobert /* C must have space for one digit.                                   */
706*404b540aSrobert /* ------------------------------------------------------------------ */
707*404b540aSrobert decNumber *
decNumberCompare(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)708*404b540aSrobert decNumberCompare (decNumber * res, const decNumber * lhs,
709*404b540aSrobert 		  const decNumber * rhs, decContext * set)
710*404b540aSrobert {
711*404b540aSrobert   uInt status = 0;		/* accumulator */
712*404b540aSrobert   decCompareOp (res, lhs, rhs, set, COMPARE, &status);
713*404b540aSrobert   if (status != 0)
714*404b540aSrobert     decStatus (res, status, set);
715*404b540aSrobert   return res;
716*404b540aSrobert }
717*404b540aSrobert 
718*404b540aSrobert /* ------------------------------------------------------------------ */
719*404b540aSrobert /* decNumberDivide -- divide one number by another                    */
720*404b540aSrobert /*                                                                    */
721*404b540aSrobert /*   This computes C = A / B                                          */
722*404b540aSrobert /*                                                                    */
723*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
724*404b540aSrobert /*   lhs is A                                                         */
725*404b540aSrobert /*   rhs is B                                                         */
726*404b540aSrobert /*   set is the context                                               */
727*404b540aSrobert /*                                                                    */
728*404b540aSrobert /* C must have space for set->digits digits.                          */
729*404b540aSrobert /* ------------------------------------------------------------------ */
730*404b540aSrobert decNumber *
decNumberDivide(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)731*404b540aSrobert decNumberDivide (decNumber * res, const decNumber * lhs,
732*404b540aSrobert 		 const decNumber * rhs, decContext * set)
733*404b540aSrobert {
734*404b540aSrobert   uInt status = 0;		/* accumulator */
735*404b540aSrobert   decDivideOp (res, lhs, rhs, set, DIVIDE, &status);
736*404b540aSrobert   if (status != 0)
737*404b540aSrobert     decStatus (res, status, set);
738*404b540aSrobert   return res;
739*404b540aSrobert }
740*404b540aSrobert 
741*404b540aSrobert /* ------------------------------------------------------------------ */
742*404b540aSrobert /* decNumberDivideInteger -- divide and return integer quotient       */
743*404b540aSrobert /*                                                                    */
744*404b540aSrobert /*   This computes C = A # B, where # is the integer divide operator  */
745*404b540aSrobert /*                                                                    */
746*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
747*404b540aSrobert /*   lhs is A                                                         */
748*404b540aSrobert /*   rhs is B                                                         */
749*404b540aSrobert /*   set is the context                                               */
750*404b540aSrobert /*                                                                    */
751*404b540aSrobert /* C must have space for set->digits digits.                          */
752*404b540aSrobert /* ------------------------------------------------------------------ */
753*404b540aSrobert decNumber *
decNumberDivideInteger(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)754*404b540aSrobert decNumberDivideInteger (decNumber * res, const decNumber * lhs,
755*404b540aSrobert 			const decNumber * rhs, decContext * set)
756*404b540aSrobert {
757*404b540aSrobert   uInt status = 0;		/* accumulator */
758*404b540aSrobert   decDivideOp (res, lhs, rhs, set, DIVIDEINT, &status);
759*404b540aSrobert   if (status != 0)
760*404b540aSrobert     decStatus (res, status, set);
761*404b540aSrobert   return res;
762*404b540aSrobert }
763*404b540aSrobert 
764*404b540aSrobert /* ------------------------------------------------------------------ */
765*404b540aSrobert /* decNumberMax -- compare two Numbers and return the maximum         */
766*404b540aSrobert /*                                                                    */
767*404b540aSrobert /*   This computes C = A ? B, returning the maximum or A if equal     */
768*404b540aSrobert /*                                                                    */
769*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
770*404b540aSrobert /*   lhs is A                                                         */
771*404b540aSrobert /*   rhs is B                                                         */
772*404b540aSrobert /*   set is the context                                               */
773*404b540aSrobert /*                                                                    */
774*404b540aSrobert /* C must have space for set->digits digits.                          */
775*404b540aSrobert /* ------------------------------------------------------------------ */
776*404b540aSrobert decNumber *
decNumberMax(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)777*404b540aSrobert decNumberMax (decNumber * res, const decNumber * lhs,
778*404b540aSrobert 	      const decNumber * rhs, decContext * set)
779*404b540aSrobert {
780*404b540aSrobert   uInt status = 0;		/* accumulator */
781*404b540aSrobert   decCompareOp (res, lhs, rhs, set, COMPMAX, &status);
782*404b540aSrobert   if (status != 0)
783*404b540aSrobert     decStatus (res, status, set);
784*404b540aSrobert   return res;
785*404b540aSrobert }
786*404b540aSrobert 
787*404b540aSrobert /* ------------------------------------------------------------------ */
788*404b540aSrobert /* decNumberMin -- compare two Numbers and return the minimum         */
789*404b540aSrobert /*                                                                    */
790*404b540aSrobert /*   This computes C = A ? B, returning the minimum or A if equal     */
791*404b540aSrobert /*                                                                    */
792*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
793*404b540aSrobert /*   lhs is A                                                         */
794*404b540aSrobert /*   rhs is B                                                         */
795*404b540aSrobert /*   set is the context                                               */
796*404b540aSrobert /*                                                                    */
797*404b540aSrobert /* C must have space for set->digits digits.                          */
798*404b540aSrobert /* ------------------------------------------------------------------ */
799*404b540aSrobert decNumber *
decNumberMin(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)800*404b540aSrobert decNumberMin (decNumber * res, const decNumber * lhs,
801*404b540aSrobert 	      const decNumber * rhs, decContext * set)
802*404b540aSrobert {
803*404b540aSrobert   uInt status = 0;		/* accumulator */
804*404b540aSrobert   decCompareOp (res, lhs, rhs, set, COMPMIN, &status);
805*404b540aSrobert   if (status != 0)
806*404b540aSrobert     decStatus (res, status, set);
807*404b540aSrobert   return res;
808*404b540aSrobert }
809*404b540aSrobert 
810*404b540aSrobert /* ------------------------------------------------------------------ */
811*404b540aSrobert /* decNumberMinus -- prefix minus operator                            */
812*404b540aSrobert /*                                                                    */
813*404b540aSrobert /*   This computes C = 0 - A                                          */
814*404b540aSrobert /*                                                                    */
815*404b540aSrobert /*   res is C, the result.  C may be A                                */
816*404b540aSrobert /*   rhs is A                                                         */
817*404b540aSrobert /*   set is the context                                               */
818*404b540aSrobert /*                                                                    */
819*404b540aSrobert /* C must have space for set->digits digits.                          */
820*404b540aSrobert /* ------------------------------------------------------------------ */
821*404b540aSrobert /* We simply use AddOp for the subtract, which will do the necessary. */
822*404b540aSrobert /* ------------------------------------------------------------------ */
823*404b540aSrobert decNumber *
decNumberMinus(decNumber * res,const decNumber * rhs,decContext * set)824*404b540aSrobert decNumberMinus (decNumber * res, const decNumber * rhs, decContext * set)
825*404b540aSrobert {
826*404b540aSrobert   decNumber dzero;
827*404b540aSrobert   uInt status = 0;		/* accumulator */
828*404b540aSrobert 
829*404b540aSrobert #if DECCHECK
830*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
831*404b540aSrobert     return res;
832*404b540aSrobert #endif
833*404b540aSrobert 
834*404b540aSrobert   decNumberZero (&dzero);	/* make 0 */
835*404b540aSrobert   dzero.exponent = rhs->exponent;	/* [no coefficient expansion] */
836*404b540aSrobert   decAddOp (res, &dzero, rhs, set, DECNEG, &status);
837*404b540aSrobert   if (status != 0)
838*404b540aSrobert     decStatus (res, status, set);
839*404b540aSrobert   return res;
840*404b540aSrobert }
841*404b540aSrobert 
842*404b540aSrobert /* ------------------------------------------------------------------ */
843*404b540aSrobert /* decNumberPlus -- prefix plus operator                              */
844*404b540aSrobert /*                                                                    */
845*404b540aSrobert /*   This computes C = 0 + A                                          */
846*404b540aSrobert /*                                                                    */
847*404b540aSrobert /*   res is C, the result.  C may be A                                */
848*404b540aSrobert /*   rhs is A                                                         */
849*404b540aSrobert /*   set is the context                                               */
850*404b540aSrobert /*                                                                    */
851*404b540aSrobert /* C must have space for set->digits digits.                          */
852*404b540aSrobert /* ------------------------------------------------------------------ */
853*404b540aSrobert /* We simply use AddOp; Add will take fast path after preparing A.    */
854*404b540aSrobert /* Performance is a concern here, as this routine is often used to    */
855*404b540aSrobert /* check operands and apply rounding and overflow/underflow testing.  */
856*404b540aSrobert /* ------------------------------------------------------------------ */
857*404b540aSrobert decNumber *
decNumberPlus(decNumber * res,const decNumber * rhs,decContext * set)858*404b540aSrobert decNumberPlus (decNumber * res, const decNumber * rhs, decContext * set)
859*404b540aSrobert {
860*404b540aSrobert   decNumber dzero;
861*404b540aSrobert   uInt status = 0;		/* accumulator */
862*404b540aSrobert 
863*404b540aSrobert #if DECCHECK
864*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
865*404b540aSrobert     return res;
866*404b540aSrobert #endif
867*404b540aSrobert 
868*404b540aSrobert   decNumberZero (&dzero);	/* make 0 */
869*404b540aSrobert   dzero.exponent = rhs->exponent;	/* [no coefficient expansion] */
870*404b540aSrobert   decAddOp (res, &dzero, rhs, set, 0, &status);
871*404b540aSrobert   if (status != 0)
872*404b540aSrobert     decStatus (res, status, set);
873*404b540aSrobert   return res;
874*404b540aSrobert }
875*404b540aSrobert 
876*404b540aSrobert /* ------------------------------------------------------------------ */
877*404b540aSrobert /* decNumberMultiply -- multiply two Numbers                          */
878*404b540aSrobert /*                                                                    */
879*404b540aSrobert /*   This computes C = A x B                                          */
880*404b540aSrobert /*                                                                    */
881*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
882*404b540aSrobert /*   lhs is A                                                         */
883*404b540aSrobert /*   rhs is B                                                         */
884*404b540aSrobert /*   set is the context                                               */
885*404b540aSrobert /*                                                                    */
886*404b540aSrobert /* C must have space for set->digits digits.                          */
887*404b540aSrobert /* ------------------------------------------------------------------ */
888*404b540aSrobert decNumber *
decNumberMultiply(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)889*404b540aSrobert decNumberMultiply (decNumber * res, const decNumber * lhs,
890*404b540aSrobert 		   const decNumber * rhs, decContext * set)
891*404b540aSrobert {
892*404b540aSrobert   uInt status = 0;		/* accumulator */
893*404b540aSrobert   decMultiplyOp (res, lhs, rhs, set, &status);
894*404b540aSrobert   if (status != 0)
895*404b540aSrobert     decStatus (res, status, set);
896*404b540aSrobert   return res;
897*404b540aSrobert }
898*404b540aSrobert 
899*404b540aSrobert /* ------------------------------------------------------------------ */
900*404b540aSrobert /* decNumberNormalize -- remove trailing zeros                        */
901*404b540aSrobert /*                                                                    */
902*404b540aSrobert /*   This computes C = 0 + A, and normalizes the result               */
903*404b540aSrobert /*                                                                    */
904*404b540aSrobert /*   res is C, the result.  C may be A                                */
905*404b540aSrobert /*   rhs is A                                                         */
906*404b540aSrobert /*   set is the context                                               */
907*404b540aSrobert /*                                                                    */
908*404b540aSrobert /* C must have space for set->digits digits.                          */
909*404b540aSrobert /* ------------------------------------------------------------------ */
910*404b540aSrobert decNumber *
decNumberNormalize(decNumber * res,const decNumber * rhs,decContext * set)911*404b540aSrobert decNumberNormalize (decNumber * res, const decNumber * rhs, decContext * set)
912*404b540aSrobert {
913*404b540aSrobert   decNumber *allocrhs = NULL;	/* non-NULL if rounded rhs allocated */
914*404b540aSrobert   uInt status = 0;		/* as usual */
915*404b540aSrobert   Int residue = 0;		/* as usual */
916*404b540aSrobert   Int dropped;			/* work */
917*404b540aSrobert 
918*404b540aSrobert #if DECCHECK
919*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
920*404b540aSrobert     return res;
921*404b540aSrobert #endif
922*404b540aSrobert 
923*404b540aSrobert   do
924*404b540aSrobert     {				/* protect allocated storage */
925*404b540aSrobert #if DECSUBSET
926*404b540aSrobert       if (!set->extended)
927*404b540aSrobert 	{
928*404b540aSrobert 	  /* reduce operand and set lostDigits status, as needed */
929*404b540aSrobert 	  if (rhs->digits > set->digits)
930*404b540aSrobert 	    {
931*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, &status);
932*404b540aSrobert 	      if (allocrhs == NULL)
933*404b540aSrobert 		break;
934*404b540aSrobert 	      rhs = allocrhs;
935*404b540aSrobert 	    }
936*404b540aSrobert 	}
937*404b540aSrobert #endif
938*404b540aSrobert       /* [following code does not require input rounding] */
939*404b540aSrobert 
940*404b540aSrobert       /* specials copy through, except NaNs need care */
941*404b540aSrobert       if (decNumberIsNaN (rhs))
942*404b540aSrobert 	{
943*404b540aSrobert 	  decNaNs (res, rhs, NULL, &status);
944*404b540aSrobert 	  break;
945*404b540aSrobert 	}
946*404b540aSrobert 
947*404b540aSrobert       /* reduce result to the requested length and copy to result */
948*404b540aSrobert       decCopyFit (res, rhs, set, &residue, &status);	/* copy & round */
949*404b540aSrobert       decFinish (res, set, &residue, &status);	/* cleanup/set flags */
950*404b540aSrobert       decTrim (res, 1, &dropped);	/* normalize in place */
951*404b540aSrobert     }
952*404b540aSrobert   while (0);			/* end protected */
953*404b540aSrobert 
954*404b540aSrobert   if (allocrhs != NULL)
955*404b540aSrobert     free (allocrhs);		/* .. */
956*404b540aSrobert   if (status != 0)
957*404b540aSrobert     decStatus (res, status, set);	/* then report status */
958*404b540aSrobert   return res;
959*404b540aSrobert }
960*404b540aSrobert 
961*404b540aSrobert /* ------------------------------------------------------------------ */
962*404b540aSrobert /* decNumberPower -- raise a number to an integer power               */
963*404b540aSrobert /*                                                                    */
964*404b540aSrobert /*   This computes C = A ** B                                         */
965*404b540aSrobert /*                                                                    */
966*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
967*404b540aSrobert /*   lhs is A                                                         */
968*404b540aSrobert /*   rhs is B                                                         */
969*404b540aSrobert /*   set is the context                                               */
970*404b540aSrobert /*                                                                    */
971*404b540aSrobert /* C must have space for set->digits digits.                          */
972*404b540aSrobert /*                                                                    */
973*404b540aSrobert /* Specification restriction: abs(n) must be <=999999999              */
974*404b540aSrobert /* ------------------------------------------------------------------ */
975*404b540aSrobert decNumber *
decNumberPower(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)976*404b540aSrobert decNumberPower (decNumber * res, const decNumber * lhs,
977*404b540aSrobert 		const decNumber * rhs, decContext * set)
978*404b540aSrobert {
979*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
980*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
981*404b540aSrobert   decNumber *allocdac = NULL;	/* -> allocated acc buffer, iff used */
982*404b540aSrobert   const decNumber *inrhs = rhs;	/* save original rhs */
983*404b540aSrobert   Int reqdigits = set->digits;	/* requested DIGITS */
984*404b540aSrobert   Int n;			/* RHS in binary */
985*404b540aSrobert   Int i;			/* work */
986*404b540aSrobert #if DECSUBSET
987*404b540aSrobert   Int dropped;			/* .. */
988*404b540aSrobert #endif
989*404b540aSrobert   uInt needbytes;		/* buffer size needed */
990*404b540aSrobert   Flag seenbit;			/* seen a bit while powering */
991*404b540aSrobert   Int residue = 0;		/* rounding residue */
992*404b540aSrobert   uInt status = 0;		/* accumulator */
993*404b540aSrobert   uByte bits = 0;		/* result sign if errors */
994*404b540aSrobert   decContext workset;		/* working context */
995*404b540aSrobert   decNumber dnOne;		/* work value 1... */
996*404b540aSrobert   /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
997*404b540aSrobert   uByte dacbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
998*404b540aSrobert   /* same again for possible 1/lhs calculation */
999*404b540aSrobert   uByte lhsbuff[sizeof (decNumber) + D2U (DECBUFFER + 9) * sizeof (Unit)];
1000*404b540aSrobert   decNumber *dac = (decNumber *) dacbuff;	/* -> result accumulator */
1001*404b540aSrobert 
1002*404b540aSrobert #if DECCHECK
1003*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
1004*404b540aSrobert     return res;
1005*404b540aSrobert #endif
1006*404b540aSrobert 
1007*404b540aSrobert   do
1008*404b540aSrobert     {				/* protect allocated storage */
1009*404b540aSrobert #if DECSUBSET
1010*404b540aSrobert       if (!set->extended)
1011*404b540aSrobert 	{
1012*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
1013*404b540aSrobert 	  if (lhs->digits > reqdigits)
1014*404b540aSrobert 	    {
1015*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, &status);
1016*404b540aSrobert 	      if (alloclhs == NULL)
1017*404b540aSrobert 		break;
1018*404b540aSrobert 	      lhs = alloclhs;
1019*404b540aSrobert 	    }
1020*404b540aSrobert 	  /* rounding won't affect the result, but we might signal lostDigits */
1021*404b540aSrobert 	  /* as well as the error for non-integer [x**y would need this too] */
1022*404b540aSrobert 	  if (rhs->digits > reqdigits)
1023*404b540aSrobert 	    {
1024*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, &status);
1025*404b540aSrobert 	      if (allocrhs == NULL)
1026*404b540aSrobert 		break;
1027*404b540aSrobert 	      rhs = allocrhs;
1028*404b540aSrobert 	    }
1029*404b540aSrobert 	}
1030*404b540aSrobert #endif
1031*404b540aSrobert       /* [following code does not require input rounding] */
1032*404b540aSrobert 
1033*404b540aSrobert       /* handle rhs Infinity */
1034*404b540aSrobert       if (decNumberIsInfinite (rhs))
1035*404b540aSrobert 	{
1036*404b540aSrobert 	  status |= DEC_Invalid_operation;	/* bad */
1037*404b540aSrobert 	  break;
1038*404b540aSrobert 	}
1039*404b540aSrobert       /* handle NaNs */
1040*404b540aSrobert       if ((lhs->bits | rhs->bits) & (DECNAN | DECSNAN))
1041*404b540aSrobert 	{
1042*404b540aSrobert 	  decNaNs (res, lhs, rhs, &status);
1043*404b540aSrobert 	  break;
1044*404b540aSrobert 	}
1045*404b540aSrobert 
1046*404b540aSrobert       /* Original rhs must be an integer that fits and is in range */
1047*404b540aSrobert #if DECSUBSET
1048*404b540aSrobert       n = decGetInt (inrhs, set);
1049*404b540aSrobert #else
1050*404b540aSrobert       n = decGetInt (inrhs);
1051*404b540aSrobert #endif
1052*404b540aSrobert       if (n == BADINT || n > 999999999 || n < -999999999)
1053*404b540aSrobert 	{
1054*404b540aSrobert 	  status |= DEC_Invalid_operation;
1055*404b540aSrobert 	  break;
1056*404b540aSrobert 	}
1057*404b540aSrobert       if (n < 0)
1058*404b540aSrobert 	{			/* negative */
1059*404b540aSrobert 	  n = -n;		/* use the absolute value */
1060*404b540aSrobert 	}
1061*404b540aSrobert       if (decNumberIsNegative (lhs)	/* -x .. */
1062*404b540aSrobert 	  && (n & 0x00000001))
1063*404b540aSrobert 	bits = DECNEG;		/* .. to an odd power */
1064*404b540aSrobert 
1065*404b540aSrobert       /* handle LHS infinity */
1066*404b540aSrobert       if (decNumberIsInfinite (lhs))
1067*404b540aSrobert 	{			/* [NaNs already handled] */
1068*404b540aSrobert 	  uByte rbits = rhs->bits;	/* save */
1069*404b540aSrobert 	  decNumberZero (res);
1070*404b540aSrobert 	  if (n == 0)
1071*404b540aSrobert 	    *res->lsu = 1;	/* [-]Inf**0 => 1 */
1072*404b540aSrobert 	  else
1073*404b540aSrobert 	    {
1074*404b540aSrobert 	      if (!(rbits & DECNEG))
1075*404b540aSrobert 		bits |= DECINF;	/* was not a **-n */
1076*404b540aSrobert 	      /* [otherwise will be 0 or -0] */
1077*404b540aSrobert 	      res->bits = bits;
1078*404b540aSrobert 	    }
1079*404b540aSrobert 	  break;
1080*404b540aSrobert 	}
1081*404b540aSrobert 
1082*404b540aSrobert       /* clone the context */
1083*404b540aSrobert       workset = *set;		/* copy all fields */
1084*404b540aSrobert       /* calculate the working DIGITS */
1085*404b540aSrobert       workset.digits = reqdigits + (inrhs->digits + inrhs->exponent) + 1;
1086*404b540aSrobert       /* it's an error if this is more than we can handle */
1087*404b540aSrobert       if (workset.digits > DECNUMMAXP)
1088*404b540aSrobert 	{
1089*404b540aSrobert 	  status |= DEC_Invalid_operation;
1090*404b540aSrobert 	  break;
1091*404b540aSrobert 	}
1092*404b540aSrobert 
1093*404b540aSrobert       /* workset.digits is the count of digits for the accumulator we need */
1094*404b540aSrobert       /* if accumulator is too long for local storage, then allocate */
1095*404b540aSrobert       needbytes =
1096*404b540aSrobert 	sizeof (decNumber) + (D2U (workset.digits) - 1) * sizeof (Unit);
1097*404b540aSrobert       /* [needbytes also used below if 1/lhs needed] */
1098*404b540aSrobert       if (needbytes > sizeof (dacbuff))
1099*404b540aSrobert 	{
1100*404b540aSrobert 	  allocdac = (decNumber *) malloc (needbytes);
1101*404b540aSrobert 	  if (allocdac == NULL)
1102*404b540aSrobert 	    {			/* hopeless -- abandon */
1103*404b540aSrobert 	      status |= DEC_Insufficient_storage;
1104*404b540aSrobert 	      break;
1105*404b540aSrobert 	    }
1106*404b540aSrobert 	  dac = allocdac;	/* use the allocated space */
1107*404b540aSrobert 	}
1108*404b540aSrobert       decNumberZero (dac);	/* acc=1 */
1109*404b540aSrobert       *dac->lsu = 1;		/* .. */
1110*404b540aSrobert 
1111*404b540aSrobert       if (n == 0)
1112*404b540aSrobert 	{			/* x**0 is usually 1 */
1113*404b540aSrobert 	  /* 0**0 is bad unless subset, when it becomes 1 */
1114*404b540aSrobert 	  if (ISZERO (lhs)
1115*404b540aSrobert #if DECSUBSET
1116*404b540aSrobert 	      && set->extended
1117*404b540aSrobert #endif
1118*404b540aSrobert 	    )
1119*404b540aSrobert 	    status |= DEC_Invalid_operation;
1120*404b540aSrobert 	  else
1121*404b540aSrobert 	    decNumberCopy (res, dac);	/* copy the 1 */
1122*404b540aSrobert 	  break;
1123*404b540aSrobert 	}
1124*404b540aSrobert 
1125*404b540aSrobert       /* if a negative power we'll need the constant 1, and if not subset */
1126*404b540aSrobert       /* we'll invert the lhs now rather than inverting the result later */
1127*404b540aSrobert       if (decNumberIsNegative (rhs))
1128*404b540aSrobert 	{			/* was a **-n [hence digits>0] */
1129*404b540aSrobert 	  decNumber * newlhs;
1130*404b540aSrobert 	  decNumberCopy (&dnOne, dac);	/* dnOne=1;  [needed now or later] */
1131*404b540aSrobert #if DECSUBSET
1132*404b540aSrobert 	  if (set->extended)
1133*404b540aSrobert 	    {			/* need to calculate 1/lhs */
1134*404b540aSrobert #endif
1135*404b540aSrobert 	      /* divide lhs into 1, putting result in dac [dac=1/dac] */
1136*404b540aSrobert 	      decDivideOp (dac, &dnOne, lhs, &workset, DIVIDE, &status);
1137*404b540aSrobert 	      if (alloclhs != NULL)
1138*404b540aSrobert 		{
1139*404b540aSrobert 		  free (alloclhs);	/* done with intermediate */
1140*404b540aSrobert 		  alloclhs = NULL;	/* indicate freed */
1141*404b540aSrobert 		}
1142*404b540aSrobert 	      /* now locate or allocate space for the inverted lhs */
1143*404b540aSrobert 	      if (needbytes > sizeof (lhsbuff))
1144*404b540aSrobert 		{
1145*404b540aSrobert 		  alloclhs = (decNumber *) malloc (needbytes);
1146*404b540aSrobert 		  if (alloclhs == NULL)
1147*404b540aSrobert 		    {		/* hopeless -- abandon */
1148*404b540aSrobert 		      status |= DEC_Insufficient_storage;
1149*404b540aSrobert 		      break;
1150*404b540aSrobert 		    }
1151*404b540aSrobert 		  newlhs = alloclhs;	/* use the allocated space */
1152*404b540aSrobert 		}
1153*404b540aSrobert 	      else
1154*404b540aSrobert 		newlhs = (decNumber *) lhsbuff;	/* use stack storage */
1155*404b540aSrobert 	      /* [lhs now points to buffer or allocated storage] */
1156*404b540aSrobert 	      decNumberCopy (newlhs, dac);	/* copy the 1/lhs */
1157*404b540aSrobert 	      decNumberCopy (dac, &dnOne);	/* restore acc=1 */
1158*404b540aSrobert 	      lhs = newlhs;
1159*404b540aSrobert #if DECSUBSET
1160*404b540aSrobert 	    }
1161*404b540aSrobert #endif
1162*404b540aSrobert 	}
1163*404b540aSrobert 
1164*404b540aSrobert       /* Raise-to-the-power loop... */
1165*404b540aSrobert       seenbit = 0;		/* set once we've seen a 1-bit */
1166*404b540aSrobert       for (i = 1;; i++)
1167*404b540aSrobert 	{			/* for each bit [top bit ignored] */
1168*404b540aSrobert 	  /* abandon if we have had overflow or terminal underflow */
1169*404b540aSrobert 	  if (status & (DEC_Overflow | DEC_Underflow))
1170*404b540aSrobert 	    {			/* interesting? */
1171*404b540aSrobert 	      if (status & DEC_Overflow || ISZERO (dac))
1172*404b540aSrobert 		break;
1173*404b540aSrobert 	    }
1174*404b540aSrobert 	  /* [the following two lines revealed an optimizer bug in a C++ */
1175*404b540aSrobert 	  /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
1176*404b540aSrobert 	  n = n << 1;		/* move next bit to testable position */
1177*404b540aSrobert 	  if (n < 0)
1178*404b540aSrobert 	    {			/* top bit is set */
1179*404b540aSrobert 	      seenbit = 1;	/* OK, we're off */
1180*404b540aSrobert 	      decMultiplyOp (dac, dac, lhs, &workset, &status);	/* dac=dac*x */
1181*404b540aSrobert 	    }
1182*404b540aSrobert 	  if (i == 31)
1183*404b540aSrobert 	    break;		/* that was the last bit */
1184*404b540aSrobert 	  if (!seenbit)
1185*404b540aSrobert 	    continue;		/* we don't have to square 1 */
1186*404b540aSrobert 	  decMultiplyOp (dac, dac, dac, &workset, &status);	/* dac=dac*dac [square] */
1187*404b540aSrobert 	}			/*i *//* 32 bits */
1188*404b540aSrobert 
1189*404b540aSrobert       /* complete internal overflow or underflow processing */
1190*404b540aSrobert       if (status & (DEC_Overflow | DEC_Subnormal))
1191*404b540aSrobert 	{
1192*404b540aSrobert #if DECSUBSET
1193*404b540aSrobert 	  /* If subset, and power was negative, reverse the kind of -erflow */
1194*404b540aSrobert 	  /* [1/x not yet done] */
1195*404b540aSrobert 	  if (!set->extended && decNumberIsNegative (rhs))
1196*404b540aSrobert 	    {
1197*404b540aSrobert 	      if (status & DEC_Overflow)
1198*404b540aSrobert 		status ^= DEC_Overflow | DEC_Underflow | DEC_Subnormal;
1199*404b540aSrobert 	      else
1200*404b540aSrobert 		{		/* trickier -- Underflow may or may not be set */
1201*404b540aSrobert 		  status &= ~(DEC_Underflow | DEC_Subnormal);	/* [one or both] */
1202*404b540aSrobert 		  status |= DEC_Overflow;
1203*404b540aSrobert 		}
1204*404b540aSrobert 	    }
1205*404b540aSrobert #endif
1206*404b540aSrobert 	  dac->bits = (dac->bits & ~DECNEG) | bits;	/* force correct sign */
1207*404b540aSrobert 	  /* round subnormals [to set.digits rather than workset.digits] */
1208*404b540aSrobert 	  /* or set overflow result similarly as required */
1209*404b540aSrobert 	  decFinalize (dac, set, &residue, &status);
1210*404b540aSrobert 	  decNumberCopy (res, dac);	/* copy to result (is now OK length) */
1211*404b540aSrobert 	  break;
1212*404b540aSrobert 	}
1213*404b540aSrobert 
1214*404b540aSrobert #if DECSUBSET
1215*404b540aSrobert       if (!set->extended &&	/* subset math */
1216*404b540aSrobert 	  decNumberIsNegative (rhs))
1217*404b540aSrobert 	{			/* was a **-n [hence digits>0] */
1218*404b540aSrobert 	  /* so divide result into 1 [dac=1/dac] */
1219*404b540aSrobert 	  decDivideOp (dac, &dnOne, dac, &workset, DIVIDE, &status);
1220*404b540aSrobert 	}
1221*404b540aSrobert #endif
1222*404b540aSrobert 
1223*404b540aSrobert       /* reduce result to the requested length and copy to result */
1224*404b540aSrobert       decCopyFit (res, dac, set, &residue, &status);
1225*404b540aSrobert       decFinish (res, set, &residue, &status);	/* final cleanup */
1226*404b540aSrobert #if DECSUBSET
1227*404b540aSrobert       if (!set->extended)
1228*404b540aSrobert 	decTrim (res, 0, &dropped);	/* trailing zeros */
1229*404b540aSrobert #endif
1230*404b540aSrobert     }
1231*404b540aSrobert   while (0);			/* end protected */
1232*404b540aSrobert 
1233*404b540aSrobert   if (allocdac != NULL)
1234*404b540aSrobert     free (allocdac);		/* drop any storage we used */
1235*404b540aSrobert   if (allocrhs != NULL)
1236*404b540aSrobert     free (allocrhs);		/* .. */
1237*404b540aSrobert   if (alloclhs != NULL)
1238*404b540aSrobert     free (alloclhs);		/* .. */
1239*404b540aSrobert   if (status != 0)
1240*404b540aSrobert     decStatus (res, status, set);
1241*404b540aSrobert   return res;
1242*404b540aSrobert }
1243*404b540aSrobert 
1244*404b540aSrobert /* ------------------------------------------------------------------ */
1245*404b540aSrobert /* decNumberQuantize -- force exponent to requested value             */
1246*404b540aSrobert /*                                                                    */
1247*404b540aSrobert /*   This computes C = op(A, B), where op adjusts the coefficient     */
1248*404b540aSrobert /*   of C (by rounding or shifting) such that the exponent (-scale)   */
1249*404b540aSrobert /*   of C has exponent of B.  The numerical value of C will equal A,  */
1250*404b540aSrobert /*   except for the effects of any rounding that occurred.            */
1251*404b540aSrobert /*                                                                    */
1252*404b540aSrobert /*   res is C, the result.  C may be A or B                           */
1253*404b540aSrobert /*   lhs is A, the number to adjust                                   */
1254*404b540aSrobert /*   rhs is B, the number with exponent to match                      */
1255*404b540aSrobert /*   set is the context                                               */
1256*404b540aSrobert /*                                                                    */
1257*404b540aSrobert /* C must have space for set->digits digits.                          */
1258*404b540aSrobert /*                                                                    */
1259*404b540aSrobert /* Unless there is an error or the result is infinite, the exponent   */
1260*404b540aSrobert /* after the operation is guaranteed to be equal to that of B.        */
1261*404b540aSrobert /* ------------------------------------------------------------------ */
1262*404b540aSrobert decNumber *
decNumberQuantize(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1263*404b540aSrobert decNumberQuantize (decNumber * res, const decNumber * lhs,
1264*404b540aSrobert 		   const decNumber * rhs, decContext * set)
1265*404b540aSrobert {
1266*404b540aSrobert   uInt status = 0;		/* accumulator */
1267*404b540aSrobert   decQuantizeOp (res, lhs, rhs, set, 1, &status);
1268*404b540aSrobert   if (status != 0)
1269*404b540aSrobert     decStatus (res, status, set);
1270*404b540aSrobert   return res;
1271*404b540aSrobert }
1272*404b540aSrobert 
1273*404b540aSrobert /* ------------------------------------------------------------------ */
1274*404b540aSrobert /* decNumberRescale -- force exponent to requested value              */
1275*404b540aSrobert /*                                                                    */
1276*404b540aSrobert /*   This computes C = op(A, B), where op adjusts the coefficient     */
1277*404b540aSrobert /*   of C (by rounding or shifting) such that the exponent (-scale)   */
1278*404b540aSrobert /*   of C has the value B.  The numerical value of C will equal A,    */
1279*404b540aSrobert /*   except for the effects of any rounding that occurred.            */
1280*404b540aSrobert /*                                                                    */
1281*404b540aSrobert /*   res is C, the result.  C may be A or B                           */
1282*404b540aSrobert /*   lhs is A, the number to adjust                                   */
1283*404b540aSrobert /*   rhs is B, the requested exponent                                 */
1284*404b540aSrobert /*   set is the context                                               */
1285*404b540aSrobert /*                                                                    */
1286*404b540aSrobert /* C must have space for set->digits digits.                          */
1287*404b540aSrobert /*                                                                    */
1288*404b540aSrobert /* Unless there is an error or the result is infinite, the exponent   */
1289*404b540aSrobert /* after the operation is guaranteed to be equal to B.                */
1290*404b540aSrobert /* ------------------------------------------------------------------ */
1291*404b540aSrobert decNumber *
decNumberRescale(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1292*404b540aSrobert decNumberRescale (decNumber * res, const decNumber * lhs,
1293*404b540aSrobert 		  const decNumber * rhs, decContext * set)
1294*404b540aSrobert {
1295*404b540aSrobert   uInt status = 0;		/* accumulator */
1296*404b540aSrobert   decQuantizeOp (res, lhs, rhs, set, 0, &status);
1297*404b540aSrobert   if (status != 0)
1298*404b540aSrobert     decStatus (res, status, set);
1299*404b540aSrobert   return res;
1300*404b540aSrobert }
1301*404b540aSrobert 
1302*404b540aSrobert /* ------------------------------------------------------------------ */
1303*404b540aSrobert /* decNumberRemainder -- divide and return remainder                  */
1304*404b540aSrobert /*                                                                    */
1305*404b540aSrobert /*   This computes C = A % B                                          */
1306*404b540aSrobert /*                                                                    */
1307*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
1308*404b540aSrobert /*   lhs is A                                                         */
1309*404b540aSrobert /*   rhs is B                                                         */
1310*404b540aSrobert /*   set is the context                                               */
1311*404b540aSrobert /*                                                                    */
1312*404b540aSrobert /* C must have space for set->digits digits.                          */
1313*404b540aSrobert /* ------------------------------------------------------------------ */
1314*404b540aSrobert decNumber *
decNumberRemainder(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1315*404b540aSrobert decNumberRemainder (decNumber * res, const decNumber * lhs,
1316*404b540aSrobert 		    const decNumber * rhs, decContext * set)
1317*404b540aSrobert {
1318*404b540aSrobert   uInt status = 0;		/* accumulator */
1319*404b540aSrobert   decDivideOp (res, lhs, rhs, set, REMAINDER, &status);
1320*404b540aSrobert   if (status != 0)
1321*404b540aSrobert     decStatus (res, status, set);
1322*404b540aSrobert   return res;
1323*404b540aSrobert }
1324*404b540aSrobert 
1325*404b540aSrobert /* ------------------------------------------------------------------ */
1326*404b540aSrobert /* decNumberRemainderNear -- divide and return remainder from nearest */
1327*404b540aSrobert /*                                                                    */
1328*404b540aSrobert /*   This computes C = A % B, where % is the IEEE remainder operator  */
1329*404b540aSrobert /*                                                                    */
1330*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
1331*404b540aSrobert /*   lhs is A                                                         */
1332*404b540aSrobert /*   rhs is B                                                         */
1333*404b540aSrobert /*   set is the context                                               */
1334*404b540aSrobert /*                                                                    */
1335*404b540aSrobert /* C must have space for set->digits digits.                          */
1336*404b540aSrobert /* ------------------------------------------------------------------ */
1337*404b540aSrobert decNumber *
decNumberRemainderNear(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1338*404b540aSrobert decNumberRemainderNear (decNumber * res, const decNumber * lhs,
1339*404b540aSrobert 			const decNumber * rhs, decContext * set)
1340*404b540aSrobert {
1341*404b540aSrobert   uInt status = 0;		/* accumulator */
1342*404b540aSrobert   decDivideOp (res, lhs, rhs, set, REMNEAR, &status);
1343*404b540aSrobert   if (status != 0)
1344*404b540aSrobert     decStatus (res, status, set);
1345*404b540aSrobert   return res;
1346*404b540aSrobert }
1347*404b540aSrobert 
1348*404b540aSrobert /* ------------------------------------------------------------------ */
1349*404b540aSrobert /* decNumberSameQuantum -- test for equal exponents                   */
1350*404b540aSrobert /*                                                                    */
1351*404b540aSrobert /*   res is the result number, which will contain either 0 or 1       */
1352*404b540aSrobert /*   lhs is a number to test                                          */
1353*404b540aSrobert /*   rhs is the second (usually a pattern)                            */
1354*404b540aSrobert /*                                                                    */
1355*404b540aSrobert /* No errors are possible and no context is needed.                   */
1356*404b540aSrobert /* ------------------------------------------------------------------ */
1357*404b540aSrobert decNumber *
decNumberSameQuantum(decNumber * res,const decNumber * lhs,const decNumber * rhs)1358*404b540aSrobert decNumberSameQuantum (decNumber * res, const decNumber * lhs, const decNumber * rhs)
1359*404b540aSrobert {
1360*404b540aSrobert   uByte merged;			/* merged flags */
1361*404b540aSrobert   Unit ret = 0;			/* return value */
1362*404b540aSrobert 
1363*404b540aSrobert #if DECCHECK
1364*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, DECUNUSED))
1365*404b540aSrobert     return res;
1366*404b540aSrobert #endif
1367*404b540aSrobert 
1368*404b540aSrobert   merged = (lhs->bits | rhs->bits) & DECSPECIAL;
1369*404b540aSrobert   if (merged)
1370*404b540aSrobert     {
1371*404b540aSrobert       if (decNumberIsNaN (lhs) && decNumberIsNaN (rhs))
1372*404b540aSrobert 	ret = 1;
1373*404b540aSrobert       else if (decNumberIsInfinite (lhs) && decNumberIsInfinite (rhs))
1374*404b540aSrobert 	ret = 1;
1375*404b540aSrobert       /* [anything else with a special gives 0] */
1376*404b540aSrobert     }
1377*404b540aSrobert   else if (lhs->exponent == rhs->exponent)
1378*404b540aSrobert     ret = 1;
1379*404b540aSrobert 
1380*404b540aSrobert   decNumberZero (res);		/* OK to overwrite an operand */
1381*404b540aSrobert   *res->lsu = ret;
1382*404b540aSrobert   return res;
1383*404b540aSrobert }
1384*404b540aSrobert 
1385*404b540aSrobert /* ------------------------------------------------------------------ */
1386*404b540aSrobert /* decNumberSquareRoot -- square root operator                        */
1387*404b540aSrobert /*                                                                    */
1388*404b540aSrobert /*   This computes C = squareroot(A)                                  */
1389*404b540aSrobert /*                                                                    */
1390*404b540aSrobert /*   res is C, the result.  C may be A                                */
1391*404b540aSrobert /*   rhs is A                                                         */
1392*404b540aSrobert /*   set is the context; note that rounding mode has no effect        */
1393*404b540aSrobert /*                                                                    */
1394*404b540aSrobert /* C must have space for set->digits digits.                          */
1395*404b540aSrobert /* ------------------------------------------------------------------ */
1396*404b540aSrobert /* This uses the following varying-precision algorithm in:            */
1397*404b540aSrobert /*                                                                    */
1398*404b540aSrobert /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
1399*404b540aSrobert /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
1400*404b540aSrobert /*   pp229-237, ACM, September 1985.                                  */
1401*404b540aSrobert /*                                                                    */
1402*404b540aSrobert /* % [Reformatted original Numerical Turing source code follows.]     */
1403*404b540aSrobert /* function sqrt(x : real) : real                                     */
1404*404b540aSrobert /* % sqrt(x) returns the properly rounded approximation to the square */
1405*404b540aSrobert /* % root of x, in the precision of the calling environment, or it    */
1406*404b540aSrobert /* % fails if x < 0.                                                  */
1407*404b540aSrobert /* % t e hull and a abrham, august, 1984                              */
1408*404b540aSrobert /* if x <= 0 then                                                     */
1409*404b540aSrobert /*   if x < 0 then                                                    */
1410*404b540aSrobert /*     assert false                                                   */
1411*404b540aSrobert /*   else                                                             */
1412*404b540aSrobert /*     result 0                                                       */
1413*404b540aSrobert /*   end if                                                           */
1414*404b540aSrobert /* end if                                                             */
1415*404b540aSrobert /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
1416*404b540aSrobert /* var e := getexp(x)     % exponent part of x                        */
1417*404b540aSrobert /* var approx : real                                                  */
1418*404b540aSrobert /* if e mod 2 = 0  then                                               */
1419*404b540aSrobert /*   approx := .259 + .819 * f   % approx to root of f                */
1420*404b540aSrobert /* else                                                               */
1421*404b540aSrobert /*   f := f/l0                   % adjustments                        */
1422*404b540aSrobert /*   e := e + 1                  %   for odd                          */
1423*404b540aSrobert /*   approx := .0819 + 2.59 * f  %   exponent                         */
1424*404b540aSrobert /* end if                                                             */
1425*404b540aSrobert /*                                                                    */
1426*404b540aSrobert /* var p:= 3                                                          */
1427*404b540aSrobert /* const maxp := currentprecision + 2                                 */
1428*404b540aSrobert /* loop                                                               */
1429*404b540aSrobert /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
1430*404b540aSrobert /*   precision p                                                      */
1431*404b540aSrobert /*   approx := .5 * (approx + f/approx)                               */
1432*404b540aSrobert /*   exit when p = maxp                                               */
1433*404b540aSrobert /* end loop                                                           */
1434*404b540aSrobert /*                                                                    */
1435*404b540aSrobert /* % approx is now within 1 ulp of the properly rounded square root   */
1436*404b540aSrobert /* % of f; to ensure proper rounding, compare squares of (approx -    */
1437*404b540aSrobert /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
1438*404b540aSrobert /* p := currentprecision                                              */
1439*404b540aSrobert /* begin                                                              */
1440*404b540aSrobert /*   precision p + 2                                                  */
1441*404b540aSrobert /*   const approxsubhalf := approx - setexp(.5, -p)                   */
1442*404b540aSrobert /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
1443*404b540aSrobert /*     approx := approx - setexp(.l, -p + 1)                          */
1444*404b540aSrobert /*   else                                                             */
1445*404b540aSrobert /*     const approxaddhalf := approx + setexp(.5, -p)                 */
1446*404b540aSrobert /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
1447*404b540aSrobert /*       approx := approx + setexp(.l, -p + 1)                        */
1448*404b540aSrobert /*     end if                                                         */
1449*404b540aSrobert /*   end if                                                           */
1450*404b540aSrobert /* end                                                                */
1451*404b540aSrobert /* result setexp(approx, e div 2)  % fix exponent                     */
1452*404b540aSrobert /* end sqrt                                                           */
1453*404b540aSrobert /* ------------------------------------------------------------------ */
1454*404b540aSrobert decNumber *
decNumberSquareRoot(decNumber * res,const decNumber * rhs,decContext * set)1455*404b540aSrobert decNumberSquareRoot (decNumber * res, const decNumber * rhs, decContext * set)
1456*404b540aSrobert {
1457*404b540aSrobert   decContext workset, approxset;	/* work contexts */
1458*404b540aSrobert   decNumber dzero;		/* used for constant zero */
1459*404b540aSrobert   Int maxp = set->digits + 2;	/* largest working precision */
1460*404b540aSrobert   Int residue = 0;		/* rounding residue */
1461*404b540aSrobert   uInt status = 0, ignore = 0;	/* status accumulators */
1462*404b540aSrobert   Int exp;			/* working exponent */
1463*404b540aSrobert   Int ideal;			/* ideal (preferred) exponent */
1464*404b540aSrobert   uInt needbytes;		/* work */
1465*404b540aSrobert   Int dropped;			/* .. */
1466*404b540aSrobert 
1467*404b540aSrobert   decNumber *allocrhs = NULL;	/* non-NULL if rounded rhs allocated */
1468*404b540aSrobert   /* buffer for f [needs +1 in case DECBUFFER 0] */
1469*404b540aSrobert   uByte buff[sizeof (decNumber) + (D2U (DECBUFFER + 1) - 1) * sizeof (Unit)];
1470*404b540aSrobert   /* buffer for a [needs +2 to match maxp] */
1471*404b540aSrobert   uByte bufa[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1472*404b540aSrobert   /* buffer for temporary, b [must be same size as a] */
1473*404b540aSrobert   uByte bufb[sizeof (decNumber) + (D2U (DECBUFFER + 2) - 1) * sizeof (Unit)];
1474*404b540aSrobert   decNumber *allocbuff = NULL;	/* -> allocated buff, iff allocated */
1475*404b540aSrobert   decNumber *allocbufa = NULL;	/* -> allocated bufa, iff allocated */
1476*404b540aSrobert   decNumber *allocbufb = NULL;	/* -> allocated bufb, iff allocated */
1477*404b540aSrobert   decNumber *f = (decNumber *) buff;	/* reduced fraction */
1478*404b540aSrobert   decNumber *a = (decNumber *) bufa;	/* approximation to result */
1479*404b540aSrobert   decNumber *b = (decNumber *) bufb;	/* intermediate result */
1480*404b540aSrobert   /* buffer for temporary variable, up to 3 digits */
1481*404b540aSrobert   uByte buft[sizeof (decNumber) + (D2U (3) - 1) * sizeof (Unit)];
1482*404b540aSrobert   decNumber *t = (decNumber *) buft;	/* up-to-3-digit constant or work */
1483*404b540aSrobert 
1484*404b540aSrobert #if DECCHECK
1485*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
1486*404b540aSrobert     return res;
1487*404b540aSrobert #endif
1488*404b540aSrobert 
1489*404b540aSrobert   do
1490*404b540aSrobert     {				/* protect allocated storage */
1491*404b540aSrobert #if DECSUBSET
1492*404b540aSrobert       if (!set->extended)
1493*404b540aSrobert 	{
1494*404b540aSrobert 	  /* reduce operand and set lostDigits status, as needed */
1495*404b540aSrobert 	  if (rhs->digits > set->digits)
1496*404b540aSrobert 	    {
1497*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, &status);
1498*404b540aSrobert 	      if (allocrhs == NULL)
1499*404b540aSrobert 		break;
1500*404b540aSrobert 	      /* [Note: 'f' allocation below could reuse this buffer if */
1501*404b540aSrobert 	      /* used, but as this is rare we keep them separate for clarity.] */
1502*404b540aSrobert 	      rhs = allocrhs;
1503*404b540aSrobert 	    }
1504*404b540aSrobert 	}
1505*404b540aSrobert #endif
1506*404b540aSrobert       /* [following code does not require input rounding] */
1507*404b540aSrobert 
1508*404b540aSrobert       /* handle infinities and NaNs */
1509*404b540aSrobert       if (rhs->bits & DECSPECIAL)
1510*404b540aSrobert 	{
1511*404b540aSrobert 	  if (decNumberIsInfinite (rhs))
1512*404b540aSrobert 	    {			/* an infinity */
1513*404b540aSrobert 	      if (decNumberIsNegative (rhs))
1514*404b540aSrobert 		status |= DEC_Invalid_operation;
1515*404b540aSrobert 	      else
1516*404b540aSrobert 		decNumberCopy (res, rhs);	/* +Infinity */
1517*404b540aSrobert 	    }
1518*404b540aSrobert 	  else
1519*404b540aSrobert 	    decNaNs (res, rhs, NULL, &status);	/* a NaN */
1520*404b540aSrobert 	  break;
1521*404b540aSrobert 	}
1522*404b540aSrobert 
1523*404b540aSrobert       /* calculate the ideal (preferred) exponent [floor(exp/2)] */
1524*404b540aSrobert       /* [We would like to write: ideal=rhs->exponent>>1, but this */
1525*404b540aSrobert       /* generates a compiler warning.  Generated code is the same.] */
1526*404b540aSrobert       ideal = (rhs->exponent & ~1) / 2;	/* target */
1527*404b540aSrobert 
1528*404b540aSrobert       /* handle zeros */
1529*404b540aSrobert       if (ISZERO (rhs))
1530*404b540aSrobert 	{
1531*404b540aSrobert 	  decNumberCopy (res, rhs);	/* could be 0 or -0 */
1532*404b540aSrobert 	  res->exponent = ideal;	/* use the ideal [safe] */
1533*404b540aSrobert 	  break;
1534*404b540aSrobert 	}
1535*404b540aSrobert 
1536*404b540aSrobert       /* any other -x is an oops */
1537*404b540aSrobert       if (decNumberIsNegative (rhs))
1538*404b540aSrobert 	{
1539*404b540aSrobert 	  status |= DEC_Invalid_operation;
1540*404b540aSrobert 	  break;
1541*404b540aSrobert 	}
1542*404b540aSrobert 
1543*404b540aSrobert       /* we need space for three working variables */
1544*404b540aSrobert       /*   f -- the same precision as the RHS, reduced to 0.01->0.99... */
1545*404b540aSrobert       /*   a -- Hull's approx -- precision, when assigned, is */
1546*404b540aSrobert       /*        currentprecision (we allow +2 for use as temporary) */
1547*404b540aSrobert       /*   b -- intermediate temporary result */
1548*404b540aSrobert       /* if any is too long for local storage, then allocate */
1549*404b540aSrobert       needbytes =
1550*404b540aSrobert 	sizeof (decNumber) + (D2U (rhs->digits) - 1) * sizeof (Unit);
1551*404b540aSrobert       if (needbytes > sizeof (buff))
1552*404b540aSrobert 	{
1553*404b540aSrobert 	  allocbuff = (decNumber *) malloc (needbytes);
1554*404b540aSrobert 	  if (allocbuff == NULL)
1555*404b540aSrobert 	    {			/* hopeless -- abandon */
1556*404b540aSrobert 	      status |= DEC_Insufficient_storage;
1557*404b540aSrobert 	      break;
1558*404b540aSrobert 	    }
1559*404b540aSrobert 	  f = allocbuff;	/* use the allocated space */
1560*404b540aSrobert 	}
1561*404b540aSrobert       /* a and b both need to be able to hold a maxp-length number */
1562*404b540aSrobert       needbytes = sizeof (decNumber) + (D2U (maxp) - 1) * sizeof (Unit);
1563*404b540aSrobert       if (needbytes > sizeof (bufa))
1564*404b540aSrobert 	{			/* [same applies to b] */
1565*404b540aSrobert 	  allocbufa = (decNumber *) malloc (needbytes);
1566*404b540aSrobert 	  allocbufb = (decNumber *) malloc (needbytes);
1567*404b540aSrobert 	  if (allocbufa == NULL || allocbufb == NULL)
1568*404b540aSrobert 	    {			/* hopeless */
1569*404b540aSrobert 	      status |= DEC_Insufficient_storage;
1570*404b540aSrobert 	      break;
1571*404b540aSrobert 	    }
1572*404b540aSrobert 	  a = allocbufa;	/* use the allocated space */
1573*404b540aSrobert 	  b = allocbufb;	/* .. */
1574*404b540aSrobert 	}
1575*404b540aSrobert 
1576*404b540aSrobert       /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
1577*404b540aSrobert       decNumberCopy (f, rhs);
1578*404b540aSrobert       exp = f->exponent + f->digits;	/* adjusted to Hull rules */
1579*404b540aSrobert       f->exponent = -(f->digits);	/* to range */
1580*404b540aSrobert 
1581*404b540aSrobert       /* set up working contexts (the second is used for Numerical */
1582*404b540aSrobert       /* Turing assignment) */
1583*404b540aSrobert       decContextDefault (&workset, DEC_INIT_DECIMAL64);
1584*404b540aSrobert       decContextDefault (&approxset, DEC_INIT_DECIMAL64);
1585*404b540aSrobert       approxset.digits = set->digits;	/* approx's length */
1586*404b540aSrobert 
1587*404b540aSrobert       /* [Until further notice, no error is possible and status bits */
1588*404b540aSrobert       /* (Rounded, etc.) should be ignored, not accumulated.] */
1589*404b540aSrobert 
1590*404b540aSrobert       /* Calculate initial approximation, and allow for odd exponent */
1591*404b540aSrobert       workset.digits = set->digits;	/* p for initial calculation */
1592*404b540aSrobert       t->bits = 0;
1593*404b540aSrobert       t->digits = 3;
1594*404b540aSrobert       a->bits = 0;
1595*404b540aSrobert       a->digits = 3;
1596*404b540aSrobert       if ((exp & 1) == 0)
1597*404b540aSrobert 	{			/* even exponent */
1598*404b540aSrobert 	  /* Set t=0.259, a=0.819 */
1599*404b540aSrobert 	  t->exponent = -3;
1600*404b540aSrobert 	  a->exponent = -3;
1601*404b540aSrobert #if DECDPUN>=3
1602*404b540aSrobert 	  t->lsu[0] = 259;
1603*404b540aSrobert 	  a->lsu[0] = 819;
1604*404b540aSrobert #elif DECDPUN==2
1605*404b540aSrobert 	  t->lsu[0] = 59;
1606*404b540aSrobert 	  t->lsu[1] = 2;
1607*404b540aSrobert 	  a->lsu[0] = 19;
1608*404b540aSrobert 	  a->lsu[1] = 8;
1609*404b540aSrobert #else
1610*404b540aSrobert 	  t->lsu[0] = 9;
1611*404b540aSrobert 	  t->lsu[1] = 5;
1612*404b540aSrobert 	  t->lsu[2] = 2;
1613*404b540aSrobert 	  a->lsu[0] = 9;
1614*404b540aSrobert 	  a->lsu[1] = 1;
1615*404b540aSrobert 	  a->lsu[2] = 8;
1616*404b540aSrobert #endif
1617*404b540aSrobert 	}
1618*404b540aSrobert       else
1619*404b540aSrobert 	{			/* odd exponent */
1620*404b540aSrobert 	  /* Set t=0.0819, a=2.59 */
1621*404b540aSrobert 	  f->exponent--;	/* f=f/10 */
1622*404b540aSrobert 	  exp++;		/* e=e+1 */
1623*404b540aSrobert 	  t->exponent = -4;
1624*404b540aSrobert 	  a->exponent = -2;
1625*404b540aSrobert #if DECDPUN>=3
1626*404b540aSrobert 	  t->lsu[0] = 819;
1627*404b540aSrobert 	  a->lsu[0] = 259;
1628*404b540aSrobert #elif DECDPUN==2
1629*404b540aSrobert 	  t->lsu[0] = 19;
1630*404b540aSrobert 	  t->lsu[1] = 8;
1631*404b540aSrobert 	  a->lsu[0] = 59;
1632*404b540aSrobert 	  a->lsu[1] = 2;
1633*404b540aSrobert #else
1634*404b540aSrobert 	  t->lsu[0] = 9;
1635*404b540aSrobert 	  t->lsu[1] = 1;
1636*404b540aSrobert 	  t->lsu[2] = 8;
1637*404b540aSrobert 	  a->lsu[0] = 9;
1638*404b540aSrobert 	  a->lsu[1] = 5;
1639*404b540aSrobert 	  a->lsu[2] = 2;
1640*404b540aSrobert #endif
1641*404b540aSrobert 	}
1642*404b540aSrobert       decMultiplyOp (a, a, f, &workset, &ignore);	/* a=a*f */
1643*404b540aSrobert       decAddOp (a, a, t, &workset, 0, &ignore);	/* ..+t */
1644*404b540aSrobert       /* [a is now the initial approximation for sqrt(f), calculated with */
1645*404b540aSrobert       /* currentprecision, which is also a's precision.] */
1646*404b540aSrobert 
1647*404b540aSrobert       /* the main calculation loop */
1648*404b540aSrobert       decNumberZero (&dzero);	/* make 0 */
1649*404b540aSrobert       decNumberZero (t);	/* set t = 0.5 */
1650*404b540aSrobert       t->lsu[0] = 5;		/* .. */
1651*404b540aSrobert       t->exponent = -1;		/* .. */
1652*404b540aSrobert       workset.digits = 3;	/* initial p */
1653*404b540aSrobert       for (;;)
1654*404b540aSrobert 	{
1655*404b540aSrobert 	  /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp] */
1656*404b540aSrobert 	  workset.digits = workset.digits * 2 - 2;
1657*404b540aSrobert 	  if (workset.digits > maxp)
1658*404b540aSrobert 	    workset.digits = maxp;
1659*404b540aSrobert 	  /* a = 0.5 * (a + f/a) */
1660*404b540aSrobert 	  /* [calculated at p then rounded to currentprecision] */
1661*404b540aSrobert 	  decDivideOp (b, f, a, &workset, DIVIDE, &ignore);	/* b=f/a */
1662*404b540aSrobert 	  decAddOp (b, b, a, &workset, 0, &ignore);	/* b=b+a */
1663*404b540aSrobert 	  decMultiplyOp (a, b, t, &workset, &ignore);	/* a=b*0.5 */
1664*404b540aSrobert 	  /* assign to approx [round to length] */
1665*404b540aSrobert 	  decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1666*404b540aSrobert 	  if (workset.digits == maxp)
1667*404b540aSrobert 	    break;		/* just did final */
1668*404b540aSrobert 	}			/* loop */
1669*404b540aSrobert 
1670*404b540aSrobert       /* a is now at currentprecision and within 1 ulp of the properly */
1671*404b540aSrobert       /* rounded square root of f; to ensure proper rounding, compare */
1672*404b540aSrobert       /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
1673*404b540aSrobert       /* Here workset.digits=maxp and t=0.5 */
1674*404b540aSrobert       workset.digits--;		/* maxp-1 is OK now */
1675*404b540aSrobert       t->exponent = -set->digits - 1;	/* make 0.5 ulp */
1676*404b540aSrobert       decNumberCopy (b, a);
1677*404b540aSrobert       decAddOp (b, b, t, &workset, DECNEG, &ignore);	/* b = a - 0.5 ulp */
1678*404b540aSrobert       workset.round = DEC_ROUND_UP;
1679*404b540aSrobert       decMultiplyOp (b, b, b, &workset, &ignore);	/* b = mulru(b, b) */
1680*404b540aSrobert       decCompareOp (b, f, b, &workset, COMPARE, &ignore);	/* b ? f, reversed */
1681*404b540aSrobert       if (decNumberIsNegative (b))
1682*404b540aSrobert 	{			/* f < b [i.e., b > f] */
1683*404b540aSrobert 	  /* this is the more common adjustment, though both are rare */
1684*404b540aSrobert 	  t->exponent++;	/* make 1.0 ulp */
1685*404b540aSrobert 	  t->lsu[0] = 1;	/* .. */
1686*404b540aSrobert 	  decAddOp (a, a, t, &workset, DECNEG, &ignore);	/* a = a - 1 ulp */
1687*404b540aSrobert 	  /* assign to approx [round to length] */
1688*404b540aSrobert 	  decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1689*404b540aSrobert 	}
1690*404b540aSrobert       else
1691*404b540aSrobert 	{
1692*404b540aSrobert 	  decNumberCopy (b, a);
1693*404b540aSrobert 	  decAddOp (b, b, t, &workset, 0, &ignore);	/* b = a + 0.5 ulp */
1694*404b540aSrobert 	  workset.round = DEC_ROUND_DOWN;
1695*404b540aSrobert 	  decMultiplyOp (b, b, b, &workset, &ignore);	/* b = mulrd(b, b) */
1696*404b540aSrobert 	  decCompareOp (b, b, f, &workset, COMPARE, &ignore);	/* b ? f */
1697*404b540aSrobert 	  if (decNumberIsNegative (b))
1698*404b540aSrobert 	    {			/* b < f */
1699*404b540aSrobert 	      t->exponent++;	/* make 1.0 ulp */
1700*404b540aSrobert 	      t->lsu[0] = 1;	/* .. */
1701*404b540aSrobert 	      decAddOp (a, a, t, &workset, 0, &ignore);	/* a = a + 1 ulp */
1702*404b540aSrobert 	      /* assign to approx [round to length] */
1703*404b540aSrobert 	      decAddOp (a, &dzero, a, &approxset, 0, &ignore);
1704*404b540aSrobert 	    }
1705*404b540aSrobert 	}
1706*404b540aSrobert       /* [no errors are possible in the above, and rounding/inexact during */
1707*404b540aSrobert       /* estimation are irrelevant, so status was not accumulated] */
1708*404b540aSrobert 
1709*404b540aSrobert       /* Here, 0.1 <= a < 1  [Hull] */
1710*404b540aSrobert       a->exponent += exp / 2;	/* set correct exponent */
1711*404b540aSrobert 
1712*404b540aSrobert       /* Process Subnormals */
1713*404b540aSrobert       decFinalize (a, set, &residue, &status);
1714*404b540aSrobert 
1715*404b540aSrobert       /* count dropable zeros [after any subnormal rounding] */
1716*404b540aSrobert       decNumberCopy (b, a);
1717*404b540aSrobert       decTrim (b, 1, &dropped);	/* [drops trailing zeros] */
1718*404b540aSrobert 
1719*404b540aSrobert       /* Finally set Inexact and Rounded.  The answer can only be exact if */
1720*404b540aSrobert       /* it is short enough so that squaring it could fit in set->digits, */
1721*404b540aSrobert       /* so this is the only (relatively rare) time we have to check */
1722*404b540aSrobert       /* carefully */
1723*404b540aSrobert       if (b->digits * 2 - 1 > set->digits)
1724*404b540aSrobert 	{			/* cannot fit */
1725*404b540aSrobert 	  status |= DEC_Inexact | DEC_Rounded;
1726*404b540aSrobert 	}
1727*404b540aSrobert       else
1728*404b540aSrobert 	{			/* could be exact/unrounded */
1729*404b540aSrobert 	  uInt mstatus = 0;	/* local status */
1730*404b540aSrobert 	  decMultiplyOp (b, b, b, &workset, &mstatus);	/* try the multiply */
1731*404b540aSrobert 	  if (mstatus != 0)
1732*404b540aSrobert 	    {			/* result won't fit */
1733*404b540aSrobert 	      status |= DEC_Inexact | DEC_Rounded;
1734*404b540aSrobert 	    }
1735*404b540aSrobert 	  else
1736*404b540aSrobert 	    {			/* plausible */
1737*404b540aSrobert 	      decCompareOp (t, b, rhs, &workset, COMPARE, &mstatus);	/* b ? rhs */
1738*404b540aSrobert 	      if (!ISZERO (t))
1739*404b540aSrobert 		{
1740*404b540aSrobert 		  status |= DEC_Inexact | DEC_Rounded;
1741*404b540aSrobert 		}
1742*404b540aSrobert 	      else
1743*404b540aSrobert 		{		/* is Exact */
1744*404b540aSrobert 		  /* here, dropped is the count of trailing zeros in 'a' */
1745*404b540aSrobert 		  /* use closest exponent to ideal... */
1746*404b540aSrobert 		  Int todrop = ideal - a->exponent;	/* most we can drop */
1747*404b540aSrobert 
1748*404b540aSrobert 		  if (todrop < 0)
1749*404b540aSrobert 		    {		/* ideally would add 0s */
1750*404b540aSrobert 		      status |= DEC_Rounded;
1751*404b540aSrobert 		    }
1752*404b540aSrobert 		  else
1753*404b540aSrobert 		    {		/* unrounded */
1754*404b540aSrobert 		      if (dropped < todrop)
1755*404b540aSrobert 			todrop = dropped;	/* clamp to those available */
1756*404b540aSrobert 		      if (todrop > 0)
1757*404b540aSrobert 			{	/* OK, some to drop */
1758*404b540aSrobert 			  decShiftToLeast (a->lsu, D2U (a->digits), todrop);
1759*404b540aSrobert 			  a->exponent += todrop;	/* maintain numerical value */
1760*404b540aSrobert 			  a->digits -= todrop;	/* new length */
1761*404b540aSrobert 			}
1762*404b540aSrobert 		    }
1763*404b540aSrobert 		}
1764*404b540aSrobert 	    }
1765*404b540aSrobert 	}
1766*404b540aSrobert       decNumberCopy (res, a);	/* assume this is the result */
1767*404b540aSrobert     }
1768*404b540aSrobert   while (0);			/* end protected */
1769*404b540aSrobert 
1770*404b540aSrobert   if (allocbuff != NULL)
1771*404b540aSrobert     free (allocbuff);		/* drop any storage we used */
1772*404b540aSrobert   if (allocbufa != NULL)
1773*404b540aSrobert     free (allocbufa);		/* .. */
1774*404b540aSrobert   if (allocbufb != NULL)
1775*404b540aSrobert     free (allocbufb);		/* .. */
1776*404b540aSrobert   if (allocrhs != NULL)
1777*404b540aSrobert     free (allocrhs);		/* .. */
1778*404b540aSrobert   if (status != 0)
1779*404b540aSrobert     decStatus (res, status, set);	/* then report status */
1780*404b540aSrobert   return res;
1781*404b540aSrobert }
1782*404b540aSrobert 
1783*404b540aSrobert /* ------------------------------------------------------------------ */
1784*404b540aSrobert /* decNumberSubtract -- subtract two Numbers                          */
1785*404b540aSrobert /*                                                                    */
1786*404b540aSrobert /*   This computes C = A - B                                          */
1787*404b540aSrobert /*                                                                    */
1788*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
1789*404b540aSrobert /*   lhs is A                                                         */
1790*404b540aSrobert /*   rhs is B                                                         */
1791*404b540aSrobert /*   set is the context                                               */
1792*404b540aSrobert /*                                                                    */
1793*404b540aSrobert /* C must have space for set->digits digits.                          */
1794*404b540aSrobert /* ------------------------------------------------------------------ */
1795*404b540aSrobert decNumber *
decNumberSubtract(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set)1796*404b540aSrobert decNumberSubtract (decNumber * res, const decNumber * lhs,
1797*404b540aSrobert 		   const decNumber * rhs, decContext * set)
1798*404b540aSrobert {
1799*404b540aSrobert   uInt status = 0;		/* accumulator */
1800*404b540aSrobert 
1801*404b540aSrobert   decAddOp (res, lhs, rhs, set, DECNEG, &status);
1802*404b540aSrobert   if (status != 0)
1803*404b540aSrobert     decStatus (res, status, set);
1804*404b540aSrobert   return res;
1805*404b540aSrobert }
1806*404b540aSrobert 
1807*404b540aSrobert /* ------------------------------------------------------------------ */
1808*404b540aSrobert /* decNumberToIntegralValue -- round-to-integral-value                */
1809*404b540aSrobert /*                                                                    */
1810*404b540aSrobert /*   res is the result                                                */
1811*404b540aSrobert /*   rhs is input number                                              */
1812*404b540aSrobert /*   set is the context                                               */
1813*404b540aSrobert /*                                                                    */
1814*404b540aSrobert /* res must have space for any value of rhs.                          */
1815*404b540aSrobert /*                                                                    */
1816*404b540aSrobert /* This implements the IEEE special operator and therefore treats     */
1817*404b540aSrobert /* special values as valid, and also never sets Inexact.  For finite  */
1818*404b540aSrobert /* numbers it returns rescale(rhs, 0) if rhs->exponent is <0.         */
1819*404b540aSrobert /* Otherwise the result is rhs (so no error is possible).             */
1820*404b540aSrobert /*                                                                    */
1821*404b540aSrobert /* The context is used for rounding mode and status after sNaN, but   */
1822*404b540aSrobert /* the digits setting is ignored.                                     */
1823*404b540aSrobert /* ------------------------------------------------------------------ */
1824*404b540aSrobert decNumber *
decNumberToIntegralValue(decNumber * res,const decNumber * rhs,decContext * set)1825*404b540aSrobert decNumberToIntegralValue (decNumber * res, const decNumber * rhs, decContext * set)
1826*404b540aSrobert {
1827*404b540aSrobert   decNumber dn;
1828*404b540aSrobert   decContext workset;		/* working context */
1829*404b540aSrobert 
1830*404b540aSrobert #if DECCHECK
1831*404b540aSrobert   if (decCheckOperands (res, DECUNUSED, rhs, set))
1832*404b540aSrobert     return res;
1833*404b540aSrobert #endif
1834*404b540aSrobert 
1835*404b540aSrobert   /* handle infinities and NaNs */
1836*404b540aSrobert   if (rhs->bits & DECSPECIAL)
1837*404b540aSrobert     {
1838*404b540aSrobert       uInt status = 0;
1839*404b540aSrobert       if (decNumberIsInfinite (rhs))
1840*404b540aSrobert 	decNumberCopy (res, rhs);	/* an Infinity */
1841*404b540aSrobert       else
1842*404b540aSrobert 	decNaNs (res, rhs, NULL, &status);	/* a NaN */
1843*404b540aSrobert       if (status != 0)
1844*404b540aSrobert 	decStatus (res, status, set);
1845*404b540aSrobert       return res;
1846*404b540aSrobert     }
1847*404b540aSrobert 
1848*404b540aSrobert   /* we have a finite number; no error possible */
1849*404b540aSrobert   if (rhs->exponent >= 0)
1850*404b540aSrobert     return decNumberCopy (res, rhs);
1851*404b540aSrobert   /* that was easy, but if negative exponent we have work to do... */
1852*404b540aSrobert   workset = *set;		/* clone rounding, etc. */
1853*404b540aSrobert   workset.digits = rhs->digits;	/* no length rounding */
1854*404b540aSrobert   workset.traps = 0;		/* no traps */
1855*404b540aSrobert   decNumberZero (&dn);		/* make a number with exponent 0 */
1856*404b540aSrobert   return decNumberQuantize (res, rhs, &dn, &workset);
1857*404b540aSrobert }
1858*404b540aSrobert 
1859*404b540aSrobert /* ================================================================== */
1860*404b540aSrobert /* Utility routines                                                   */
1861*404b540aSrobert /* ================================================================== */
1862*404b540aSrobert 
1863*404b540aSrobert /* ------------------------------------------------------------------ */
1864*404b540aSrobert /* decNumberCopy -- copy a number                                     */
1865*404b540aSrobert /*                                                                    */
1866*404b540aSrobert /*   dest is the target decNumber                                     */
1867*404b540aSrobert /*   src  is the source decNumber                                     */
1868*404b540aSrobert /*   returns dest                                                     */
1869*404b540aSrobert /*                                                                    */
1870*404b540aSrobert /* (dest==src is allowed and is a no-op)                              */
1871*404b540aSrobert /* All fields are updated as required.  This is a utility operation,  */
1872*404b540aSrobert /* so special values are unchanged and no error is possible.          */
1873*404b540aSrobert /* ------------------------------------------------------------------ */
1874*404b540aSrobert decNumber *
decNumberCopy(decNumber * dest,const decNumber * src)1875*404b540aSrobert decNumberCopy (decNumber * dest, const decNumber * src)
1876*404b540aSrobert {
1877*404b540aSrobert 
1878*404b540aSrobert #if DECCHECK
1879*404b540aSrobert   if (src == NULL)
1880*404b540aSrobert     return decNumberZero (dest);
1881*404b540aSrobert #endif
1882*404b540aSrobert 
1883*404b540aSrobert   if (dest == src)
1884*404b540aSrobert     return dest;		/* no copy required */
1885*404b540aSrobert 
1886*404b540aSrobert   /* We use explicit assignments here as structure assignment can copy */
1887*404b540aSrobert   /* more than just the lsu (for small DECDPUN).  This would not affect */
1888*404b540aSrobert   /* the value of the results, but would disturb test harness spill */
1889*404b540aSrobert   /* checking. */
1890*404b540aSrobert   dest->bits = src->bits;
1891*404b540aSrobert   dest->exponent = src->exponent;
1892*404b540aSrobert   dest->digits = src->digits;
1893*404b540aSrobert   dest->lsu[0] = src->lsu[0];
1894*404b540aSrobert   if (src->digits > DECDPUN)
1895*404b540aSrobert     {				/* more Units to come */
1896*404b540aSrobert       Unit *d;			/* work */
1897*404b540aSrobert       const Unit *s, *smsup;	/* work */
1898*404b540aSrobert       /* memcpy for the remaining Units would be safe as they cannot */
1899*404b540aSrobert       /* overlap.  However, this explicit loop is faster in short cases. */
1900*404b540aSrobert       d = dest->lsu + 1;	/* -> first destination */
1901*404b540aSrobert       smsup = src->lsu + D2U (src->digits);	/* -> source msu+1 */
1902*404b540aSrobert       for (s = src->lsu + 1; s < smsup; s++, d++)
1903*404b540aSrobert 	*d = *s;
1904*404b540aSrobert     }
1905*404b540aSrobert   return dest;
1906*404b540aSrobert }
1907*404b540aSrobert 
1908*404b540aSrobert /* ------------------------------------------------------------------ */
1909*404b540aSrobert /* decNumberTrim -- remove insignificant zeros                        */
1910*404b540aSrobert /*                                                                    */
1911*404b540aSrobert /*   dn is the number to trim                                         */
1912*404b540aSrobert /*   returns dn                                                       */
1913*404b540aSrobert /*                                                                    */
1914*404b540aSrobert /* All fields are updated as required.  This is a utility operation,  */
1915*404b540aSrobert /* so special values are unchanged and no error is possible.          */
1916*404b540aSrobert /* ------------------------------------------------------------------ */
1917*404b540aSrobert decNumber *
decNumberTrim(decNumber * dn)1918*404b540aSrobert decNumberTrim (decNumber * dn)
1919*404b540aSrobert {
1920*404b540aSrobert   Int dropped;			/* work */
1921*404b540aSrobert   return decTrim (dn, 0, &dropped);
1922*404b540aSrobert }
1923*404b540aSrobert 
1924*404b540aSrobert /* ------------------------------------------------------------------ */
1925*404b540aSrobert /* decNumberVersion -- return the name and version of this module     */
1926*404b540aSrobert /*                                                                    */
1927*404b540aSrobert /* No error is possible.                                              */
1928*404b540aSrobert /* ------------------------------------------------------------------ */
1929*404b540aSrobert const char *
decNumberVersion(void)1930*404b540aSrobert decNumberVersion (void)
1931*404b540aSrobert {
1932*404b540aSrobert   return DECVERSION;
1933*404b540aSrobert }
1934*404b540aSrobert 
1935*404b540aSrobert /* ------------------------------------------------------------------ */
1936*404b540aSrobert /* decNumberZero -- set a number to 0                                 */
1937*404b540aSrobert /*                                                                    */
1938*404b540aSrobert /*   dn is the number to set, with space for one digit                */
1939*404b540aSrobert /*   returns dn                                                       */
1940*404b540aSrobert /*                                                                    */
1941*404b540aSrobert /* No error is possible.                                              */
1942*404b540aSrobert /* ------------------------------------------------------------------ */
1943*404b540aSrobert /* Memset is not used as it is much slower in some environments. */
1944*404b540aSrobert decNumber *
decNumberZero(decNumber * dn)1945*404b540aSrobert decNumberZero (decNumber * dn)
1946*404b540aSrobert {
1947*404b540aSrobert 
1948*404b540aSrobert #if DECCHECK
1949*404b540aSrobert   if (decCheckOperands (dn, DECUNUSED, DECUNUSED, DECUNUSED))
1950*404b540aSrobert     return dn;
1951*404b540aSrobert #endif
1952*404b540aSrobert 
1953*404b540aSrobert   dn->bits = 0;
1954*404b540aSrobert   dn->exponent = 0;
1955*404b540aSrobert   dn->digits = 1;
1956*404b540aSrobert   dn->lsu[0] = 0;
1957*404b540aSrobert   return dn;
1958*404b540aSrobert }
1959*404b540aSrobert 
1960*404b540aSrobert /* ================================================================== */
1961*404b540aSrobert /* Local routines                                                     */
1962*404b540aSrobert /* ================================================================== */
1963*404b540aSrobert 
1964*404b540aSrobert /* ------------------------------------------------------------------ */
1965*404b540aSrobert /* decToString -- lay out a number into a string                      */
1966*404b540aSrobert /*                                                                    */
1967*404b540aSrobert /*   dn     is the number to lay out                                  */
1968*404b540aSrobert /*   string is where to lay out the number                            */
1969*404b540aSrobert /*   eng    is 1 if Engineering, 0 if Scientific                      */
1970*404b540aSrobert /*                                                                    */
1971*404b540aSrobert /* str must be at least dn->digits+14 characters long                 */
1972*404b540aSrobert /* No error is possible.                                              */
1973*404b540aSrobert /*                                                                    */
1974*404b540aSrobert /* Note that this routine can generate a -0 or 0.000.  These are      */
1975*404b540aSrobert /* never generated in subset to-number or arithmetic, but can occur   */
1976*404b540aSrobert /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
1977*404b540aSrobert /* ------------------------------------------------------------------ */
1978*404b540aSrobert /* If DECCHECK is enabled the string "?" is returned if a number is */
1979*404b540aSrobert /* invalid. */
1980*404b540aSrobert 
1981*404b540aSrobert /* TODIGIT -- macro to remove the leading digit from the unsigned */
1982*404b540aSrobert /* integer u at column cut (counting from the right, LSD=0) and place */
1983*404b540aSrobert /* it as an ASCII character into the character pointed to by c.  Note */
1984*404b540aSrobert /* that cut must be <= 9, and the maximum value for u is 2,000,000,000 */
1985*404b540aSrobert /* (as is needed for negative exponents of subnormals).  The unsigned */
1986*404b540aSrobert /* integer pow is used as a temporary variable. */
1987*404b540aSrobert #define TODIGIT(u, cut, c) {            \
1988*404b540aSrobert   *(c)='0';                             \
1989*404b540aSrobert   pow=powers[cut]*2;                    \
1990*404b540aSrobert   if ((u)>pow) {                        \
1991*404b540aSrobert     pow*=4;                             \
1992*404b540aSrobert     if ((u)>=pow) {(u)-=pow; *(c)+=8;}  \
1993*404b540aSrobert     pow/=2;                             \
1994*404b540aSrobert     if ((u)>=pow) {(u)-=pow; *(c)+=4;}  \
1995*404b540aSrobert     pow/=2;                             \
1996*404b540aSrobert     }                                   \
1997*404b540aSrobert   if ((u)>=pow) {(u)-=pow; *(c)+=2;}    \
1998*404b540aSrobert   pow/=2;                               \
1999*404b540aSrobert   if ((u)>=pow) {(u)-=pow; *(c)+=1;}    \
2000*404b540aSrobert   }
2001*404b540aSrobert 
2002*404b540aSrobert static void
decToString(const decNumber * dn,char * string,Flag eng)2003*404b540aSrobert decToString (const decNumber * dn, char *string, Flag eng)
2004*404b540aSrobert {
2005*404b540aSrobert   Int exp = dn->exponent;	/* local copy */
2006*404b540aSrobert   Int e;			/* E-part value */
2007*404b540aSrobert   Int pre;			/* digits before the '.' */
2008*404b540aSrobert   Int cut;			/* for counting digits in a Unit */
2009*404b540aSrobert   char *c = string;		/* work [output pointer] */
2010*404b540aSrobert   const Unit *up = dn->lsu + D2U (dn->digits) - 1;	/* -> msu [input pointer] */
2011*404b540aSrobert   uInt u, pow;			/* work */
2012*404b540aSrobert 
2013*404b540aSrobert #if DECCHECK
2014*404b540aSrobert   if (decCheckOperands (DECUNUSED, dn, DECUNUSED, DECUNUSED))
2015*404b540aSrobert     {
2016*404b540aSrobert       strcpy (string, "?");
2017*404b540aSrobert       return;
2018*404b540aSrobert     }
2019*404b540aSrobert #endif
2020*404b540aSrobert 
2021*404b540aSrobert   if (decNumberIsNegative (dn))
2022*404b540aSrobert     {				/* Negatives get a minus (except */
2023*404b540aSrobert       *c = '-';			/* NaNs, which remove the '-' below) */
2024*404b540aSrobert       c++;
2025*404b540aSrobert     }
2026*404b540aSrobert   if (dn->bits & DECSPECIAL)
2027*404b540aSrobert     {				/* Is a special value */
2028*404b540aSrobert       if (decNumberIsInfinite (dn))
2029*404b540aSrobert 	{
2030*404b540aSrobert 	  strcpy (c, "Infinity");
2031*404b540aSrobert 	  return;
2032*404b540aSrobert 	}
2033*404b540aSrobert       /* a NaN */
2034*404b540aSrobert       if (dn->bits & DECSNAN)
2035*404b540aSrobert 	{			/* signalling NaN */
2036*404b540aSrobert 	  *c = 's';
2037*404b540aSrobert 	  c++;
2038*404b540aSrobert 	}
2039*404b540aSrobert       strcpy (c, "NaN");
2040*404b540aSrobert       c += 3;			/* step past */
2041*404b540aSrobert       /* if not a clean non-zero coefficient, that's all we have in a */
2042*404b540aSrobert       /* NaN string */
2043*404b540aSrobert       if (exp != 0 || (*dn->lsu == 0 && dn->digits == 1))
2044*404b540aSrobert 	return;
2045*404b540aSrobert       /* [drop through to add integer] */
2046*404b540aSrobert     }
2047*404b540aSrobert 
2048*404b540aSrobert   /* calculate how many digits in msu, and hence first cut */
2049*404b540aSrobert   cut = dn->digits % DECDPUN;
2050*404b540aSrobert   if (cut == 0)
2051*404b540aSrobert     cut = DECDPUN;		/* msu is full */
2052*404b540aSrobert   cut--;			/* power of ten for digit */
2053*404b540aSrobert 
2054*404b540aSrobert   if (exp == 0)
2055*404b540aSrobert     {				/* simple integer [common fastpath, */
2056*404b540aSrobert       /*   used for NaNs, too] */
2057*404b540aSrobert       for (; up >= dn->lsu; up--)
2058*404b540aSrobert 	{			/* each Unit from msu */
2059*404b540aSrobert 	  u = *up;		/* contains DECDPUN digits to lay out */
2060*404b540aSrobert 	  for (; cut >= 0; c++, cut--)
2061*404b540aSrobert 	    TODIGIT (u, cut, c);
2062*404b540aSrobert 	  cut = DECDPUN - 1;	/* next Unit has all digits */
2063*404b540aSrobert 	}
2064*404b540aSrobert       *c = '\0';		/* terminate the string */
2065*404b540aSrobert       return;
2066*404b540aSrobert     }
2067*404b540aSrobert 
2068*404b540aSrobert   /* non-0 exponent -- assume plain form */
2069*404b540aSrobert   pre = dn->digits + exp;	/* digits before '.' */
2070*404b540aSrobert   e = 0;			/* no E */
2071*404b540aSrobert   if ((exp > 0) || (pre < -5))
2072*404b540aSrobert     {				/* need exponential form */
2073*404b540aSrobert       e = exp + dn->digits - 1;	/* calculate E value */
2074*404b540aSrobert       pre = 1;			/* assume one digit before '.' */
2075*404b540aSrobert       if (eng && (e != 0))
2076*404b540aSrobert 	{			/* may need to adjust */
2077*404b540aSrobert 	  Int adj;		/* adjustment */
2078*404b540aSrobert 	  /* The C remainder operator is undefined for negative numbers, so */
2079*404b540aSrobert 	  /* we must use positive remainder calculation here */
2080*404b540aSrobert 	  if (e < 0)
2081*404b540aSrobert 	    {
2082*404b540aSrobert 	      adj = (-e) % 3;
2083*404b540aSrobert 	      if (adj != 0)
2084*404b540aSrobert 		adj = 3 - adj;
2085*404b540aSrobert 	    }
2086*404b540aSrobert 	  else
2087*404b540aSrobert 	    {			/* e>0 */
2088*404b540aSrobert 	      adj = e % 3;
2089*404b540aSrobert 	    }
2090*404b540aSrobert 	  e = e - adj;
2091*404b540aSrobert 	  /* if we are dealing with zero we will use exponent which is a */
2092*404b540aSrobert 	  /* multiple of three, as expected, but there will only be the */
2093*404b540aSrobert 	  /* one zero before the E, still.  Otherwise note the padding. */
2094*404b540aSrobert 	  if (!ISZERO (dn))
2095*404b540aSrobert 	    pre += adj;
2096*404b540aSrobert 	  else
2097*404b540aSrobert 	    {			/* is zero */
2098*404b540aSrobert 	      if (adj != 0)
2099*404b540aSrobert 		{		/* 0.00Esnn needed */
2100*404b540aSrobert 		  e = e + 3;
2101*404b540aSrobert 		  pre = -(2 - adj);
2102*404b540aSrobert 		}
2103*404b540aSrobert 	    }			/* zero */
2104*404b540aSrobert 	}			/* eng */
2105*404b540aSrobert     }
2106*404b540aSrobert 
2107*404b540aSrobert   /* lay out the digits of the coefficient, adding 0s and . as needed */
2108*404b540aSrobert   u = *up;
2109*404b540aSrobert   if (pre > 0)
2110*404b540aSrobert     {				/* xxx.xxx or xx00 (engineering) form */
2111*404b540aSrobert       for (; pre > 0; pre--, c++, cut--)
2112*404b540aSrobert 	{
2113*404b540aSrobert 	  if (cut < 0)
2114*404b540aSrobert 	    {			/* need new Unit */
2115*404b540aSrobert 	      if (up == dn->lsu)
2116*404b540aSrobert 		break;		/* out of input digits (pre>digits) */
2117*404b540aSrobert 	      up--;
2118*404b540aSrobert 	      cut = DECDPUN - 1;
2119*404b540aSrobert 	      u = *up;
2120*404b540aSrobert 	    }
2121*404b540aSrobert 	  TODIGIT (u, cut, c);
2122*404b540aSrobert 	}
2123*404b540aSrobert       if (up > dn->lsu || (up == dn->lsu && cut >= 0))
2124*404b540aSrobert 	{			/* more to come, after '.' */
2125*404b540aSrobert 	  *c = '.';
2126*404b540aSrobert 	  c++;
2127*404b540aSrobert 	  for (;; c++, cut--)
2128*404b540aSrobert 	    {
2129*404b540aSrobert 	      if (cut < 0)
2130*404b540aSrobert 		{		/* need new Unit */
2131*404b540aSrobert 		  if (up == dn->lsu)
2132*404b540aSrobert 		    break;	/* out of input digits */
2133*404b540aSrobert 		  up--;
2134*404b540aSrobert 		  cut = DECDPUN - 1;
2135*404b540aSrobert 		  u = *up;
2136*404b540aSrobert 		}
2137*404b540aSrobert 	      TODIGIT (u, cut, c);
2138*404b540aSrobert 	    }
2139*404b540aSrobert 	}
2140*404b540aSrobert       else
2141*404b540aSrobert 	for (; pre > 0; pre--, c++)
2142*404b540aSrobert 	  *c = '0';		/* 0 padding (for engineering) needed */
2143*404b540aSrobert     }
2144*404b540aSrobert   else
2145*404b540aSrobert     {				/* 0.xxx or 0.000xxx form */
2146*404b540aSrobert       *c = '0';
2147*404b540aSrobert       c++;
2148*404b540aSrobert       *c = '.';
2149*404b540aSrobert       c++;
2150*404b540aSrobert       for (; pre < 0; pre++, c++)
2151*404b540aSrobert 	*c = '0';		/* add any 0's after '.' */
2152*404b540aSrobert       for (;; c++, cut--)
2153*404b540aSrobert 	{
2154*404b540aSrobert 	  if (cut < 0)
2155*404b540aSrobert 	    {			/* need new Unit */
2156*404b540aSrobert 	      if (up == dn->lsu)
2157*404b540aSrobert 		break;		/* out of input digits */
2158*404b540aSrobert 	      up--;
2159*404b540aSrobert 	      cut = DECDPUN - 1;
2160*404b540aSrobert 	      u = *up;
2161*404b540aSrobert 	    }
2162*404b540aSrobert 	  TODIGIT (u, cut, c);
2163*404b540aSrobert 	}
2164*404b540aSrobert     }
2165*404b540aSrobert 
2166*404b540aSrobert   /* Finally add the E-part, if needed.  It will never be 0, has a
2167*404b540aSrobert      base maximum and minimum of +999999999 through -999999999, but
2168*404b540aSrobert      could range down to -1999999998 for subnormal numbers */
2169*404b540aSrobert   if (e != 0)
2170*404b540aSrobert     {
2171*404b540aSrobert       Flag had = 0;		/* 1=had non-zero */
2172*404b540aSrobert       *c = 'E';
2173*404b540aSrobert       c++;
2174*404b540aSrobert       *c = '+';
2175*404b540aSrobert       c++;			/* assume positive */
2176*404b540aSrobert       u = e;			/* .. */
2177*404b540aSrobert       if (e < 0)
2178*404b540aSrobert 	{
2179*404b540aSrobert 	  *(c - 1) = '-';	/* oops, need - */
2180*404b540aSrobert 	  u = -e;		/* uInt, please */
2181*404b540aSrobert 	}
2182*404b540aSrobert       /* layout the exponent (_itoa is not ANSI C) */
2183*404b540aSrobert       for (cut = 9; cut >= 0; cut--)
2184*404b540aSrobert 	{
2185*404b540aSrobert 	  TODIGIT (u, cut, c);
2186*404b540aSrobert 	  if (*c == '0' && !had)
2187*404b540aSrobert 	    continue;		/* skip leading zeros */
2188*404b540aSrobert 	  had = 1;		/* had non-0 */
2189*404b540aSrobert 	  c++;			/* step for next */
2190*404b540aSrobert 	}			/* cut */
2191*404b540aSrobert     }
2192*404b540aSrobert   *c = '\0';			/* terminate the string (all paths) */
2193*404b540aSrobert   return;
2194*404b540aSrobert }
2195*404b540aSrobert 
2196*404b540aSrobert /* ------------------------------------------------------------------ */
2197*404b540aSrobert /* decAddOp -- add/subtract operation                                 */
2198*404b540aSrobert /*                                                                    */
2199*404b540aSrobert /*   This computes C = A + B                                          */
2200*404b540aSrobert /*                                                                    */
2201*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
2202*404b540aSrobert /*   lhs is A                                                         */
2203*404b540aSrobert /*   rhs is B                                                         */
2204*404b540aSrobert /*   set is the context                                               */
2205*404b540aSrobert /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
2206*404b540aSrobert /*   status accumulates status for the caller                         */
2207*404b540aSrobert /*                                                                    */
2208*404b540aSrobert /* C must have space for set->digits digits.                          */
2209*404b540aSrobert /* ------------------------------------------------------------------ */
2210*404b540aSrobert /* If possible, we calculate the coefficient directly into C.         */
2211*404b540aSrobert /* However, if:                                                       */
2212*404b540aSrobert /*   -- we need a digits+1 calculation because numbers are unaligned  */
2213*404b540aSrobert /*      and span more than set->digits digits                         */
2214*404b540aSrobert /*   -- a carry to digits+1 digits looks possible                     */
2215*404b540aSrobert /*   -- C is the same as A or B, and the result would destructively   */
2216*404b540aSrobert /*      overlap the A or B coefficient                                */
2217*404b540aSrobert /* then we must calculate into a temporary buffer.  In this latter    */
2218*404b540aSrobert /* case we use the local (stack) buffer if possible, and only if too  */
2219*404b540aSrobert /* long for that do we resort to malloc.                              */
2220*404b540aSrobert /*                                                                    */
2221*404b540aSrobert /* Misalignment is handled as follows:                                */
2222*404b540aSrobert /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
2223*404b540aSrobert /*   BPad: Apply the padding by a combination of shifting (whole      */
2224*404b540aSrobert /*         units) and multiplication (part units).                    */
2225*404b540aSrobert /*                                                                    */
2226*404b540aSrobert /* Addition, especially x=x+1, is speed-critical, so we take pains    */
2227*404b540aSrobert /* to make returning as fast as possible, by flagging any allocation. */
2228*404b540aSrobert /* ------------------------------------------------------------------ */
2229*404b540aSrobert static decNumber *
decAddOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,uByte negate,uInt * status)2230*404b540aSrobert decAddOp (decNumber * res, const decNumber * lhs,
2231*404b540aSrobert 	  const decNumber * rhs, decContext * set, uByte negate, uInt * status)
2232*404b540aSrobert {
2233*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
2234*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
2235*404b540aSrobert   Int rhsshift;			/* working shift (in Units) */
2236*404b540aSrobert   Int maxdigits;		/* longest logical length */
2237*404b540aSrobert   Int mult;			/* multiplier */
2238*404b540aSrobert   Int residue;			/* rounding accumulator */
2239*404b540aSrobert   uByte bits;			/* result bits */
2240*404b540aSrobert   Flag diffsign;		/* non-0 if arguments have different sign */
2241*404b540aSrobert   Unit *acc;			/* accumulator for result */
2242*404b540aSrobert   Unit accbuff[D2U (DECBUFFER + 1)];	/* local buffer [+1 is for possible */
2243*404b540aSrobert   /* final carry digit or DECBUFFER=0] */
2244*404b540aSrobert   Unit *allocacc = NULL;	/* -> allocated acc buffer, iff allocated */
2245*404b540aSrobert   Flag alloced = 0;		/* set non-0 if any allocations */
2246*404b540aSrobert   Int reqdigits = set->digits;	/* local copy; requested DIGITS */
2247*404b540aSrobert   uByte merged;			/* merged flags */
2248*404b540aSrobert   Int padding;			/* work */
2249*404b540aSrobert 
2250*404b540aSrobert #if DECCHECK
2251*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
2252*404b540aSrobert     return res;
2253*404b540aSrobert #endif
2254*404b540aSrobert 
2255*404b540aSrobert   do
2256*404b540aSrobert     {				/* protect allocated storage */
2257*404b540aSrobert #if DECSUBSET
2258*404b540aSrobert       if (!set->extended)
2259*404b540aSrobert 	{
2260*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
2261*404b540aSrobert 	  if (lhs->digits > reqdigits)
2262*404b540aSrobert 	    {
2263*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, status);
2264*404b540aSrobert 	      if (alloclhs == NULL)
2265*404b540aSrobert 		break;
2266*404b540aSrobert 	      lhs = alloclhs;
2267*404b540aSrobert 	      alloced = 1;
2268*404b540aSrobert 	    }
2269*404b540aSrobert 	  if (rhs->digits > reqdigits)
2270*404b540aSrobert 	    {
2271*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, status);
2272*404b540aSrobert 	      if (allocrhs == NULL)
2273*404b540aSrobert 		break;
2274*404b540aSrobert 	      rhs = allocrhs;
2275*404b540aSrobert 	      alloced = 1;
2276*404b540aSrobert 	    }
2277*404b540aSrobert 	}
2278*404b540aSrobert #endif
2279*404b540aSrobert       /* [following code does not require input rounding] */
2280*404b540aSrobert 
2281*404b540aSrobert       /* note whether signs differ */
2282*404b540aSrobert       diffsign = (Flag) ((lhs->bits ^ rhs->bits ^ negate) & DECNEG);
2283*404b540aSrobert 
2284*404b540aSrobert       /* handle infinities and NaNs */
2285*404b540aSrobert       merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2286*404b540aSrobert       if (merged)
2287*404b540aSrobert 	{			/* a special bit set */
2288*404b540aSrobert 	  if (merged & (DECSNAN | DECNAN))	/* a NaN */
2289*404b540aSrobert 	    decNaNs (res, lhs, rhs, status);
2290*404b540aSrobert 	  else
2291*404b540aSrobert 	    {			/* one or two infinities */
2292*404b540aSrobert 	      if (decNumberIsInfinite (lhs))
2293*404b540aSrobert 		{		/* LHS is infinity */
2294*404b540aSrobert 		  /* two infinities with different signs is invalid */
2295*404b540aSrobert 		  if (decNumberIsInfinite (rhs) && diffsign)
2296*404b540aSrobert 		    {
2297*404b540aSrobert 		      *status |= DEC_Invalid_operation;
2298*404b540aSrobert 		      break;
2299*404b540aSrobert 		    }
2300*404b540aSrobert 		  bits = lhs->bits & DECNEG;	/* get sign from LHS */
2301*404b540aSrobert 		}
2302*404b540aSrobert 	      else
2303*404b540aSrobert 		bits = (rhs->bits ^ negate) & DECNEG;	/* RHS must be Infinity */
2304*404b540aSrobert 	      bits |= DECINF;
2305*404b540aSrobert 	      decNumberZero (res);
2306*404b540aSrobert 	      res->bits = bits;	/* set +/- infinity */
2307*404b540aSrobert 	    }			/* an infinity */
2308*404b540aSrobert 	  break;
2309*404b540aSrobert 	}
2310*404b540aSrobert 
2311*404b540aSrobert       /* Quick exit for add 0s; return the non-0, modified as need be */
2312*404b540aSrobert       if (ISZERO (lhs))
2313*404b540aSrobert 	{
2314*404b540aSrobert 	  Int adjust;		/* work */
2315*404b540aSrobert 	  Int lexp = lhs->exponent;	/* save in case LHS==RES */
2316*404b540aSrobert 	  bits = lhs->bits;	/* .. */
2317*404b540aSrobert 	  residue = 0;		/* clear accumulator */
2318*404b540aSrobert 	  decCopyFit (res, rhs, set, &residue, status);	/* copy (as needed) */
2319*404b540aSrobert 	  res->bits ^= negate;	/* flip if rhs was negated */
2320*404b540aSrobert #if DECSUBSET
2321*404b540aSrobert 	  if (set->extended)
2322*404b540aSrobert 	    {			/* exponents on zeros count */
2323*404b540aSrobert #endif
2324*404b540aSrobert 	      /* exponent will be the lower of the two */
2325*404b540aSrobert 	      adjust = lexp - res->exponent;	/* adjustment needed [if -ve] */
2326*404b540aSrobert 	      if (ISZERO (res))
2327*404b540aSrobert 		{		/* both 0: special IEEE 854 rules */
2328*404b540aSrobert 		  if (adjust < 0)
2329*404b540aSrobert 		    res->exponent = lexp;	/* set exponent */
2330*404b540aSrobert 		  /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
2331*404b540aSrobert 		  if (diffsign)
2332*404b540aSrobert 		    {
2333*404b540aSrobert 		      if (set->round != DEC_ROUND_FLOOR)
2334*404b540aSrobert 			res->bits = 0;
2335*404b540aSrobert 		      else
2336*404b540aSrobert 			res->bits = DECNEG;	/* preserve 0 sign */
2337*404b540aSrobert 		    }
2338*404b540aSrobert 		}
2339*404b540aSrobert 	      else
2340*404b540aSrobert 		{		/* non-0 res */
2341*404b540aSrobert 		  if (adjust < 0)
2342*404b540aSrobert 		    {		/* 0-padding needed */
2343*404b540aSrobert 		      if ((res->digits - adjust) > set->digits)
2344*404b540aSrobert 			{
2345*404b540aSrobert 			  adjust = res->digits - set->digits;	/* to fit exactly */
2346*404b540aSrobert 			  *status |= DEC_Rounded;	/* [but exact] */
2347*404b540aSrobert 			}
2348*404b540aSrobert 		      res->digits =
2349*404b540aSrobert 			decShiftToMost (res->lsu, res->digits, -adjust);
2350*404b540aSrobert 		      res->exponent += adjust;	/* set the exponent. */
2351*404b540aSrobert 		    }
2352*404b540aSrobert 		}		/* non-0 res */
2353*404b540aSrobert #if DECSUBSET
2354*404b540aSrobert 	    }			/* extended */
2355*404b540aSrobert #endif
2356*404b540aSrobert 	  decFinish (res, set, &residue, status);	/* clean and finalize */
2357*404b540aSrobert 	  break;
2358*404b540aSrobert 	}
2359*404b540aSrobert 
2360*404b540aSrobert       if (ISZERO (rhs))
2361*404b540aSrobert 	{			/* [lhs is non-zero] */
2362*404b540aSrobert 	  Int adjust;		/* work */
2363*404b540aSrobert 	  Int rexp = rhs->exponent;	/* save in case RHS==RES */
2364*404b540aSrobert 	  bits = rhs->bits;	/* be clean */
2365*404b540aSrobert 	  residue = 0;		/* clear accumulator */
2366*404b540aSrobert 	  decCopyFit (res, lhs, set, &residue, status);	/* copy (as needed) */
2367*404b540aSrobert #if DECSUBSET
2368*404b540aSrobert 	  if (set->extended)
2369*404b540aSrobert 	    {			/* exponents on zeros count */
2370*404b540aSrobert #endif
2371*404b540aSrobert 	      /* exponent will be the lower of the two */
2372*404b540aSrobert 	      /* [0-0 case handled above] */
2373*404b540aSrobert 	      adjust = rexp - res->exponent;	/* adjustment needed [if -ve] */
2374*404b540aSrobert 	      if (adjust < 0)
2375*404b540aSrobert 		{		/* 0-padding needed */
2376*404b540aSrobert 		  if ((res->digits - adjust) > set->digits)
2377*404b540aSrobert 		    {
2378*404b540aSrobert 		      adjust = res->digits - set->digits;	/* to fit exactly */
2379*404b540aSrobert 		      *status |= DEC_Rounded;	/* [but exact] */
2380*404b540aSrobert 		    }
2381*404b540aSrobert 		  res->digits =
2382*404b540aSrobert 		    decShiftToMost (res->lsu, res->digits, -adjust);
2383*404b540aSrobert 		  res->exponent += adjust;	/* set the exponent. */
2384*404b540aSrobert 		}
2385*404b540aSrobert #if DECSUBSET
2386*404b540aSrobert 	    }			/* extended */
2387*404b540aSrobert #endif
2388*404b540aSrobert 	  decFinish (res, set, &residue, status);	/* clean and finalize */
2389*404b540aSrobert 	  break;
2390*404b540aSrobert 	}
2391*404b540aSrobert       /* [both fastpath and mainpath code below assume these cases */
2392*404b540aSrobert       /* (notably 0-0) have already been handled] */
2393*404b540aSrobert 
2394*404b540aSrobert       /* calculate the padding needed to align the operands */
2395*404b540aSrobert       padding = rhs->exponent - lhs->exponent;
2396*404b540aSrobert 
2397*404b540aSrobert       /* Fastpath cases where the numbers are aligned and normal, the RHS */
2398*404b540aSrobert       /* is all in one unit, no operand rounding is needed, and no carry, */
2399*404b540aSrobert       /* lengthening, or borrow is needed */
2400*404b540aSrobert       if (rhs->digits <= DECDPUN && padding == 0 && rhs->exponent >= set->emin	/* [some normals drop through] */
2401*404b540aSrobert 	  && rhs->digits <= reqdigits && lhs->digits <= reqdigits)
2402*404b540aSrobert 	{
2403*404b540aSrobert 	  Int partial = *lhs->lsu;
2404*404b540aSrobert 	  if (!diffsign)
2405*404b540aSrobert 	    {			/* adding */
2406*404b540aSrobert 	      Int maxv = DECDPUNMAX;	/* highest no-overflow */
2407*404b540aSrobert 	      if (lhs->digits < DECDPUN)
2408*404b540aSrobert 		maxv = powers[lhs->digits] - 1;
2409*404b540aSrobert 	      partial += *rhs->lsu;
2410*404b540aSrobert 	      if (partial <= maxv)
2411*404b540aSrobert 		{		/* no carry */
2412*404b540aSrobert 		  if (res != lhs)
2413*404b540aSrobert 		    decNumberCopy (res, lhs);	/* not in place */
2414*404b540aSrobert 		  *res->lsu = (Unit) partial;	/* [copy could have overwritten RHS] */
2415*404b540aSrobert 		  break;
2416*404b540aSrobert 		}
2417*404b540aSrobert 	      /* else drop out for careful add */
2418*404b540aSrobert 	    }
2419*404b540aSrobert 	  else
2420*404b540aSrobert 	    {			/* signs differ */
2421*404b540aSrobert 	      partial -= *rhs->lsu;
2422*404b540aSrobert 	      if (partial > 0)
2423*404b540aSrobert 		{		/* no borrow needed, and non-0 result */
2424*404b540aSrobert 		  if (res != lhs)
2425*404b540aSrobert 		    decNumberCopy (res, lhs);	/* not in place */
2426*404b540aSrobert 		  *res->lsu = (Unit) partial;
2427*404b540aSrobert 		  /* this could have reduced digits [but result>0] */
2428*404b540aSrobert 		  res->digits = decGetDigits (res->lsu, D2U (res->digits));
2429*404b540aSrobert 		  break;
2430*404b540aSrobert 		}
2431*404b540aSrobert 	      /* else drop out for careful subtract */
2432*404b540aSrobert 	    }
2433*404b540aSrobert 	}
2434*404b540aSrobert 
2435*404b540aSrobert       /* Now align (pad) the lhs or rhs so we can add or subtract them, as
2436*404b540aSrobert          necessary.  If one number is much larger than the other (that is,
2437*404b540aSrobert          if in plain form there is a least one digit between the lowest
2438*404b540aSrobert          digit or one and the highest of the other) we need to pad with up
2439*404b540aSrobert          to DIGITS-1 trailing zeros, and then apply rounding (as exotic
2440*404b540aSrobert          rounding modes may be affected by the residue).
2441*404b540aSrobert        */
2442*404b540aSrobert       rhsshift = 0;		/* rhs shift to left (padding) in Units */
2443*404b540aSrobert       bits = lhs->bits;		/* assume sign is that of LHS */
2444*404b540aSrobert       mult = 1;			/* likely multiplier */
2445*404b540aSrobert 
2446*404b540aSrobert       /* if padding==0 the operands are aligned; no padding needed */
2447*404b540aSrobert       if (padding != 0)
2448*404b540aSrobert 	{
2449*404b540aSrobert 	  /* some padding needed */
2450*404b540aSrobert 	  /* We always pad the RHS, as we can then effect any required */
2451*404b540aSrobert 	  /* padding by a combination of shifts and a multiply */
2452*404b540aSrobert 	  Flag swapped = 0;
2453*404b540aSrobert 	  if (padding < 0)
2454*404b540aSrobert 	    {			/* LHS needs the padding */
2455*404b540aSrobert 	      const decNumber *t;
2456*404b540aSrobert 	      padding = -padding;	/* will be +ve */
2457*404b540aSrobert 	      bits = (uByte) (rhs->bits ^ negate);	/* assumed sign is now that of RHS */
2458*404b540aSrobert 	      t = lhs;
2459*404b540aSrobert 	      lhs = rhs;
2460*404b540aSrobert 	      rhs = t;
2461*404b540aSrobert 	      swapped = 1;
2462*404b540aSrobert 	    }
2463*404b540aSrobert 
2464*404b540aSrobert 	  /* If, after pad, rhs would be longer than lhs by digits+1 or */
2465*404b540aSrobert 	  /* more then lhs cannot affect the answer, except as a residue, */
2466*404b540aSrobert 	  /* so we only need to pad up to a length of DIGITS+1. */
2467*404b540aSrobert 	  if (rhs->digits + padding > lhs->digits + reqdigits + 1)
2468*404b540aSrobert 	    {
2469*404b540aSrobert 	      /* The RHS is sufficient */
2470*404b540aSrobert 	      /* for residue we use the relative sign indication... */
2471*404b540aSrobert 	      Int shift = reqdigits - rhs->digits;	/* left shift needed */
2472*404b540aSrobert 	      residue = 1;	/* residue for rounding */
2473*404b540aSrobert 	      if (diffsign)
2474*404b540aSrobert 		residue = -residue;	/* signs differ */
2475*404b540aSrobert 	      /* copy, shortening if necessary */
2476*404b540aSrobert 	      decCopyFit (res, rhs, set, &residue, status);
2477*404b540aSrobert 	      /* if it was already shorter, then need to pad with zeros */
2478*404b540aSrobert 	      if (shift > 0)
2479*404b540aSrobert 		{
2480*404b540aSrobert 		  res->digits = decShiftToMost (res->lsu, res->digits, shift);
2481*404b540aSrobert 		  res->exponent -= shift;	/* adjust the exponent. */
2482*404b540aSrobert 		}
2483*404b540aSrobert 	      /* flip the result sign if unswapped and rhs was negated */
2484*404b540aSrobert 	      if (!swapped)
2485*404b540aSrobert 		res->bits ^= negate;
2486*404b540aSrobert 	      decFinish (res, set, &residue, status);	/* done */
2487*404b540aSrobert 	      break;
2488*404b540aSrobert 	    }
2489*404b540aSrobert 
2490*404b540aSrobert 	  /* LHS digits may affect result */
2491*404b540aSrobert 	  rhsshift = D2U (padding + 1) - 1;	/* this much by Unit shift .. */
2492*404b540aSrobert 	  mult = powers[padding - (rhsshift * DECDPUN)];	/* .. this by multiplication */
2493*404b540aSrobert 	}			/* padding needed */
2494*404b540aSrobert 
2495*404b540aSrobert       if (diffsign)
2496*404b540aSrobert 	mult = -mult;		/* signs differ */
2497*404b540aSrobert 
2498*404b540aSrobert       /* determine the longer operand */
2499*404b540aSrobert       maxdigits = rhs->digits + padding;	/* virtual length of RHS */
2500*404b540aSrobert       if (lhs->digits > maxdigits)
2501*404b540aSrobert 	maxdigits = lhs->digits;
2502*404b540aSrobert 
2503*404b540aSrobert       /* Decide on the result buffer to use; if possible place directly */
2504*404b540aSrobert       /* into result. */
2505*404b540aSrobert       acc = res->lsu;		/* assume build direct */
2506*404b540aSrobert       /* If destructive overlap, or the number is too long, or a carry or */
2507*404b540aSrobert       /* borrow to DIGITS+1 might be possible we must use a buffer. */
2508*404b540aSrobert       /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
2509*404b540aSrobert       if ((maxdigits >= reqdigits)	/* is, or could be, too large */
2510*404b540aSrobert 	  || (res == rhs && rhsshift > 0))
2511*404b540aSrobert 	{			/* destructive overlap */
2512*404b540aSrobert 	  /* buffer needed; choose it */
2513*404b540aSrobert 	  /* we'll need units for maxdigits digits, +1 Unit for carry or borrow */
2514*404b540aSrobert 	  Int need = D2U (maxdigits) + 1;
2515*404b540aSrobert 	  acc = accbuff;	/* assume use local buffer */
2516*404b540aSrobert 	  if (need * sizeof (Unit) > sizeof (accbuff))
2517*404b540aSrobert 	    {
2518*404b540aSrobert 	      allocacc = (Unit *) malloc (need * sizeof (Unit));
2519*404b540aSrobert 	      if (allocacc == NULL)
2520*404b540aSrobert 		{		/* hopeless -- abandon */
2521*404b540aSrobert 		  *status |= DEC_Insufficient_storage;
2522*404b540aSrobert 		  break;
2523*404b540aSrobert 		}
2524*404b540aSrobert 	      acc = allocacc;
2525*404b540aSrobert 	      alloced = 1;
2526*404b540aSrobert 	    }
2527*404b540aSrobert 	}
2528*404b540aSrobert 
2529*404b540aSrobert       res->bits = (uByte) (bits & DECNEG);	/* it's now safe to overwrite.. */
2530*404b540aSrobert       res->exponent = lhs->exponent;	/* .. operands (even if aliased) */
2531*404b540aSrobert 
2532*404b540aSrobert #if DECTRACE
2533*404b540aSrobert       decDumpAr ('A', lhs->lsu, D2U (lhs->digits));
2534*404b540aSrobert       decDumpAr ('B', rhs->lsu, D2U (rhs->digits));
2535*404b540aSrobert       printf ("  :h: %d %d\n", rhsshift, mult);
2536*404b540aSrobert #endif
2537*404b540aSrobert 
2538*404b540aSrobert       /* add [A+B*m] or subtract [A+B*(-m)] */
2539*404b540aSrobert       res->digits = decUnitAddSub (lhs->lsu, D2U (lhs->digits), rhs->lsu, D2U (rhs->digits), rhsshift, acc, mult) * DECDPUN;	/* [units -> digits] */
2540*404b540aSrobert       if (res->digits < 0)
2541*404b540aSrobert 	{			/* we borrowed */
2542*404b540aSrobert 	  res->digits = -res->digits;
2543*404b540aSrobert 	  res->bits ^= DECNEG;	/* flip the sign */
2544*404b540aSrobert 	}
2545*404b540aSrobert #if DECTRACE
2546*404b540aSrobert       decDumpAr ('+', acc, D2U (res->digits));
2547*404b540aSrobert #endif
2548*404b540aSrobert 
2549*404b540aSrobert       /* If we used a buffer we need to copy back, possibly shortening */
2550*404b540aSrobert       /* (If we didn't use buffer it must have fit, so can't need rounding */
2551*404b540aSrobert       /* and residue must be 0.) */
2552*404b540aSrobert       residue = 0;		/* clear accumulator */
2553*404b540aSrobert       if (acc != res->lsu)
2554*404b540aSrobert 	{
2555*404b540aSrobert #if DECSUBSET
2556*404b540aSrobert 	  if (set->extended)
2557*404b540aSrobert 	    {			/* round from first significant digit */
2558*404b540aSrobert #endif
2559*404b540aSrobert 	      /* remove leading zeros that we added due to rounding up to */
2560*404b540aSrobert 	      /* integral Units -- before the test for rounding. */
2561*404b540aSrobert 	      if (res->digits > reqdigits)
2562*404b540aSrobert 		res->digits = decGetDigits (acc, D2U (res->digits));
2563*404b540aSrobert 	      decSetCoeff (res, set, acc, res->digits, &residue, status);
2564*404b540aSrobert #if DECSUBSET
2565*404b540aSrobert 	    }
2566*404b540aSrobert 	  else
2567*404b540aSrobert 	    {			/* subset arithmetic rounds from original significant digit */
2568*404b540aSrobert 	      /* We may have an underestimate.  This only occurs when both */
2569*404b540aSrobert 	      /* numbers fit in DECDPUN digits and we are padding with a */
2570*404b540aSrobert 	      /* negative multiple (-10, -100...) and the top digit(s) become */
2571*404b540aSrobert 	      /* 0.  (This only matters if we are using X3.274 rules where the */
2572*404b540aSrobert 	      /* leading zero could be included in the rounding.) */
2573*404b540aSrobert 	      if (res->digits < maxdigits)
2574*404b540aSrobert 		{
2575*404b540aSrobert 		  *(acc + D2U (res->digits)) = 0;	/* ensure leading 0 is there */
2576*404b540aSrobert 		  res->digits = maxdigits;
2577*404b540aSrobert 		}
2578*404b540aSrobert 	      else
2579*404b540aSrobert 		{
2580*404b540aSrobert 		  /* remove leading zeros that we added due to rounding up to */
2581*404b540aSrobert 		  /* integral Units (but only those in excess of the original */
2582*404b540aSrobert 		  /* maxdigits length, unless extended) before test for rounding. */
2583*404b540aSrobert 		  if (res->digits > reqdigits)
2584*404b540aSrobert 		    {
2585*404b540aSrobert 		      res->digits = decGetDigits (acc, D2U (res->digits));
2586*404b540aSrobert 		      if (res->digits < maxdigits)
2587*404b540aSrobert 			res->digits = maxdigits;
2588*404b540aSrobert 		    }
2589*404b540aSrobert 		}
2590*404b540aSrobert 	      decSetCoeff (res, set, acc, res->digits, &residue, status);
2591*404b540aSrobert 	      /* Now apply rounding if needed before removing leading zeros. */
2592*404b540aSrobert 	      /* This is safe because subnormals are not a possibility */
2593*404b540aSrobert 	      if (residue != 0)
2594*404b540aSrobert 		{
2595*404b540aSrobert 		  decApplyRound (res, set, residue, status);
2596*404b540aSrobert 		  residue = 0;	/* we did what we had to do */
2597*404b540aSrobert 		}
2598*404b540aSrobert 	    }			/* subset */
2599*404b540aSrobert #endif
2600*404b540aSrobert 	}			/* used buffer */
2601*404b540aSrobert 
2602*404b540aSrobert       /* strip leading zeros [these were left on in case of subset subtract] */
2603*404b540aSrobert       res->digits = decGetDigits (res->lsu, D2U (res->digits));
2604*404b540aSrobert 
2605*404b540aSrobert       /* apply checks and rounding */
2606*404b540aSrobert       decFinish (res, set, &residue, status);
2607*404b540aSrobert 
2608*404b540aSrobert       /* "When the sum of two operands with opposite signs is exactly */
2609*404b540aSrobert       /* zero, the sign of that sum shall be '+' in all rounding modes */
2610*404b540aSrobert       /* except round toward -Infinity, in which mode that sign shall be */
2611*404b540aSrobert       /* '-'."  [Subset zeros also never have '-', set by decFinish.] */
2612*404b540aSrobert       if (ISZERO (res) && diffsign
2613*404b540aSrobert #if DECSUBSET
2614*404b540aSrobert 	  && set->extended
2615*404b540aSrobert #endif
2616*404b540aSrobert 	  && (*status & DEC_Inexact) == 0)
2617*404b540aSrobert 	{
2618*404b540aSrobert 	  if (set->round == DEC_ROUND_FLOOR)
2619*404b540aSrobert 	    res->bits |= DECNEG;	/* sign - */
2620*404b540aSrobert 	  else
2621*404b540aSrobert 	    res->bits &= ~DECNEG;	/* sign + */
2622*404b540aSrobert 	}
2623*404b540aSrobert     }
2624*404b540aSrobert   while (0);			/* end protected */
2625*404b540aSrobert 
2626*404b540aSrobert   if (alloced)
2627*404b540aSrobert     {
2628*404b540aSrobert       if (allocacc != NULL)
2629*404b540aSrobert 	free (allocacc);	/* drop any storage we used */
2630*404b540aSrobert       if (allocrhs != NULL)
2631*404b540aSrobert 	free (allocrhs);	/* .. */
2632*404b540aSrobert       if (alloclhs != NULL)
2633*404b540aSrobert 	free (alloclhs);	/* .. */
2634*404b540aSrobert     }
2635*404b540aSrobert   return res;
2636*404b540aSrobert }
2637*404b540aSrobert 
2638*404b540aSrobert /* ------------------------------------------------------------------ */
2639*404b540aSrobert /* decDivideOp -- division operation                                  */
2640*404b540aSrobert /*                                                                    */
2641*404b540aSrobert /*  This routine performs the calculations for all four division      */
2642*404b540aSrobert /*  operators (divide, divideInteger, remainder, remainderNear).      */
2643*404b540aSrobert /*                                                                    */
2644*404b540aSrobert /*  C=A op B                                                          */
2645*404b540aSrobert /*                                                                    */
2646*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
2647*404b540aSrobert /*   lhs is A                                                         */
2648*404b540aSrobert /*   rhs is B                                                         */
2649*404b540aSrobert /*   set is the context                                               */
2650*404b540aSrobert /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
2651*404b540aSrobert /*   status is the usual accumulator                                  */
2652*404b540aSrobert /*                                                                    */
2653*404b540aSrobert /* C must have space for set->digits digits.                          */
2654*404b540aSrobert /*                                                                    */
2655*404b540aSrobert /* ------------------------------------------------------------------ */
2656*404b540aSrobert /*   The underlying algorithm of this routine is the same as in the   */
2657*404b540aSrobert /*   1981 S/370 implementation, that is, non-restoring long division  */
2658*404b540aSrobert /*   with bi-unit (rather than bi-digit) estimation for each unit     */
2659*404b540aSrobert /*   multiplier.  In this pseudocode overview, complications for the  */
2660*404b540aSrobert /*   Remainder operators and division residues for exact rounding are */
2661*404b540aSrobert /*   omitted for clarity.                                             */
2662*404b540aSrobert /*                                                                    */
2663*404b540aSrobert /*     Prepare operands and handle special values                     */
2664*404b540aSrobert /*     Test for x/0 and then 0/x                                      */
2665*404b540aSrobert /*     Exp =Exp1 - Exp2                                               */
2666*404b540aSrobert /*     Exp =Exp +len(var1) -len(var2)                                 */
2667*404b540aSrobert /*     Sign=Sign1 * Sign2                                             */
2668*404b540aSrobert /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
2669*404b540aSrobert /*     Pad Var2 to same length as Var1                                */
2670*404b540aSrobert /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
2671*404b540aSrobert /*     have=0                                                         */
2672*404b540aSrobert /*     Do until (have=digits+1 OR residue=0)                          */
2673*404b540aSrobert /*       if exp<0 then if integer divide/residue then leave           */
2674*404b540aSrobert /*       this_unit=0                                                  */
2675*404b540aSrobert /*       Do forever                                                   */
2676*404b540aSrobert /*          compare numbers                                           */
2677*404b540aSrobert /*          if <0 then leave inner_loop                               */
2678*404b540aSrobert /*          if =0 then (* quick exit without subtract *) do           */
2679*404b540aSrobert /*             this_unit=this_unit+1; output this_unit                */
2680*404b540aSrobert /*             leave outer_loop; end                                  */
2681*404b540aSrobert /*          Compare lengths of numbers (mantissae):                   */
2682*404b540aSrobert /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
2683*404b540aSrobert /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
2684*404b540aSrobert /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
2685*404b540aSrobert /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
2686*404b540aSrobert /*          if mult=0 then mult=1                                     */
2687*404b540aSrobert /*          this_unit=this_unit+mult                                  */
2688*404b540aSrobert /*          subtract                                                  */
2689*404b540aSrobert /*          end inner_loop                                            */
2690*404b540aSrobert /*        if have\=0 | this_unit\=0 then do                           */
2691*404b540aSrobert /*          output this_unit                                          */
2692*404b540aSrobert /*          have=have+1; end                                          */
2693*404b540aSrobert /*        var2=var2/10                                                */
2694*404b540aSrobert /*        exp=exp-1                                                   */
2695*404b540aSrobert /*        end outer_loop                                              */
2696*404b540aSrobert /*     exp=exp+1   -- set the proper exponent                         */
2697*404b540aSrobert /*     if have=0 then generate answer=0                               */
2698*404b540aSrobert /*     Return (Result is defined by Var1)                             */
2699*404b540aSrobert /*                                                                    */
2700*404b540aSrobert /* ------------------------------------------------------------------ */
2701*404b540aSrobert /* We need two working buffers during the long division; one (digits+ */
2702*404b540aSrobert /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
2703*404b540aSrobert /* long subtractions.  These are acc and var1 respectively.           */
2704*404b540aSrobert /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
2705*404b540aSrobert /* ------------------------------------------------------------------ */
2706*404b540aSrobert static decNumber *
decDivideOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,Flag op,uInt * status)2707*404b540aSrobert decDivideOp (decNumber * res,
2708*404b540aSrobert 	     const decNumber * lhs, const decNumber * rhs,
2709*404b540aSrobert 	     decContext * set, Flag op, uInt * status)
2710*404b540aSrobert {
2711*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
2712*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
2713*404b540aSrobert   Unit accbuff[D2U (DECBUFFER + DECDPUN)];	/* local buffer */
2714*404b540aSrobert   Unit *acc = accbuff;		/* -> accumulator array for result */
2715*404b540aSrobert   Unit *allocacc = NULL;	/* -> allocated buffer, iff allocated */
2716*404b540aSrobert   Unit *accnext;		/* -> where next digit will go */
2717*404b540aSrobert   Int acclength;		/* length of acc needed [Units] */
2718*404b540aSrobert   Int accunits;			/* count of units accumulated */
2719*404b540aSrobert   Int accdigits;		/* count of digits accumulated */
2720*404b540aSrobert 
2721*404b540aSrobert   Unit varbuff[D2U (DECBUFFER * 2 + DECDPUN) * sizeof (Unit)];	/* buffer for var1 */
2722*404b540aSrobert   Unit *var1 = varbuff;		/* -> var1 array for long subtraction */
2723*404b540aSrobert   Unit *varalloc = NULL;	/* -> allocated buffer, iff used */
2724*404b540aSrobert 
2725*404b540aSrobert   const Unit *var2;		/* -> var2 array */
2726*404b540aSrobert 
2727*404b540aSrobert   Int var1units, var2units;	/* actual lengths */
2728*404b540aSrobert   Int var2ulen;			/* logical length (units) */
2729*404b540aSrobert   Int var1initpad = 0;		/* var1 initial padding (digits) */
2730*404b540aSrobert   Unit *msu1;			/* -> msu of each var */
2731*404b540aSrobert   const Unit *msu2;		/* -> msu of each var */
2732*404b540aSrobert   Int msu2plus;			/* msu2 plus one [does not vary] */
2733*404b540aSrobert   eInt msu2pair;		/* msu2 pair plus one [does not vary] */
2734*404b540aSrobert   Int maxdigits;		/* longest LHS or required acc length */
2735*404b540aSrobert   Int mult;			/* multiplier for subtraction */
2736*404b540aSrobert   Unit thisunit;		/* current unit being accumulated */
2737*404b540aSrobert   Int residue;			/* for rounding */
2738*404b540aSrobert   Int reqdigits = set->digits;	/* requested DIGITS */
2739*404b540aSrobert   Int exponent;			/* working exponent */
2740*404b540aSrobert   Int maxexponent = 0;		/* DIVIDE maximum exponent if unrounded */
2741*404b540aSrobert   uByte bits;			/* working sign */
2742*404b540aSrobert   uByte merged;			/* merged flags */
2743*404b540aSrobert   Unit *target;			/* work */
2744*404b540aSrobert   const Unit *source;		/* work */
2745*404b540aSrobert   uInt const *pow;		/* .. */
2746*404b540aSrobert   Int shift, cut;		/* .. */
2747*404b540aSrobert #if DECSUBSET
2748*404b540aSrobert   Int dropped;			/* work */
2749*404b540aSrobert #endif
2750*404b540aSrobert 
2751*404b540aSrobert #if DECCHECK
2752*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
2753*404b540aSrobert     return res;
2754*404b540aSrobert #endif
2755*404b540aSrobert 
2756*404b540aSrobert   do
2757*404b540aSrobert     {				/* protect allocated storage */
2758*404b540aSrobert #if DECSUBSET
2759*404b540aSrobert       if (!set->extended)
2760*404b540aSrobert 	{
2761*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
2762*404b540aSrobert 	  if (lhs->digits > reqdigits)
2763*404b540aSrobert 	    {
2764*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, status);
2765*404b540aSrobert 	      if (alloclhs == NULL)
2766*404b540aSrobert 		break;
2767*404b540aSrobert 	      lhs = alloclhs;
2768*404b540aSrobert 	    }
2769*404b540aSrobert 	  if (rhs->digits > reqdigits)
2770*404b540aSrobert 	    {
2771*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, status);
2772*404b540aSrobert 	      if (allocrhs == NULL)
2773*404b540aSrobert 		break;
2774*404b540aSrobert 	      rhs = allocrhs;
2775*404b540aSrobert 	    }
2776*404b540aSrobert 	}
2777*404b540aSrobert #endif
2778*404b540aSrobert       /* [following code does not require input rounding] */
2779*404b540aSrobert 
2780*404b540aSrobert       bits = (lhs->bits ^ rhs->bits) & DECNEG;	/* assumed sign for divisions */
2781*404b540aSrobert 
2782*404b540aSrobert       /* handle infinities and NaNs */
2783*404b540aSrobert       merged = (lhs->bits | rhs->bits) & DECSPECIAL;
2784*404b540aSrobert       if (merged)
2785*404b540aSrobert 	{			/* a special bit set */
2786*404b540aSrobert 	  if (merged & (DECSNAN | DECNAN))
2787*404b540aSrobert 	    {			/* one or two NaNs */
2788*404b540aSrobert 	      decNaNs (res, lhs, rhs, status);
2789*404b540aSrobert 	      break;
2790*404b540aSrobert 	    }
2791*404b540aSrobert 	  /* one or two infinities */
2792*404b540aSrobert 	  if (decNumberIsInfinite (lhs))
2793*404b540aSrobert 	    {			/* LHS (dividend) is infinite */
2794*404b540aSrobert 	      if (decNumberIsInfinite (rhs) ||	/* two infinities are invalid .. */
2795*404b540aSrobert 		  op & (REMAINDER | REMNEAR))
2796*404b540aSrobert 		{		/* as is remainder of infinity */
2797*404b540aSrobert 		  *status |= DEC_Invalid_operation;
2798*404b540aSrobert 		  break;
2799*404b540aSrobert 		}
2800*404b540aSrobert 	      /* [Note that infinity/0 raises no exceptions] */
2801*404b540aSrobert 	      decNumberZero (res);
2802*404b540aSrobert 	      res->bits = bits | DECINF;	/* set +/- infinity */
2803*404b540aSrobert 	      break;
2804*404b540aSrobert 	    }
2805*404b540aSrobert 	  else
2806*404b540aSrobert 	    {			/* RHS (divisor) is infinite */
2807*404b540aSrobert 	      residue = 0;
2808*404b540aSrobert 	      if (op & (REMAINDER | REMNEAR))
2809*404b540aSrobert 		{
2810*404b540aSrobert 		  /* result is [finished clone of] lhs */
2811*404b540aSrobert 		  decCopyFit (res, lhs, set, &residue, status);
2812*404b540aSrobert 		}
2813*404b540aSrobert 	      else
2814*404b540aSrobert 		{		/* a division */
2815*404b540aSrobert 		  decNumberZero (res);
2816*404b540aSrobert 		  res->bits = bits;	/* set +/- zero */
2817*404b540aSrobert 		  /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result */
2818*404b540aSrobert 		  /* is a 0 with infinitely negative exponent, clamped to minimum */
2819*404b540aSrobert 		  if (op & DIVIDE)
2820*404b540aSrobert 		    {
2821*404b540aSrobert 		      res->exponent = set->emin - set->digits + 1;
2822*404b540aSrobert 		      *status |= DEC_Clamped;
2823*404b540aSrobert 		    }
2824*404b540aSrobert 		}
2825*404b540aSrobert 	      decFinish (res, set, &residue, status);
2826*404b540aSrobert 	      break;
2827*404b540aSrobert 	    }
2828*404b540aSrobert 	}
2829*404b540aSrobert 
2830*404b540aSrobert       /* handle 0 rhs (x/0) */
2831*404b540aSrobert       if (ISZERO (rhs))
2832*404b540aSrobert 	{			/* x/0 is always exceptional */
2833*404b540aSrobert 	  if (ISZERO (lhs))
2834*404b540aSrobert 	    {
2835*404b540aSrobert 	      decNumberZero (res);	/* [after lhs test] */
2836*404b540aSrobert 	      *status |= DEC_Division_undefined;	/* 0/0 will become NaN */
2837*404b540aSrobert 	    }
2838*404b540aSrobert 	  else
2839*404b540aSrobert 	    {
2840*404b540aSrobert 	      decNumberZero (res);
2841*404b540aSrobert 	      if (op & (REMAINDER | REMNEAR))
2842*404b540aSrobert 		*status |= DEC_Invalid_operation;
2843*404b540aSrobert 	      else
2844*404b540aSrobert 		{
2845*404b540aSrobert 		  *status |= DEC_Division_by_zero;	/* x/0 */
2846*404b540aSrobert 		  res->bits = bits | DECINF;	/* .. is +/- Infinity */
2847*404b540aSrobert 		}
2848*404b540aSrobert 	    }
2849*404b540aSrobert 	  break;
2850*404b540aSrobert 	}
2851*404b540aSrobert 
2852*404b540aSrobert       /* handle 0 lhs (0/x) */
2853*404b540aSrobert       if (ISZERO (lhs))
2854*404b540aSrobert 	{			/* 0/x [x!=0] */
2855*404b540aSrobert #if DECSUBSET
2856*404b540aSrobert 	  if (!set->extended)
2857*404b540aSrobert 	    decNumberZero (res);
2858*404b540aSrobert 	  else
2859*404b540aSrobert 	    {
2860*404b540aSrobert #endif
2861*404b540aSrobert 	      if (op & DIVIDE)
2862*404b540aSrobert 		{
2863*404b540aSrobert 		  residue = 0;
2864*404b540aSrobert 		  exponent = lhs->exponent - rhs->exponent;	/* ideal exponent */
2865*404b540aSrobert 		  decNumberCopy (res, lhs);	/* [zeros always fit] */
2866*404b540aSrobert 		  res->bits = bits;	/* sign as computed */
2867*404b540aSrobert 		  res->exponent = exponent;	/* exponent, too */
2868*404b540aSrobert 		  decFinalize (res, set, &residue, status);	/* check exponent */
2869*404b540aSrobert 		}
2870*404b540aSrobert 	      else if (op & DIVIDEINT)
2871*404b540aSrobert 		{
2872*404b540aSrobert 		  decNumberZero (res);	/* integer 0 */
2873*404b540aSrobert 		  res->bits = bits;	/* sign as computed */
2874*404b540aSrobert 		}
2875*404b540aSrobert 	      else
2876*404b540aSrobert 		{		/* a remainder */
2877*404b540aSrobert 		  exponent = rhs->exponent;	/* [save in case overwrite] */
2878*404b540aSrobert 		  decNumberCopy (res, lhs);	/* [zeros always fit] */
2879*404b540aSrobert 		  if (exponent < res->exponent)
2880*404b540aSrobert 		    res->exponent = exponent;	/* use lower */
2881*404b540aSrobert 		}
2882*404b540aSrobert #if DECSUBSET
2883*404b540aSrobert 	    }
2884*404b540aSrobert #endif
2885*404b540aSrobert 	  break;
2886*404b540aSrobert 	}
2887*404b540aSrobert 
2888*404b540aSrobert       /* Precalculate exponent.  This starts off adjusted (and hence fits */
2889*404b540aSrobert       /* in 31 bits) and becomes the usual unadjusted exponent as the */
2890*404b540aSrobert       /* division proceeds.  The order of evaluation is important, here, */
2891*404b540aSrobert       /* to avoid wrap. */
2892*404b540aSrobert       exponent =
2893*404b540aSrobert 	(lhs->exponent + lhs->digits) - (rhs->exponent + rhs->digits);
2894*404b540aSrobert 
2895*404b540aSrobert       /* If the working exponent is -ve, then some quick exits are */
2896*404b540aSrobert       /* possible because the quotient is known to be <1 */
2897*404b540aSrobert       /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
2898*404b540aSrobert       if (exponent < 0 && !(op == DIVIDE))
2899*404b540aSrobert 	{
2900*404b540aSrobert 	  if (op & DIVIDEINT)
2901*404b540aSrobert 	    {
2902*404b540aSrobert 	      decNumberZero (res);	/* integer part is 0 */
2903*404b540aSrobert #if DECSUBSET
2904*404b540aSrobert 	      if (set->extended)
2905*404b540aSrobert #endif
2906*404b540aSrobert 		res->bits = bits;	/* set +/- zero */
2907*404b540aSrobert 	      break;
2908*404b540aSrobert 	    }
2909*404b540aSrobert 	  /* we can fastpath remainders so long as the lhs has the */
2910*404b540aSrobert 	  /* smaller (or equal) exponent */
2911*404b540aSrobert 	  if (lhs->exponent <= rhs->exponent)
2912*404b540aSrobert 	    {
2913*404b540aSrobert 	      if (op & REMAINDER || exponent < -1)
2914*404b540aSrobert 		{
2915*404b540aSrobert 		  /* It is REMAINDER or safe REMNEAR; result is [finished */
2916*404b540aSrobert 		  /* clone of] lhs  (r = x - 0*y) */
2917*404b540aSrobert 		  residue = 0;
2918*404b540aSrobert 		  decCopyFit (res, lhs, set, &residue, status);
2919*404b540aSrobert 		  decFinish (res, set, &residue, status);
2920*404b540aSrobert 		  break;
2921*404b540aSrobert 		}
2922*404b540aSrobert 	      /* [unsafe REMNEAR drops through] */
2923*404b540aSrobert 	    }
2924*404b540aSrobert 	}			/* fastpaths */
2925*404b540aSrobert 
2926*404b540aSrobert       /* We need long (slow) division; roll up the sleeves... */
2927*404b540aSrobert 
2928*404b540aSrobert       /* The accumulator will hold the quotient of the division. */
2929*404b540aSrobert       /* If it needs to be too long for stack storage, then allocate. */
2930*404b540aSrobert       acclength = D2U (reqdigits + DECDPUN);	/* in Units */
2931*404b540aSrobert       if (acclength * sizeof (Unit) > sizeof (accbuff))
2932*404b540aSrobert 	{
2933*404b540aSrobert 	  allocacc = (Unit *) malloc (acclength * sizeof (Unit));
2934*404b540aSrobert 	  if (allocacc == NULL)
2935*404b540aSrobert 	    {			/* hopeless -- abandon */
2936*404b540aSrobert 	      *status |= DEC_Insufficient_storage;
2937*404b540aSrobert 	      break;
2938*404b540aSrobert 	    }
2939*404b540aSrobert 	  acc = allocacc;	/* use the allocated space */
2940*404b540aSrobert 	}
2941*404b540aSrobert 
2942*404b540aSrobert       /* var1 is the padded LHS ready for subtractions. */
2943*404b540aSrobert       /* If it needs to be too long for stack storage, then allocate. */
2944*404b540aSrobert       /* The maximum units we need for var1 (long subtraction) is: */
2945*404b540aSrobert       /* Enough for */
2946*404b540aSrobert       /*     (rhs->digits+reqdigits-1) -- to allow full slide to right */
2947*404b540aSrobert       /* or  (lhs->digits)             -- to allow for long lhs */
2948*404b540aSrobert       /* whichever is larger */
2949*404b540aSrobert       /*   +1                -- for rounding of slide to right */
2950*404b540aSrobert       /*   +1                -- for leading 0s */
2951*404b540aSrobert       /*   +1                -- for pre-adjust if a remainder or DIVIDEINT */
2952*404b540aSrobert       /* [Note: unused units do not participate in decUnitAddSub data] */
2953*404b540aSrobert       maxdigits = rhs->digits + reqdigits - 1;
2954*404b540aSrobert       if (lhs->digits > maxdigits)
2955*404b540aSrobert 	maxdigits = lhs->digits;
2956*404b540aSrobert       var1units = D2U (maxdigits) + 2;
2957*404b540aSrobert       /* allocate a guard unit above msu1 for REMAINDERNEAR */
2958*404b540aSrobert       if (!(op & DIVIDE))
2959*404b540aSrobert 	var1units++;
2960*404b540aSrobert       if ((var1units + 1) * sizeof (Unit) > sizeof (varbuff))
2961*404b540aSrobert 	{
2962*404b540aSrobert 	  varalloc = (Unit *) malloc ((var1units + 1) * sizeof (Unit));
2963*404b540aSrobert 	  if (varalloc == NULL)
2964*404b540aSrobert 	    {			/* hopeless -- abandon */
2965*404b540aSrobert 	      *status |= DEC_Insufficient_storage;
2966*404b540aSrobert 	      break;
2967*404b540aSrobert 	    }
2968*404b540aSrobert 	  var1 = varalloc;	/* use the allocated space */
2969*404b540aSrobert 	}
2970*404b540aSrobert 
2971*404b540aSrobert       /* Extend the lhs and rhs to full long subtraction length.  The lhs */
2972*404b540aSrobert       /* is truly extended into the var1 buffer, with 0 padding, so we can */
2973*404b540aSrobert       /* subtract in place.  The rhs (var2) has virtual padding */
2974*404b540aSrobert       /* (implemented by decUnitAddSub). */
2975*404b540aSrobert       /* We allocated one guard unit above msu1 for rem=rem+rem in REMAINDERNEAR */
2976*404b540aSrobert       msu1 = var1 + var1units - 1;	/* msu of var1 */
2977*404b540aSrobert       source = lhs->lsu + D2U (lhs->digits) - 1;	/* msu of input array */
2978*404b540aSrobert       for (target = msu1; source >= lhs->lsu; source--, target--)
2979*404b540aSrobert 	*target = *source;
2980*404b540aSrobert       for (; target >= var1; target--)
2981*404b540aSrobert 	*target = 0;
2982*404b540aSrobert 
2983*404b540aSrobert       /* rhs (var2) is left-aligned with var1 at the start */
2984*404b540aSrobert       var2ulen = var1units;	/* rhs logical length (units) */
2985*404b540aSrobert       var2units = D2U (rhs->digits);	/* rhs actual length (units) */
2986*404b540aSrobert       var2 = rhs->lsu;		/* -> rhs array */
2987*404b540aSrobert       msu2 = var2 + var2units - 1;	/* -> msu of var2 [never changes] */
2988*404b540aSrobert       /* now set up the variables which we'll use for estimating the */
2989*404b540aSrobert       /* multiplication factor.  If these variables are not exact, we add */
2990*404b540aSrobert       /* 1 to make sure that we never overestimate the multiplier. */
2991*404b540aSrobert       msu2plus = *msu2;		/* it's value .. */
2992*404b540aSrobert       if (var2units > 1)
2993*404b540aSrobert 	msu2plus++;		/* .. +1 if any more */
2994*404b540aSrobert       msu2pair = (eInt) * msu2 * (DECDPUNMAX + 1);	/* top two pair .. */
2995*404b540aSrobert       if (var2units > 1)
2996*404b540aSrobert 	{			/* .. [else treat 2nd as 0] */
2997*404b540aSrobert 	  msu2pair += *(msu2 - 1);	/* .. */
2998*404b540aSrobert 	  if (var2units > 2)
2999*404b540aSrobert 	    msu2pair++;		/* .. +1 if any more */
3000*404b540aSrobert 	}
3001*404b540aSrobert 
3002*404b540aSrobert       /* Since we are working in units, the units may have leading zeros, */
3003*404b540aSrobert       /* but we calculated the exponent on the assumption that they are */
3004*404b540aSrobert       /* both left-aligned.  Adjust the exponent to compensate: add the */
3005*404b540aSrobert       /* number of leading zeros in var1 msu and subtract those in var2 msu. */
3006*404b540aSrobert       /* [We actually do this by counting the digits and negating, as */
3007*404b540aSrobert       /* lead1=DECDPUN-digits1, and similarly for lead2.] */
3008*404b540aSrobert       for (pow = &powers[1]; *msu1 >= *pow; pow++)
3009*404b540aSrobert 	exponent--;
3010*404b540aSrobert       for (pow = &powers[1]; *msu2 >= *pow; pow++)
3011*404b540aSrobert 	exponent++;
3012*404b540aSrobert 
3013*404b540aSrobert       /* Now, if doing an integer divide or remainder, we want to ensure */
3014*404b540aSrobert       /* that the result will be Unit-aligned.  To do this, we shift the */
3015*404b540aSrobert       /* var1 accumulator towards least if need be.  (It's much easier to */
3016*404b540aSrobert       /* do this now than to reassemble the residue afterwards, if we are */
3017*404b540aSrobert       /* doing a remainder.)  Also ensure the exponent is not negative. */
3018*404b540aSrobert       if (!(op & DIVIDE))
3019*404b540aSrobert 	{
3020*404b540aSrobert 	  Unit *u;
3021*404b540aSrobert 	  /* save the initial 'false' padding of var1, in digits */
3022*404b540aSrobert 	  var1initpad = (var1units - D2U (lhs->digits)) * DECDPUN;
3023*404b540aSrobert 	  /* Determine the shift to do. */
3024*404b540aSrobert 	  if (exponent < 0)
3025*404b540aSrobert 	    cut = -exponent;
3026*404b540aSrobert 	  else
3027*404b540aSrobert 	    cut = DECDPUN - exponent % DECDPUN;
3028*404b540aSrobert 	  decShiftToLeast (var1, var1units, cut);
3029*404b540aSrobert 	  exponent += cut;	/* maintain numerical value */
3030*404b540aSrobert 	  var1initpad -= cut;	/* .. and reduce padding */
3031*404b540aSrobert 	  /* clean any most-significant units we just emptied */
3032*404b540aSrobert 	  for (u = msu1; cut >= DECDPUN; cut -= DECDPUN, u--)
3033*404b540aSrobert 	    *u = 0;
3034*404b540aSrobert 	}			/* align */
3035*404b540aSrobert       else
3036*404b540aSrobert 	{			/* is DIVIDE */
3037*404b540aSrobert 	  maxexponent = lhs->exponent - rhs->exponent;	/* save */
3038*404b540aSrobert 	  /* optimization: if the first iteration will just produce 0, */
3039*404b540aSrobert 	  /* preadjust to skip it [valid for DIVIDE only] */
3040*404b540aSrobert 	  if (*msu1 < *msu2)
3041*404b540aSrobert 	    {
3042*404b540aSrobert 	      var2ulen--;	/* shift down */
3043*404b540aSrobert 	      exponent -= DECDPUN;	/* update the exponent */
3044*404b540aSrobert 	    }
3045*404b540aSrobert 	}
3046*404b540aSrobert 
3047*404b540aSrobert       /* ---- start the long-division loops ------------------------------ */
3048*404b540aSrobert       accunits = 0;		/* no units accumulated yet */
3049*404b540aSrobert       accdigits = 0;		/* .. or digits */
3050*404b540aSrobert       accnext = acc + acclength - 1;	/* -> msu of acc [NB: allows digits+1] */
3051*404b540aSrobert       for (;;)
3052*404b540aSrobert 	{			/* outer forever loop */
3053*404b540aSrobert 	  thisunit = 0;		/* current unit assumed 0 */
3054*404b540aSrobert 	  /* find the next unit */
3055*404b540aSrobert 	  for (;;)
3056*404b540aSrobert 	    {			/* inner forever loop */
3057*404b540aSrobert 	      /* strip leading zero units [from either pre-adjust or from */
3058*404b540aSrobert 	      /* subtract last time around].  Leave at least one unit. */
3059*404b540aSrobert 	      for (; *msu1 == 0 && msu1 > var1; msu1--)
3060*404b540aSrobert 		var1units--;
3061*404b540aSrobert 
3062*404b540aSrobert 	      if (var1units < var2ulen)
3063*404b540aSrobert 		break;		/* var1 too low for subtract */
3064*404b540aSrobert 	      if (var1units == var2ulen)
3065*404b540aSrobert 		{		/* unit-by-unit compare needed */
3066*404b540aSrobert 		  /* compare the two numbers, from msu */
3067*404b540aSrobert 		  Unit *pv1, v2;	/* units to compare */
3068*404b540aSrobert 		  const Unit *pv2;	/* units to compare */
3069*404b540aSrobert 		  pv2 = msu2;	/* -> msu */
3070*404b540aSrobert 		  for (pv1 = msu1;; pv1--, pv2--)
3071*404b540aSrobert 		    {
3072*404b540aSrobert 		      /* v1=*pv1 -- always OK */
3073*404b540aSrobert 		      v2 = 0;	/* assume in padding */
3074*404b540aSrobert 		      if (pv2 >= var2)
3075*404b540aSrobert 			v2 = *pv2;	/* in range */
3076*404b540aSrobert 		      if (*pv1 != v2)
3077*404b540aSrobert 			break;	/* no longer the same */
3078*404b540aSrobert 		      if (pv1 == var1)
3079*404b540aSrobert 			break;	/* done; leave pv1 as is */
3080*404b540aSrobert 		    }
3081*404b540aSrobert 		  /* here when all inspected or a difference seen */
3082*404b540aSrobert 		  if (*pv1 < v2)
3083*404b540aSrobert 		    break;	/* var1 too low to subtract */
3084*404b540aSrobert 		  if (*pv1 == v2)
3085*404b540aSrobert 		    {		/* var1 == var2 */
3086*404b540aSrobert 		      /* reach here if var1 and var2 are identical; subtraction */
3087*404b540aSrobert 		      /* would increase digit by one, and the residue will be 0 so */
3088*404b540aSrobert 		      /* we are done; leave the loop with residue set to 0. */
3089*404b540aSrobert 		      thisunit++;	/* as though subtracted */
3090*404b540aSrobert 		      *var1 = 0;	/* set var1 to 0 */
3091*404b540aSrobert 		      var1units = 1;	/* .. */
3092*404b540aSrobert 		      break;	/* from inner */
3093*404b540aSrobert 		    }		/* var1 == var2 */
3094*404b540aSrobert 		  /* *pv1>v2.  Prepare for real subtraction; the lengths are equal */
3095*404b540aSrobert 		  /* Estimate the multiplier (there's always a msu1-1)... */
3096*404b540aSrobert 		  /* Bring in two units of var2 to provide a good estimate. */
3097*404b540aSrobert 		  mult =
3098*404b540aSrobert 		    (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3099*404b540aSrobert 			    *(msu1 - 1)) / msu2pair);
3100*404b540aSrobert 		}		/* lengths the same */
3101*404b540aSrobert 	      else
3102*404b540aSrobert 		{		/* var1units > var2ulen, so subtraction is safe */
3103*404b540aSrobert 		  /* The var2 msu is one unit towards the lsu of the var1 msu, */
3104*404b540aSrobert 		  /* so we can only use one unit for var2. */
3105*404b540aSrobert 		  mult =
3106*404b540aSrobert 		    (Int) (((eInt) * msu1 * (DECDPUNMAX + 1) +
3107*404b540aSrobert 			    *(msu1 - 1)) / msu2plus);
3108*404b540aSrobert 		}
3109*404b540aSrobert 	      if (mult == 0)
3110*404b540aSrobert 		mult = 1;	/* must always be at least 1 */
3111*404b540aSrobert 	      /* subtraction needed; var1 is > var2 */
3112*404b540aSrobert 	      thisunit = (Unit) (thisunit + mult);	/* accumulate */
3113*404b540aSrobert 	      /* subtract var1-var2, into var1; only the overlap needs */
3114*404b540aSrobert 	      /* processing, as we are in place */
3115*404b540aSrobert 	      shift = var2ulen - var2units;
3116*404b540aSrobert #if DECTRACE
3117*404b540aSrobert 	      decDumpAr ('1', &var1[shift], var1units - shift);
3118*404b540aSrobert 	      decDumpAr ('2', var2, var2units);
3119*404b540aSrobert 	      printf ("m=%d\n", -mult);
3120*404b540aSrobert #endif
3121*404b540aSrobert 	      decUnitAddSub (&var1[shift], var1units - shift,
3122*404b540aSrobert 			     var2, var2units, 0, &var1[shift], -mult);
3123*404b540aSrobert #if DECTRACE
3124*404b540aSrobert 	      decDumpAr ('#', &var1[shift], var1units - shift);
3125*404b540aSrobert #endif
3126*404b540aSrobert 	      /* var1 now probably has leading zeros; these are removed at the */
3127*404b540aSrobert 	      /* top of the inner loop. */
3128*404b540aSrobert 	    }			/* inner loop */
3129*404b540aSrobert 
3130*404b540aSrobert 	  /* We have the next unit; unless it's a leading zero, add to acc */
3131*404b540aSrobert 	  if (accunits != 0 || thisunit != 0)
3132*404b540aSrobert 	    {			/* put the unit we got */
3133*404b540aSrobert 	      *accnext = thisunit;	/* store in accumulator */
3134*404b540aSrobert 	      /* account exactly for the digits we got */
3135*404b540aSrobert 	      if (accunits == 0)
3136*404b540aSrobert 		{
3137*404b540aSrobert 		  accdigits++;	/* at least one */
3138*404b540aSrobert 		  for (pow = &powers[1]; thisunit >= *pow; pow++)
3139*404b540aSrobert 		    accdigits++;
3140*404b540aSrobert 		}
3141*404b540aSrobert 	      else
3142*404b540aSrobert 		accdigits += DECDPUN;
3143*404b540aSrobert 	      accunits++;	/* update count */
3144*404b540aSrobert 	      accnext--;	/* ready for next */
3145*404b540aSrobert 	      if (accdigits > reqdigits)
3146*404b540aSrobert 		break;		/* we have all we need */
3147*404b540aSrobert 	    }
3148*404b540aSrobert 
3149*404b540aSrobert 	  /* if the residue is zero, we're done (unless divide or */
3150*404b540aSrobert 	  /* divideInteger and we haven't got enough digits yet) */
3151*404b540aSrobert 	  if (*var1 == 0 && var1units == 1)
3152*404b540aSrobert 	    {			/* residue is 0 */
3153*404b540aSrobert 	      if (op & (REMAINDER | REMNEAR))
3154*404b540aSrobert 		break;
3155*404b540aSrobert 	      if ((op & DIVIDE) && (exponent <= maxexponent))
3156*404b540aSrobert 		break;
3157*404b540aSrobert 	      /* [drop through if divideInteger] */
3158*404b540aSrobert 	    }
3159*404b540aSrobert 	  /* we've also done enough if calculating remainder or integer */
3160*404b540aSrobert 	  /* divide and we just did the last ('units') unit */
3161*404b540aSrobert 	  if (exponent == 0 && !(op & DIVIDE))
3162*404b540aSrobert 	    break;
3163*404b540aSrobert 
3164*404b540aSrobert 	  /* to get here, var1 is less than var2, so divide var2 by the per- */
3165*404b540aSrobert 	  /* Unit power of ten and go for the next digit */
3166*404b540aSrobert 	  var2ulen--;		/* shift down */
3167*404b540aSrobert 	  exponent -= DECDPUN;	/* update the exponent */
3168*404b540aSrobert 	}			/* outer loop */
3169*404b540aSrobert 
3170*404b540aSrobert       /* ---- division is complete --------------------------------------- */
3171*404b540aSrobert       /* here: acc      has at least reqdigits+1 of good results (or fewer */
3172*404b540aSrobert       /*                if early stop), starting at accnext+1 (its lsu) */
3173*404b540aSrobert       /*       var1     has any residue at the stopping point */
3174*404b540aSrobert       /*       accunits is the number of digits we collected in acc */
3175*404b540aSrobert       if (accunits == 0)
3176*404b540aSrobert 	{			/* acc is 0 */
3177*404b540aSrobert 	  accunits = 1;		/* show we have one .. */
3178*404b540aSrobert 	  accdigits = 1;	/* .. */
3179*404b540aSrobert 	  *accnext = 0;		/* .. whose value is 0 */
3180*404b540aSrobert 	}
3181*404b540aSrobert       else
3182*404b540aSrobert 	accnext++;		/* back to last placed */
3183*404b540aSrobert       /* accnext now -> lowest unit of result */
3184*404b540aSrobert 
3185*404b540aSrobert       residue = 0;		/* assume no residue */
3186*404b540aSrobert       if (op & DIVIDE)
3187*404b540aSrobert 	{
3188*404b540aSrobert 	  /* record the presence of any residue, for rounding */
3189*404b540aSrobert 	  if (*var1 != 0 || var1units > 1)
3190*404b540aSrobert 	    residue = 1;
3191*404b540aSrobert 	  else
3192*404b540aSrobert 	    {			/* no residue */
3193*404b540aSrobert 	      /* We had an exact division; clean up spurious trailing 0s. */
3194*404b540aSrobert 	      /* There will be at most DECDPUN-1, from the final multiply, */
3195*404b540aSrobert 	      /* and then only if the result is non-0 (and even) and the */
3196*404b540aSrobert 	      /* exponent is 'loose'. */
3197*404b540aSrobert #if DECDPUN>1
3198*404b540aSrobert 	      Unit lsu = *accnext;
3199*404b540aSrobert 	      if (!(lsu & 0x01) && (lsu != 0))
3200*404b540aSrobert 		{
3201*404b540aSrobert 		  /* count the trailing zeros */
3202*404b540aSrobert 		  Int drop = 0;
3203*404b540aSrobert 		  for (;; drop++)
3204*404b540aSrobert 		    {		/* [will terminate because lsu!=0] */
3205*404b540aSrobert 		      if (exponent >= maxexponent)
3206*404b540aSrobert 			break;	/* don't chop real 0s */
3207*404b540aSrobert #if DECDPUN<=4
3208*404b540aSrobert 		      if ((lsu - QUOT10 (lsu, drop + 1)
3209*404b540aSrobert 			   * powers[drop + 1]) != 0)
3210*404b540aSrobert 			break;	/* found non-0 digit */
3211*404b540aSrobert #else
3212*404b540aSrobert 		      if (lsu % powers[drop + 1] != 0)
3213*404b540aSrobert 			break;	/* found non-0 digit */
3214*404b540aSrobert #endif
3215*404b540aSrobert 		      exponent++;
3216*404b540aSrobert 		    }
3217*404b540aSrobert 		  if (drop > 0)
3218*404b540aSrobert 		    {
3219*404b540aSrobert 		      accunits = decShiftToLeast (accnext, accunits, drop);
3220*404b540aSrobert 		      accdigits = decGetDigits (accnext, accunits);
3221*404b540aSrobert 		      accunits = D2U (accdigits);
3222*404b540aSrobert 		      /* [exponent was adjusted in the loop] */
3223*404b540aSrobert 		    }
3224*404b540aSrobert 		}		/* neither odd nor 0 */
3225*404b540aSrobert #endif
3226*404b540aSrobert 	    }			/* exact divide */
3227*404b540aSrobert 	}			/* divide */
3228*404b540aSrobert       else			/* op!=DIVIDE */
3229*404b540aSrobert 	{
3230*404b540aSrobert 	  /* check for coefficient overflow */
3231*404b540aSrobert 	  if (accdigits + exponent > reqdigits)
3232*404b540aSrobert 	    {
3233*404b540aSrobert 	      *status |= DEC_Division_impossible;
3234*404b540aSrobert 	      break;
3235*404b540aSrobert 	    }
3236*404b540aSrobert 	  if (op & (REMAINDER | REMNEAR))
3237*404b540aSrobert 	    {
3238*404b540aSrobert 	      /* [Here, the exponent will be 0, because we adjusted var1 */
3239*404b540aSrobert 	      /* appropriately.] */
3240*404b540aSrobert 	      Int postshift;	/* work */
3241*404b540aSrobert 	      Flag wasodd = 0;	/* integer was odd */
3242*404b540aSrobert 	      Unit *quotlsu;	/* for save */
3243*404b540aSrobert 	      Int quotdigits;	/* .. */
3244*404b540aSrobert 
3245*404b540aSrobert 	      /* Fastpath when residue is truly 0 is worthwhile [and */
3246*404b540aSrobert 	      /* simplifies the code below] */
3247*404b540aSrobert 	      if (*var1 == 0 && var1units == 1)
3248*404b540aSrobert 		{		/* residue is 0 */
3249*404b540aSrobert 		  Int exp = lhs->exponent;	/* save min(exponents) */
3250*404b540aSrobert 		  if (rhs->exponent < exp)
3251*404b540aSrobert 		    exp = rhs->exponent;
3252*404b540aSrobert 		  decNumberZero (res);	/* 0 coefficient */
3253*404b540aSrobert #if DECSUBSET
3254*404b540aSrobert 		  if (set->extended)
3255*404b540aSrobert #endif
3256*404b540aSrobert 		    res->exponent = exp;	/* .. with proper exponent */
3257*404b540aSrobert 		  break;
3258*404b540aSrobert 		}
3259*404b540aSrobert 	      /* note if the quotient was odd */
3260*404b540aSrobert 	      if (*accnext & 0x01)
3261*404b540aSrobert 		wasodd = 1;	/* acc is odd */
3262*404b540aSrobert 	      quotlsu = accnext;	/* save in case need to reinspect */
3263*404b540aSrobert 	      quotdigits = accdigits;	/* .. */
3264*404b540aSrobert 
3265*404b540aSrobert 	      /* treat the residue, in var1, as the value to return, via acc */
3266*404b540aSrobert 	      /* calculate the unused zero digits.  This is the smaller of: */
3267*404b540aSrobert 	      /*   var1 initial padding (saved above) */
3268*404b540aSrobert 	      /*   var2 residual padding, which happens to be given by: */
3269*404b540aSrobert 	      postshift =
3270*404b540aSrobert 		var1initpad + exponent - lhs->exponent + rhs->exponent;
3271*404b540aSrobert 	      /* [the 'exponent' term accounts for the shifts during divide] */
3272*404b540aSrobert 	      if (var1initpad < postshift)
3273*404b540aSrobert 		postshift = var1initpad;
3274*404b540aSrobert 
3275*404b540aSrobert 	      /* shift var1 the requested amount, and adjust its digits */
3276*404b540aSrobert 	      var1units = decShiftToLeast (var1, var1units, postshift);
3277*404b540aSrobert 	      accnext = var1;
3278*404b540aSrobert 	      accdigits = decGetDigits (var1, var1units);
3279*404b540aSrobert 	      accunits = D2U (accdigits);
3280*404b540aSrobert 
3281*404b540aSrobert 	      exponent = lhs->exponent;	/* exponent is smaller of lhs & rhs */
3282*404b540aSrobert 	      if (rhs->exponent < exponent)
3283*404b540aSrobert 		exponent = rhs->exponent;
3284*404b540aSrobert 	      bits = lhs->bits;	/* remainder sign is always as lhs */
3285*404b540aSrobert 
3286*404b540aSrobert 	      /* Now correct the result if we are doing remainderNear; if it */
3287*404b540aSrobert 	      /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
3288*404b540aSrobert 	      /* the integer was odd then the result should be rem-rhs. */
3289*404b540aSrobert 	      if (op & REMNEAR)
3290*404b540aSrobert 		{
3291*404b540aSrobert 		  Int compare, tarunits;	/* work */
3292*404b540aSrobert 		  Unit *up;	/* .. */
3293*404b540aSrobert 
3294*404b540aSrobert 
3295*404b540aSrobert 		  /* calculate remainder*2 into the var1 buffer (which has */
3296*404b540aSrobert 		  /* 'headroom' of an extra unit and hence enough space) */
3297*404b540aSrobert 		  /* [a dedicated 'double' loop would be faster, here] */
3298*404b540aSrobert 		  tarunits =
3299*404b540aSrobert 		    decUnitAddSub (accnext, accunits, accnext, accunits, 0,
3300*404b540aSrobert 				   accnext, 1);
3301*404b540aSrobert 		  /* decDumpAr('r', accnext, tarunits); */
3302*404b540aSrobert 
3303*404b540aSrobert 		  /* Here, accnext (var1) holds tarunits Units with twice the */
3304*404b540aSrobert 		  /* remainder's coefficient, which we must now compare to the */
3305*404b540aSrobert 		  /* RHS.  The remainder's exponent may be smaller than the RHS's. */
3306*404b540aSrobert 		  compare =
3307*404b540aSrobert 		    decUnitCompare (accnext, tarunits, rhs->lsu,
3308*404b540aSrobert 				    D2U (rhs->digits),
3309*404b540aSrobert 				    rhs->exponent - exponent);
3310*404b540aSrobert 		  if (compare == BADINT)
3311*404b540aSrobert 		    {		/* deep trouble */
3312*404b540aSrobert 		      *status |= DEC_Insufficient_storage;
3313*404b540aSrobert 		      break;
3314*404b540aSrobert 		    }
3315*404b540aSrobert 
3316*404b540aSrobert 		  /* now restore the remainder by dividing by two; we know the */
3317*404b540aSrobert 		  /* lsu is even. */
3318*404b540aSrobert 		  for (up = accnext; up < accnext + tarunits; up++)
3319*404b540aSrobert 		    {
3320*404b540aSrobert 		      Int half;	/* half to add to lower unit */
3321*404b540aSrobert 		      half = *up & 0x01;
3322*404b540aSrobert 		      *up /= 2;	/* [shift] */
3323*404b540aSrobert 		      if (!half)
3324*404b540aSrobert 			continue;
3325*404b540aSrobert 		      *(up - 1) += (DECDPUNMAX + 1) / 2;
3326*404b540aSrobert 		    }
3327*404b540aSrobert 		  /* [accunits still describes the original remainder length] */
3328*404b540aSrobert 
3329*404b540aSrobert 		  if (compare > 0 || (compare == 0 && wasodd))
3330*404b540aSrobert 		    {		/* adjustment needed */
3331*404b540aSrobert 		      Int exp, expunits, exprem;	/* work */
3332*404b540aSrobert 		      /* This is effectively causing round-up of the quotient, */
3333*404b540aSrobert 		      /* so if it was the rare case where it was full and all */
3334*404b540aSrobert 		      /* nines, it would overflow and hence division-impossible */
3335*404b540aSrobert 		      /* should be raised */
3336*404b540aSrobert 		      Flag allnines = 0;	/* 1 if quotient all nines */
3337*404b540aSrobert 		      if (quotdigits == reqdigits)
3338*404b540aSrobert 			{	/* could be borderline */
3339*404b540aSrobert 			  for (up = quotlsu;; up++)
3340*404b540aSrobert 			    {
3341*404b540aSrobert 			      if (quotdigits > DECDPUN)
3342*404b540aSrobert 				{
3343*404b540aSrobert 				  if (*up != DECDPUNMAX)
3344*404b540aSrobert 				    break;	/* non-nines */
3345*404b540aSrobert 				}
3346*404b540aSrobert 			      else
3347*404b540aSrobert 				{	/* this is the last Unit */
3348*404b540aSrobert 				  if (*up == powers[quotdigits] - 1)
3349*404b540aSrobert 				    allnines = 1;
3350*404b540aSrobert 				  break;
3351*404b540aSrobert 				}
3352*404b540aSrobert 			      quotdigits -= DECDPUN;	/* checked those digits */
3353*404b540aSrobert 			    }	/* up */
3354*404b540aSrobert 			}	/* borderline check */
3355*404b540aSrobert 		      if (allnines)
3356*404b540aSrobert 			{
3357*404b540aSrobert 			  *status |= DEC_Division_impossible;
3358*404b540aSrobert 			  break;
3359*404b540aSrobert 			}
3360*404b540aSrobert 
3361*404b540aSrobert 		      /* we need rem-rhs; the sign will invert.  Again we can */
3362*404b540aSrobert 		      /* safely use var1 for the working Units array. */
3363*404b540aSrobert 		      exp = rhs->exponent - exponent;	/* RHS padding needed */
3364*404b540aSrobert 		      /* Calculate units and remainder from exponent. */
3365*404b540aSrobert 		      expunits = exp / DECDPUN;
3366*404b540aSrobert 		      exprem = exp % DECDPUN;
3367*404b540aSrobert 		      /* subtract [A+B*(-m)]; the result will always be negative */
3368*404b540aSrobert 		      accunits = -decUnitAddSub (accnext, accunits,
3369*404b540aSrobert 						 rhs->lsu, D2U (rhs->digits),
3370*404b540aSrobert 						 expunits, accnext,
3371*404b540aSrobert 						 -(Int) powers[exprem]);
3372*404b540aSrobert 		      accdigits = decGetDigits (accnext, accunits);	/* count digits exactly */
3373*404b540aSrobert 		      accunits = D2U (accdigits);	/* and recalculate the units for copy */
3374*404b540aSrobert 		      /* [exponent is as for original remainder] */
3375*404b540aSrobert 		      bits ^= DECNEG;	/* flip the sign */
3376*404b540aSrobert 		    }
3377*404b540aSrobert 		}		/* REMNEAR */
3378*404b540aSrobert 	    }			/* REMAINDER or REMNEAR */
3379*404b540aSrobert 	}			/* not DIVIDE */
3380*404b540aSrobert 
3381*404b540aSrobert       /* Set exponent and bits */
3382*404b540aSrobert       res->exponent = exponent;
3383*404b540aSrobert       res->bits = (uByte) (bits & DECNEG);	/* [cleaned] */
3384*404b540aSrobert 
3385*404b540aSrobert       /* Now the coefficient. */
3386*404b540aSrobert       decSetCoeff (res, set, accnext, accdigits, &residue, status);
3387*404b540aSrobert 
3388*404b540aSrobert       decFinish (res, set, &residue, status);	/* final cleanup */
3389*404b540aSrobert 
3390*404b540aSrobert #if DECSUBSET
3391*404b540aSrobert       /* If a divide then strip trailing zeros if subset [after round] */
3392*404b540aSrobert       if (!set->extended && (op == DIVIDE))
3393*404b540aSrobert 	decTrim (res, 0, &dropped);
3394*404b540aSrobert #endif
3395*404b540aSrobert     }
3396*404b540aSrobert   while (0);			/* end protected */
3397*404b540aSrobert 
3398*404b540aSrobert   if (varalloc != NULL)
3399*404b540aSrobert     free (varalloc);		/* drop any storage we used */
3400*404b540aSrobert   if (allocacc != NULL)
3401*404b540aSrobert     free (allocacc);		/* .. */
3402*404b540aSrobert   if (allocrhs != NULL)
3403*404b540aSrobert     free (allocrhs);		/* .. */
3404*404b540aSrobert   if (alloclhs != NULL)
3405*404b540aSrobert     free (alloclhs);		/* .. */
3406*404b540aSrobert   return res;
3407*404b540aSrobert }
3408*404b540aSrobert 
3409*404b540aSrobert /* ------------------------------------------------------------------ */
3410*404b540aSrobert /* decMultiplyOp -- multiplication operation                          */
3411*404b540aSrobert /*                                                                    */
3412*404b540aSrobert /*  This routine performs the multiplication C=A x B.                 */
3413*404b540aSrobert /*                                                                    */
3414*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
3415*404b540aSrobert /*   lhs is A                                                         */
3416*404b540aSrobert /*   rhs is B                                                         */
3417*404b540aSrobert /*   set is the context                                               */
3418*404b540aSrobert /*   status is the usual accumulator                                  */
3419*404b540aSrobert /*                                                                    */
3420*404b540aSrobert /* C must have space for set->digits digits.                          */
3421*404b540aSrobert /*                                                                    */
3422*404b540aSrobert /* ------------------------------------------------------------------ */
3423*404b540aSrobert /* Note: We use 'long' multiplication rather than Karatsuba, as the   */
3424*404b540aSrobert /* latter would give only a minor improvement for the short numbers   */
3425*404b540aSrobert /* we expect to handle most (and uses much more memory).              */
3426*404b540aSrobert /*                                                                    */
3427*404b540aSrobert /* We always have to use a buffer for the accumulator.                */
3428*404b540aSrobert /* ------------------------------------------------------------------ */
3429*404b540aSrobert static decNumber *
decMultiplyOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,uInt * status)3430*404b540aSrobert decMultiplyOp (decNumber * res, const decNumber * lhs,
3431*404b540aSrobert 	       const decNumber * rhs, decContext * set, uInt * status)
3432*404b540aSrobert {
3433*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
3434*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
3435*404b540aSrobert   Unit accbuff[D2U (DECBUFFER * 2 + 1)];	/* local buffer (+1 in case DECBUFFER==0) */
3436*404b540aSrobert   Unit *acc = accbuff;		/* -> accumulator array for exact result */
3437*404b540aSrobert   Unit *allocacc = NULL;	/* -> allocated buffer, iff allocated */
3438*404b540aSrobert   const Unit *mer, *mermsup;	/* work */
3439*404b540aSrobert   Int accunits;			/* Units of accumulator in use */
3440*404b540aSrobert   Int madlength;		/* Units in multiplicand */
3441*404b540aSrobert   Int shift;			/* Units to shift multiplicand by */
3442*404b540aSrobert   Int need;			/* Accumulator units needed */
3443*404b540aSrobert   Int exponent;			/* work */
3444*404b540aSrobert   Int residue = 0;		/* rounding residue */
3445*404b540aSrobert   uByte bits;			/* result sign */
3446*404b540aSrobert   uByte merged;			/* merged flags */
3447*404b540aSrobert 
3448*404b540aSrobert #if DECCHECK
3449*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
3450*404b540aSrobert     return res;
3451*404b540aSrobert #endif
3452*404b540aSrobert 
3453*404b540aSrobert   do
3454*404b540aSrobert     {				/* protect allocated storage */
3455*404b540aSrobert #if DECSUBSET
3456*404b540aSrobert       if (!set->extended)
3457*404b540aSrobert 	{
3458*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
3459*404b540aSrobert 	  if (lhs->digits > set->digits)
3460*404b540aSrobert 	    {
3461*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, status);
3462*404b540aSrobert 	      if (alloclhs == NULL)
3463*404b540aSrobert 		break;
3464*404b540aSrobert 	      lhs = alloclhs;
3465*404b540aSrobert 	    }
3466*404b540aSrobert 	  if (rhs->digits > set->digits)
3467*404b540aSrobert 	    {
3468*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, status);
3469*404b540aSrobert 	      if (allocrhs == NULL)
3470*404b540aSrobert 		break;
3471*404b540aSrobert 	      rhs = allocrhs;
3472*404b540aSrobert 	    }
3473*404b540aSrobert 	}
3474*404b540aSrobert #endif
3475*404b540aSrobert       /* [following code does not require input rounding] */
3476*404b540aSrobert 
3477*404b540aSrobert       /* precalculate result sign */
3478*404b540aSrobert       bits = (uByte) ((lhs->bits ^ rhs->bits) & DECNEG);
3479*404b540aSrobert 
3480*404b540aSrobert       /* handle infinities and NaNs */
3481*404b540aSrobert       merged = (lhs->bits | rhs->bits) & DECSPECIAL;
3482*404b540aSrobert       if (merged)
3483*404b540aSrobert 	{			/* a special bit set */
3484*404b540aSrobert 	  if (merged & (DECSNAN | DECNAN))
3485*404b540aSrobert 	    {			/* one or two NaNs */
3486*404b540aSrobert 	      decNaNs (res, lhs, rhs, status);
3487*404b540aSrobert 	      break;
3488*404b540aSrobert 	    }
3489*404b540aSrobert 	  /* one or two infinities. Infinity * 0 is invalid */
3490*404b540aSrobert 	  if (((lhs->bits & DECSPECIAL) == 0 && ISZERO (lhs))
3491*404b540aSrobert 	      || ((rhs->bits & DECSPECIAL) == 0 && ISZERO (rhs)))
3492*404b540aSrobert 	    {
3493*404b540aSrobert 	      *status |= DEC_Invalid_operation;
3494*404b540aSrobert 	      break;
3495*404b540aSrobert 	    }
3496*404b540aSrobert 	  decNumberZero (res);
3497*404b540aSrobert 	  res->bits = bits | DECINF;	/* infinity */
3498*404b540aSrobert 	  break;
3499*404b540aSrobert 	}
3500*404b540aSrobert 
3501*404b540aSrobert       /* For best speed, as in DMSRCN, we use the shorter number as the */
3502*404b540aSrobert       /* multiplier (rhs) and the longer as the multiplicand (lhs) */
3503*404b540aSrobert       if (lhs->digits < rhs->digits)
3504*404b540aSrobert 	{			/* swap... */
3505*404b540aSrobert 	  const decNumber *hold = lhs;
3506*404b540aSrobert 	  lhs = rhs;
3507*404b540aSrobert 	  rhs = hold;
3508*404b540aSrobert 	}
3509*404b540aSrobert 
3510*404b540aSrobert       /* if accumulator is too long for local storage, then allocate */
3511*404b540aSrobert       need = D2U (lhs->digits) + D2U (rhs->digits);	/* maximum units in result */
3512*404b540aSrobert       if (need * sizeof (Unit) > sizeof (accbuff))
3513*404b540aSrobert 	{
3514*404b540aSrobert 	  allocacc = (Unit *) malloc (need * sizeof (Unit));
3515*404b540aSrobert 	  if (allocacc == NULL)
3516*404b540aSrobert 	    {
3517*404b540aSrobert 	      *status |= DEC_Insufficient_storage;
3518*404b540aSrobert 	      break;
3519*404b540aSrobert 	    }
3520*404b540aSrobert 	  acc = allocacc;	/* use the allocated space */
3521*404b540aSrobert 	}
3522*404b540aSrobert 
3523*404b540aSrobert       /* Now the main long multiplication loop */
3524*404b540aSrobert       /* Unlike the equivalent in the IBM Java implementation, there */
3525*404b540aSrobert       /* is no advantage in calculating from msu to lsu.  So we do it */
3526*404b540aSrobert       /* by the book, as it were. */
3527*404b540aSrobert       /* Each iteration calculates ACC=ACC+MULTAND*MULT */
3528*404b540aSrobert       accunits = 1;		/* accumulator starts at '0' */
3529*404b540aSrobert       *acc = 0;			/* .. (lsu=0) */
3530*404b540aSrobert       shift = 0;		/* no multiplicand shift at first */
3531*404b540aSrobert       madlength = D2U (lhs->digits);	/* we know this won't change */
3532*404b540aSrobert       mermsup = rhs->lsu + D2U (rhs->digits);	/* -> msu+1 of multiplier */
3533*404b540aSrobert 
3534*404b540aSrobert       for (mer = rhs->lsu; mer < mermsup; mer++)
3535*404b540aSrobert 	{
3536*404b540aSrobert 	  /* Here, *mer is the next Unit in the multiplier to use */
3537*404b540aSrobert 	  /* If non-zero [optimization] add it... */
3538*404b540aSrobert 	  if (*mer != 0)
3539*404b540aSrobert 	    {
3540*404b540aSrobert 	      accunits =
3541*404b540aSrobert 		decUnitAddSub (&acc[shift], accunits - shift, lhs->lsu,
3542*404b540aSrobert 			       madlength, 0, &acc[shift], *mer) + shift;
3543*404b540aSrobert 	    }
3544*404b540aSrobert 	  else
3545*404b540aSrobert 	    {			/* extend acc with a 0; we'll use it shortly */
3546*404b540aSrobert 	      /* [this avoids length of <=0 later] */
3547*404b540aSrobert 	      *(acc + accunits) = 0;
3548*404b540aSrobert 	      accunits++;
3549*404b540aSrobert 	    }
3550*404b540aSrobert 	  /* multiply multiplicand by 10**DECDPUN for next Unit to left */
3551*404b540aSrobert 	  shift++;		/* add this for 'logical length' */
3552*404b540aSrobert 	}			/* n */
3553*404b540aSrobert #if DECTRACE
3554*404b540aSrobert       /* Show exact result */
3555*404b540aSrobert       decDumpAr ('*', acc, accunits);
3556*404b540aSrobert #endif
3557*404b540aSrobert 
3558*404b540aSrobert       /* acc now contains the exact result of the multiplication */
3559*404b540aSrobert       /* Build a decNumber from it, noting if any residue */
3560*404b540aSrobert       res->bits = bits;		/* set sign */
3561*404b540aSrobert       res->digits = decGetDigits (acc, accunits);	/* count digits exactly */
3562*404b540aSrobert 
3563*404b540aSrobert       /* We might have a 31-bit wrap in calculating the exponent. */
3564*404b540aSrobert       /* This can only happen if both input exponents are negative and */
3565*404b540aSrobert       /* both their magnitudes are large.  If we did wrap, we set a safe */
3566*404b540aSrobert       /* very negative exponent, from which decFinalize() will raise a */
3567*404b540aSrobert       /* hard underflow. */
3568*404b540aSrobert       exponent = lhs->exponent + rhs->exponent;	/* calculate exponent */
3569*404b540aSrobert       if (lhs->exponent < 0 && rhs->exponent < 0 && exponent > 0)
3570*404b540aSrobert 	exponent = -2 * DECNUMMAXE;	/* force underflow */
3571*404b540aSrobert       res->exponent = exponent;	/* OK to overwrite now */
3572*404b540aSrobert 
3573*404b540aSrobert       /* Set the coefficient.  If any rounding, residue records */
3574*404b540aSrobert       decSetCoeff (res, set, acc, res->digits, &residue, status);
3575*404b540aSrobert 
3576*404b540aSrobert       decFinish (res, set, &residue, status);	/* final cleanup */
3577*404b540aSrobert     }
3578*404b540aSrobert   while (0);			/* end protected */
3579*404b540aSrobert 
3580*404b540aSrobert   if (allocacc != NULL)
3581*404b540aSrobert     free (allocacc);		/* drop any storage we used */
3582*404b540aSrobert   if (allocrhs != NULL)
3583*404b540aSrobert     free (allocrhs);		/* .. */
3584*404b540aSrobert   if (alloclhs != NULL)
3585*404b540aSrobert     free (alloclhs);		/* .. */
3586*404b540aSrobert   return res;
3587*404b540aSrobert }
3588*404b540aSrobert 
3589*404b540aSrobert /* ------------------------------------------------------------------ */
3590*404b540aSrobert /* decQuantizeOp  -- force exponent to requested value                */
3591*404b540aSrobert /*                                                                    */
3592*404b540aSrobert /*   This computes C = op(A, B), where op adjusts the coefficient     */
3593*404b540aSrobert /*   of C (by rounding or shifting) such that the exponent (-scale)   */
3594*404b540aSrobert /*   of C has the value B or matches the exponent of B.               */
3595*404b540aSrobert /*   The numerical value of C will equal A, except for the effects of */
3596*404b540aSrobert /*   any rounding that occurred.                                      */
3597*404b540aSrobert /*                                                                    */
3598*404b540aSrobert /*   res is C, the result.  C may be A or B                           */
3599*404b540aSrobert /*   lhs is A, the number to adjust                                   */
3600*404b540aSrobert /*   rhs is B, the requested exponent                                 */
3601*404b540aSrobert /*   set is the context                                               */
3602*404b540aSrobert /*   quant is 1 for quantize or 0 for rescale                         */
3603*404b540aSrobert /*   status is the status accumulator (this can be called without     */
3604*404b540aSrobert /*          risk of control loss)                                     */
3605*404b540aSrobert /*                                                                    */
3606*404b540aSrobert /* C must have space for set->digits digits.                          */
3607*404b540aSrobert /*                                                                    */
3608*404b540aSrobert /* Unless there is an error or the result is infinite, the exponent   */
3609*404b540aSrobert /* after the operation is guaranteed to be that requested.            */
3610*404b540aSrobert /* ------------------------------------------------------------------ */
3611*404b540aSrobert static decNumber *
decQuantizeOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,Flag quant,uInt * status)3612*404b540aSrobert decQuantizeOp (decNumber * res, const decNumber * lhs,
3613*404b540aSrobert 	       const decNumber * rhs, decContext * set, Flag quant, uInt * status)
3614*404b540aSrobert {
3615*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
3616*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
3617*404b540aSrobert   const decNumber *inrhs = rhs;	/* save original rhs */
3618*404b540aSrobert   Int reqdigits = set->digits;	/* requested DIGITS */
3619*404b540aSrobert   Int reqexp;			/* requested exponent [-scale] */
3620*404b540aSrobert   Int residue = 0;		/* rounding residue */
3621*404b540aSrobert   uByte merged;			/* merged flags */
3622*404b540aSrobert   Int etiny = set->emin - (set->digits - 1);
3623*404b540aSrobert 
3624*404b540aSrobert #if DECCHECK
3625*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
3626*404b540aSrobert     return res;
3627*404b540aSrobert #endif
3628*404b540aSrobert 
3629*404b540aSrobert   do
3630*404b540aSrobert     {				/* protect allocated storage */
3631*404b540aSrobert #if DECSUBSET
3632*404b540aSrobert       if (!set->extended)
3633*404b540aSrobert 	{
3634*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
3635*404b540aSrobert 	  if (lhs->digits > reqdigits)
3636*404b540aSrobert 	    {
3637*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, status);
3638*404b540aSrobert 	      if (alloclhs == NULL)
3639*404b540aSrobert 		break;
3640*404b540aSrobert 	      lhs = alloclhs;
3641*404b540aSrobert 	    }
3642*404b540aSrobert 	  if (rhs->digits > reqdigits)
3643*404b540aSrobert 	    {			/* [this only checks lostDigits] */
3644*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, status);
3645*404b540aSrobert 	      if (allocrhs == NULL)
3646*404b540aSrobert 		break;
3647*404b540aSrobert 	      rhs = allocrhs;
3648*404b540aSrobert 	    }
3649*404b540aSrobert 	}
3650*404b540aSrobert #endif
3651*404b540aSrobert       /* [following code does not require input rounding] */
3652*404b540aSrobert 
3653*404b540aSrobert       /* Handle special values */
3654*404b540aSrobert       merged = (lhs->bits | rhs->bits) & DECSPECIAL;
3655*404b540aSrobert       if ((lhs->bits | rhs->bits) & DECSPECIAL)
3656*404b540aSrobert 	{
3657*404b540aSrobert 	  /* NaNs get usual processing */
3658*404b540aSrobert 	  if (merged & (DECSNAN | DECNAN))
3659*404b540aSrobert 	    decNaNs (res, lhs, rhs, status);
3660*404b540aSrobert 	  /* one infinity but not both is bad */
3661*404b540aSrobert 	  else if ((lhs->bits ^ rhs->bits) & DECINF)
3662*404b540aSrobert 	    *status |= DEC_Invalid_operation;
3663*404b540aSrobert 	  /* both infinity: return lhs */
3664*404b540aSrobert 	  else
3665*404b540aSrobert 	    decNumberCopy (res, lhs);	/* [nop if in place] */
3666*404b540aSrobert 	  break;
3667*404b540aSrobert 	}
3668*404b540aSrobert 
3669*404b540aSrobert       /* set requested exponent */
3670*404b540aSrobert       if (quant)
3671*404b540aSrobert 	reqexp = inrhs->exponent;	/* quantize -- match exponents */
3672*404b540aSrobert       else
3673*404b540aSrobert 	{			/* rescale -- use value of rhs */
3674*404b540aSrobert 	  /* Original rhs must be an integer that fits and is in range */
3675*404b540aSrobert #if DECSUBSET
3676*404b540aSrobert 	  reqexp = decGetInt (inrhs, set);
3677*404b540aSrobert #else
3678*404b540aSrobert 	  reqexp = decGetInt (inrhs);
3679*404b540aSrobert #endif
3680*404b540aSrobert 	}
3681*404b540aSrobert 
3682*404b540aSrobert #if DECSUBSET
3683*404b540aSrobert       if (!set->extended)
3684*404b540aSrobert 	etiny = set->emin;	/* no subnormals */
3685*404b540aSrobert #endif
3686*404b540aSrobert 
3687*404b540aSrobert       if (reqexp == BADINT	/* bad (rescale only) or .. */
3688*404b540aSrobert 	  || (reqexp < etiny)	/* < lowest */
3689*404b540aSrobert 	  || (reqexp > set->emax))
3690*404b540aSrobert 	{			/* > Emax */
3691*404b540aSrobert 	  *status |= DEC_Invalid_operation;
3692*404b540aSrobert 	  break;
3693*404b540aSrobert 	}
3694*404b540aSrobert 
3695*404b540aSrobert       /* we've processed the RHS, so we can overwrite it now if necessary */
3696*404b540aSrobert       if (ISZERO (lhs))
3697*404b540aSrobert 	{			/* zero coefficient unchanged */
3698*404b540aSrobert 	  decNumberCopy (res, lhs);	/* [nop if in place] */
3699*404b540aSrobert 	  res->exponent = reqexp;	/* .. just set exponent */
3700*404b540aSrobert #if DECSUBSET
3701*404b540aSrobert 	  if (!set->extended)
3702*404b540aSrobert 	    res->bits = 0;	/* subset specification; no -0 */
3703*404b540aSrobert #endif
3704*404b540aSrobert 	}
3705*404b540aSrobert       else
3706*404b540aSrobert 	{			/* non-zero lhs */
3707*404b540aSrobert 	  Int adjust = reqexp - lhs->exponent;	/* digit adjustment needed */
3708*404b540aSrobert 	  /* if adjusted coefficient will not fit, give up now */
3709*404b540aSrobert 	  if ((lhs->digits - adjust) > reqdigits)
3710*404b540aSrobert 	    {
3711*404b540aSrobert 	      *status |= DEC_Invalid_operation;
3712*404b540aSrobert 	      break;
3713*404b540aSrobert 	    }
3714*404b540aSrobert 
3715*404b540aSrobert 	  if (adjust > 0)
3716*404b540aSrobert 	    {			/* increasing exponent */
3717*404b540aSrobert 	      /* this will decrease the length of the coefficient by adjust */
3718*404b540aSrobert 	      /* digits, and must round as it does so */
3719*404b540aSrobert 	      decContext workset;	/* work */
3720*404b540aSrobert 	      workset = *set;	/* clone rounding, etc. */
3721*404b540aSrobert 	      workset.digits = lhs->digits - adjust;	/* set requested length */
3722*404b540aSrobert 	      /* [note that the latter can be <1, here] */
3723*404b540aSrobert 	      decCopyFit (res, lhs, &workset, &residue, status);	/* fit to result */
3724*404b540aSrobert 	      decApplyRound (res, &workset, residue, status);	/* .. and round */
3725*404b540aSrobert 	      residue = 0;	/* [used] */
3726*404b540aSrobert 	      /* If we rounded a 999s case, exponent will be off by one; */
3727*404b540aSrobert 	      /* adjust back if so. */
3728*404b540aSrobert 	      if (res->exponent > reqexp)
3729*404b540aSrobert 		{
3730*404b540aSrobert 		  res->digits = decShiftToMost (res->lsu, res->digits, 1);	/* shift */
3731*404b540aSrobert 		  res->exponent--;	/* (re)adjust the exponent. */
3732*404b540aSrobert 		}
3733*404b540aSrobert #if DECSUBSET
3734*404b540aSrobert 	      if (ISZERO (res) && !set->extended)
3735*404b540aSrobert 		res->bits = 0;	/* subset; no -0 */
3736*404b540aSrobert #endif
3737*404b540aSrobert 	    }			/* increase */
3738*404b540aSrobert 	  else			/* adjust<=0 */
3739*404b540aSrobert 	    {			/* decreasing or = exponent */
3740*404b540aSrobert 	      /* this will increase the length of the coefficient by -adjust */
3741*404b540aSrobert 	      /* digits, by adding trailing zeros. */
3742*404b540aSrobert 	      decNumberCopy (res, lhs);	/* [it will fit] */
3743*404b540aSrobert 	      /* if padding needed (adjust<0), add it now... */
3744*404b540aSrobert 	      if (adjust < 0)
3745*404b540aSrobert 		{
3746*404b540aSrobert 		  res->digits =
3747*404b540aSrobert 		    decShiftToMost (res->lsu, res->digits, -adjust);
3748*404b540aSrobert 		  res->exponent += adjust;	/* adjust the exponent */
3749*404b540aSrobert 		}
3750*404b540aSrobert 	    }			/* decrease */
3751*404b540aSrobert 	}			/* non-zero */
3752*404b540aSrobert 
3753*404b540aSrobert       /* Check for overflow [do not use Finalize in this case, as an */
3754*404b540aSrobert       /* overflow here is a "don't fit" situation] */
3755*404b540aSrobert       if (res->exponent > set->emax - res->digits + 1)
3756*404b540aSrobert 	{			/* too big */
3757*404b540aSrobert 	  *status |= DEC_Invalid_operation;
3758*404b540aSrobert 	  break;
3759*404b540aSrobert 	}
3760*404b540aSrobert       else
3761*404b540aSrobert 	{
3762*404b540aSrobert 	  decFinalize (res, set, &residue, status);	/* set subnormal flags */
3763*404b540aSrobert 	  *status &= ~DEC_Underflow;	/* suppress Underflow [754r] */
3764*404b540aSrobert 	}
3765*404b540aSrobert     }
3766*404b540aSrobert   while (0);			/* end protected */
3767*404b540aSrobert 
3768*404b540aSrobert   if (allocrhs != NULL)
3769*404b540aSrobert     free (allocrhs);		/* drop any storage we used */
3770*404b540aSrobert   if (alloclhs != NULL)
3771*404b540aSrobert     free (alloclhs);		/* .. */
3772*404b540aSrobert   return res;
3773*404b540aSrobert }
3774*404b540aSrobert 
3775*404b540aSrobert /* ------------------------------------------------------------------ */
3776*404b540aSrobert /* decCompareOp -- compare, min, or max two Numbers                   */
3777*404b540aSrobert /*                                                                    */
3778*404b540aSrobert /*   This computes C = A ? B and returns the signum (as a Number)     */
3779*404b540aSrobert /*   for COMPARE or the maximum or minimum (for COMPMAX and COMPMIN). */
3780*404b540aSrobert /*                                                                    */
3781*404b540aSrobert /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
3782*404b540aSrobert /*   lhs is A                                                         */
3783*404b540aSrobert /*   rhs is B                                                         */
3784*404b540aSrobert /*   set is the context                                               */
3785*404b540aSrobert /*   op  is the operation flag                                        */
3786*404b540aSrobert /*   status is the usual accumulator                                  */
3787*404b540aSrobert /*                                                                    */
3788*404b540aSrobert /* C must have space for one digit for COMPARE or set->digits for     */
3789*404b540aSrobert /* COMPMAX and COMPMIN.                                               */
3790*404b540aSrobert /* ------------------------------------------------------------------ */
3791*404b540aSrobert /* The emphasis here is on speed for common cases, and avoiding       */
3792*404b540aSrobert /* coefficient comparison if possible.                                */
3793*404b540aSrobert /* ------------------------------------------------------------------ */
3794*404b540aSrobert decNumber *
decCompareOp(decNumber * res,const decNumber * lhs,const decNumber * rhs,decContext * set,Flag op,uInt * status)3795*404b540aSrobert decCompareOp (decNumber * res, const decNumber * lhs, const decNumber * rhs,
3796*404b540aSrobert 	      decContext * set, Flag op, uInt * status)
3797*404b540aSrobert {
3798*404b540aSrobert   decNumber *alloclhs = NULL;	/* non-NULL if rounded lhs allocated */
3799*404b540aSrobert   decNumber *allocrhs = NULL;	/* .., rhs */
3800*404b540aSrobert   Int result = 0;		/* default result value */
3801*404b540aSrobert   uByte merged;			/* merged flags */
3802*404b540aSrobert   uByte bits = 0;		/* non-0 for NaN */
3803*404b540aSrobert 
3804*404b540aSrobert #if DECCHECK
3805*404b540aSrobert   if (decCheckOperands (res, lhs, rhs, set))
3806*404b540aSrobert     return res;
3807*404b540aSrobert #endif
3808*404b540aSrobert 
3809*404b540aSrobert   do
3810*404b540aSrobert     {				/* protect allocated storage */
3811*404b540aSrobert #if DECSUBSET
3812*404b540aSrobert       if (!set->extended)
3813*404b540aSrobert 	{
3814*404b540aSrobert 	  /* reduce operands and set lostDigits status, as needed */
3815*404b540aSrobert 	  if (lhs->digits > set->digits)
3816*404b540aSrobert 	    {
3817*404b540aSrobert 	      alloclhs = decRoundOperand (lhs, set, status);
3818*404b540aSrobert 	      if (alloclhs == NULL)
3819*404b540aSrobert 		{
3820*404b540aSrobert 		  result = BADINT;
3821*404b540aSrobert 		  break;
3822*404b540aSrobert 		}
3823*404b540aSrobert 	      lhs = alloclhs;
3824*404b540aSrobert 	    }
3825*404b540aSrobert 	  if (rhs->digits > set->digits)
3826*404b540aSrobert 	    {
3827*404b540aSrobert 	      allocrhs = decRoundOperand (rhs, set, status);
3828*404b540aSrobert 	      if (allocrhs == NULL)
3829*404b540aSrobert 		{
3830*404b540aSrobert 		  result = BADINT;
3831*404b540aSrobert 		  break;
3832*404b540aSrobert 		}
3833*404b540aSrobert 	      rhs = allocrhs;
3834*404b540aSrobert 	    }
3835*404b540aSrobert 	}
3836*404b540aSrobert #endif
3837*404b540aSrobert       /* [following code does not require input rounding] */
3838*404b540aSrobert 
3839*404b540aSrobert       /* handle NaNs now; let infinities drop through */
3840*404b540aSrobert       /* +++ review sNaN handling with 754r, for now assumes sNaN */
3841*404b540aSrobert       /* (even just one) leads to NaN. */
3842*404b540aSrobert       merged = (lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
3843*404b540aSrobert       if (merged)
3844*404b540aSrobert 	{			/* a NaN bit set */
3845*404b540aSrobert 	  if (op == COMPARE);
3846*404b540aSrobert 	  else if (merged & DECSNAN);
3847*404b540aSrobert 	  else
3848*404b540aSrobert 	    {			/* 754r rules for MIN and MAX ignore single NaN */
3849*404b540aSrobert 	      /* here if MIN or MAX, and one or two quiet NaNs */
3850*404b540aSrobert 	      if (lhs->bits & rhs->bits & DECNAN);
3851*404b540aSrobert 	      else
3852*404b540aSrobert 		{		/* just one quiet NaN */
3853*404b540aSrobert 		  /* force choice to be the non-NaN operand */
3854*404b540aSrobert 		  op = COMPMAX;
3855*404b540aSrobert 		  if (lhs->bits & DECNAN)
3856*404b540aSrobert 		    result = -1;	/* pick rhs */
3857*404b540aSrobert 		  else
3858*404b540aSrobert 		    result = +1;	/* pick lhs */
3859*404b540aSrobert 		  break;
3860*404b540aSrobert 		}
3861*404b540aSrobert 	    }
3862*404b540aSrobert 	  op = COMPNAN;		/* use special path */
3863*404b540aSrobert 	  decNaNs (res, lhs, rhs, status);
3864*404b540aSrobert 	  break;
3865*404b540aSrobert 	}
3866*404b540aSrobert 
3867*404b540aSrobert       result = decCompare (lhs, rhs);	/* we have numbers */
3868*404b540aSrobert     }
3869*404b540aSrobert   while (0);			/* end protected */
3870*404b540aSrobert 
3871*404b540aSrobert   if (result == BADINT)
3872*404b540aSrobert     *status |= DEC_Insufficient_storage;	/* rare */
3873*404b540aSrobert   else
3874*404b540aSrobert     {
3875*404b540aSrobert       if (op == COMPARE)
3876*404b540aSrobert 	{			/* return signum */
3877*404b540aSrobert 	  decNumberZero (res);	/* [always a valid result] */
3878*404b540aSrobert 	  if (result == 0)
3879*404b540aSrobert 	    res->bits = bits;	/* (maybe qNaN) */
3880*404b540aSrobert 	  else
3881*404b540aSrobert 	    {
3882*404b540aSrobert 	      *res->lsu = 1;
3883*404b540aSrobert 	      if (result < 0)
3884*404b540aSrobert 		res->bits = DECNEG;
3885*404b540aSrobert 	    }
3886*404b540aSrobert 	}
3887*404b540aSrobert       else if (op == COMPNAN);	/* special, drop through */
3888*404b540aSrobert       else
3889*404b540aSrobert 	{			/* MAX or MIN, non-NaN result */
3890*404b540aSrobert 	  Int residue = 0;	/* rounding accumulator */
3891*404b540aSrobert 	  /* choose the operand for the result */
3892*404b540aSrobert 	  const decNumber *choice;
3893*404b540aSrobert 	  if (result == 0)
3894*404b540aSrobert 	    {			/* operands are numerically equal */
3895*404b540aSrobert 	      /* choose according to sign then exponent (see 754r) */
3896*404b540aSrobert 	      uByte slhs = (lhs->bits & DECNEG);
3897*404b540aSrobert 	      uByte srhs = (rhs->bits & DECNEG);
3898*404b540aSrobert #if DECSUBSET
3899*404b540aSrobert 	      if (!set->extended)
3900*404b540aSrobert 		{		/* subset: force left-hand */
3901*404b540aSrobert 		  op = COMPMAX;
3902*404b540aSrobert 		  result = +1;
3903*404b540aSrobert 		}
3904*404b540aSrobert 	      else
3905*404b540aSrobert #endif
3906*404b540aSrobert 	      if (slhs != srhs)
3907*404b540aSrobert 		{		/* signs differ */
3908*404b540aSrobert 		  if (slhs)
3909*404b540aSrobert 		    result = -1;	/* rhs is max */
3910*404b540aSrobert 		  else
3911*404b540aSrobert 		    result = +1;	/* lhs is max */
3912*404b540aSrobert 		}
3913*404b540aSrobert 	      else if (slhs && srhs)
3914*404b540aSrobert 		{		/* both negative */
3915*404b540aSrobert 		  if (lhs->exponent < rhs->exponent)
3916*404b540aSrobert 		    result = +1;
3917*404b540aSrobert 		  else
3918*404b540aSrobert 		    result = -1;
3919*404b540aSrobert 		  /* [if equal, we use lhs, technically identical] */
3920*404b540aSrobert 		}
3921*404b540aSrobert 	      else
3922*404b540aSrobert 		{		/* both positive */
3923*404b540aSrobert 		  if (lhs->exponent > rhs->exponent)
3924*404b540aSrobert 		    result = +1;
3925*404b540aSrobert 		  else
3926*404b540aSrobert 		    result = -1;
3927*404b540aSrobert 		  /* [ditto] */
3928*404b540aSrobert 		}
3929*404b540aSrobert 	    }			/* numerically equal */
3930*404b540aSrobert 	  /* here result will be non-0 */
3931*404b540aSrobert 	  if (op == COMPMIN)
3932*404b540aSrobert 	    result = -result;	/* reverse if looking for MIN */
3933*404b540aSrobert 	  choice = (result > 0 ? lhs : rhs);	/* choose */
3934*404b540aSrobert 	  /* copy chosen to result, rounding if need be */
3935*404b540aSrobert 	  decCopyFit (res, choice, set, &residue, status);
3936*404b540aSrobert 	  decFinish (res, set, &residue, status);
3937*404b540aSrobert 	}
3938*404b540aSrobert     }
3939*404b540aSrobert   if (allocrhs != NULL)
3940*404b540aSrobert     free (allocrhs);		/* free any storage we used */
3941*404b540aSrobert   if (alloclhs != NULL)
3942*404b540aSrobert     free (alloclhs);		/* .. */
3943*404b540aSrobert   return res;
3944*404b540aSrobert }
3945*404b540aSrobert 
3946*404b540aSrobert /* ------------------------------------------------------------------ */
3947*404b540aSrobert /* decCompare -- compare two decNumbers by numerical value            */
3948*404b540aSrobert /*                                                                    */
3949*404b540aSrobert /*  This routine compares A ? B without altering them.                */
3950*404b540aSrobert /*                                                                    */
3951*404b540aSrobert /*  Arg1 is A, a decNumber which is not a NaN                         */
3952*404b540aSrobert /*  Arg2 is B, a decNumber which is not a NaN                         */
3953*404b540aSrobert /*                                                                    */
3954*404b540aSrobert /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
3955*404b540aSrobert /*  (the only possible failure is an allocation error)                */
3956*404b540aSrobert /* ------------------------------------------------------------------ */
3957*404b540aSrobert /* This could be merged into decCompareOp */
3958*404b540aSrobert static Int
decCompare(const decNumber * lhs,const decNumber * rhs)3959*404b540aSrobert decCompare (const decNumber * lhs, const decNumber * rhs)
3960*404b540aSrobert {
3961*404b540aSrobert   Int result;			/* result value */
3962*404b540aSrobert   Int sigr;			/* rhs signum */
3963*404b540aSrobert   Int compare;			/* work */
3964*404b540aSrobert   result = 1;			/* assume signum(lhs) */
3965*404b540aSrobert   if (ISZERO (lhs))
3966*404b540aSrobert     result = 0;
3967*404b540aSrobert   else if (decNumberIsNegative (lhs))
3968*404b540aSrobert     result = -1;
3969*404b540aSrobert   sigr = 1;			/* compute signum(rhs) */
3970*404b540aSrobert   if (ISZERO (rhs))
3971*404b540aSrobert     sigr = 0;
3972*404b540aSrobert   else if (decNumberIsNegative (rhs))
3973*404b540aSrobert     sigr = -1;
3974*404b540aSrobert   if (result > sigr)
3975*404b540aSrobert     return +1;			/* L > R, return 1 */
3976*404b540aSrobert   if (result < sigr)
3977*404b540aSrobert     return -1;			/* R < L, return -1 */
3978*404b540aSrobert 
3979*404b540aSrobert   /* signums are the same */
3980*404b540aSrobert   if (result == 0)
3981*404b540aSrobert     return 0;			/* both 0 */
3982*404b540aSrobert   /* Both non-zero */
3983*404b540aSrobert   if ((lhs->bits | rhs->bits) & DECINF)
3984*404b540aSrobert     {				/* one or more infinities */
3985*404b540aSrobert       if (lhs->bits == rhs->bits)
3986*404b540aSrobert 	result = 0;		/* both the same */
3987*404b540aSrobert       else if (decNumberIsInfinite (rhs))
3988*404b540aSrobert 	result = -result;
3989*404b540aSrobert       return result;
3990*404b540aSrobert     }
3991*404b540aSrobert 
3992*404b540aSrobert   /* we must compare the coefficients, allowing for exponents */
3993*404b540aSrobert   if (lhs->exponent > rhs->exponent)
3994*404b540aSrobert     {				/* LHS exponent larger */
3995*404b540aSrobert       /* swap sides, and sign */
3996*404b540aSrobert       const decNumber *temp = lhs;
3997*404b540aSrobert       lhs = rhs;
3998*404b540aSrobert       rhs = temp;
3999*404b540aSrobert       result = -result;
4000*404b540aSrobert     }
4001*404b540aSrobert 
4002*404b540aSrobert   compare = decUnitCompare (lhs->lsu, D2U (lhs->digits),
4003*404b540aSrobert 			    rhs->lsu, D2U (rhs->digits),
4004*404b540aSrobert 			    rhs->exponent - lhs->exponent);
4005*404b540aSrobert 
4006*404b540aSrobert   if (compare != BADINT)
4007*404b540aSrobert     compare *= result;		/* comparison succeeded */
4008*404b540aSrobert   return compare;		/* what we got */
4009*404b540aSrobert }
4010*404b540aSrobert 
4011*404b540aSrobert /* ------------------------------------------------------------------ */
4012*404b540aSrobert /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
4013*404b540aSrobert /*                                                                    */
4014*404b540aSrobert /*  This routine compares A ? B*10**E where A and B are unit arrays   */
4015*404b540aSrobert /*  A is a plain integer                                              */
4016*404b540aSrobert /*  B has an exponent of E (which must be non-negative)               */
4017*404b540aSrobert /*                                                                    */
4018*404b540aSrobert /*  Arg1 is A first Unit (lsu)                                        */
4019*404b540aSrobert /*  Arg2 is A length in Units                                         */
4020*404b540aSrobert /*  Arg3 is B first Unit (lsu)                                        */
4021*404b540aSrobert /*  Arg4 is B length in Units                                         */
4022*404b540aSrobert /*  Arg5 is E                                                         */
4023*404b540aSrobert /*                                                                    */
4024*404b540aSrobert /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
4025*404b540aSrobert /*  (the only possible failure is an allocation error)                */
4026*404b540aSrobert /* ------------------------------------------------------------------ */
4027*404b540aSrobert static Int
decUnitCompare(const Unit * a,Int alength,const Unit * b,Int blength,Int exp)4028*404b540aSrobert decUnitCompare (const Unit * a, Int alength, const Unit * b, Int blength, Int exp)
4029*404b540aSrobert {
4030*404b540aSrobert   Unit *acc;			/* accumulator for result */
4031*404b540aSrobert   Unit accbuff[D2U (DECBUFFER + 1)];	/* local buffer */
4032*404b540aSrobert   Unit *allocacc = NULL;	/* -> allocated acc buffer, iff allocated */
4033*404b540aSrobert   Int accunits, need;		/* units in use or needed for acc */
4034*404b540aSrobert   const Unit *l, *r, *u;	/* work */
4035*404b540aSrobert   Int expunits, exprem, result;	/* .. */
4036*404b540aSrobert 
4037*404b540aSrobert   if (exp == 0)
4038*404b540aSrobert     {				/* aligned; fastpath */
4039*404b540aSrobert       if (alength > blength)
4040*404b540aSrobert 	return 1;
4041*404b540aSrobert       if (alength < blength)
4042*404b540aSrobert 	return -1;
4043*404b540aSrobert       /* same number of units in both -- need unit-by-unit compare */
4044*404b540aSrobert       l = a + alength - 1;
4045*404b540aSrobert       r = b + alength - 1;
4046*404b540aSrobert       for (; l >= a; l--, r--)
4047*404b540aSrobert 	{
4048*404b540aSrobert 	  if (*l > *r)
4049*404b540aSrobert 	    return 1;
4050*404b540aSrobert 	  if (*l < *r)
4051*404b540aSrobert 	    return -1;
4052*404b540aSrobert 	}
4053*404b540aSrobert       return 0;			/* all units match */
4054*404b540aSrobert     }				/* aligned */
4055*404b540aSrobert 
4056*404b540aSrobert   /* Unaligned.  If one is >1 unit longer than the other, padded */
4057*404b540aSrobert   /* approximately, then we can return easily */
4058*404b540aSrobert   if (alength > blength + (Int) D2U (exp))
4059*404b540aSrobert     return 1;
4060*404b540aSrobert   if (alength + 1 < blength + (Int) D2U (exp))
4061*404b540aSrobert     return -1;
4062*404b540aSrobert 
4063*404b540aSrobert   /* We need to do a real subtract.  For this, we need a result buffer */
4064*404b540aSrobert   /* even though we only are interested in the sign.  Its length needs */
4065*404b540aSrobert   /* to be the larger of alength and padded blength, +2 */
4066*404b540aSrobert   need = blength + D2U (exp);	/* maximum real length of B */
4067*404b540aSrobert   if (need < alength)
4068*404b540aSrobert     need = alength;
4069*404b540aSrobert   need += 2;
4070*404b540aSrobert   acc = accbuff;		/* assume use local buffer */
4071*404b540aSrobert   if (need * sizeof (Unit) > sizeof (accbuff))
4072*404b540aSrobert     {
4073*404b540aSrobert       allocacc = (Unit *) malloc (need * sizeof (Unit));
4074*404b540aSrobert       if (allocacc == NULL)
4075*404b540aSrobert 	return BADINT;		/* hopeless -- abandon */
4076*404b540aSrobert       acc = allocacc;
4077*404b540aSrobert     }
4078*404b540aSrobert   /* Calculate units and remainder from exponent. */
4079*404b540aSrobert   expunits = exp / DECDPUN;
4080*404b540aSrobert   exprem = exp % DECDPUN;
4081*404b540aSrobert   /* subtract [A+B*(-m)] */
4082*404b540aSrobert   accunits = decUnitAddSub (a, alength, b, blength, expunits, acc,
4083*404b540aSrobert 			    -(Int) powers[exprem]);
4084*404b540aSrobert   /* [UnitAddSub result may have leading zeros, even on zero] */
4085*404b540aSrobert   if (accunits < 0)
4086*404b540aSrobert     result = -1;		/* negative result */
4087*404b540aSrobert   else
4088*404b540aSrobert     {				/* non-negative result */
4089*404b540aSrobert       /* check units of the result before freeing any storage */
4090*404b540aSrobert       for (u = acc; u < acc + accunits - 1 && *u == 0;)
4091*404b540aSrobert 	u++;
4092*404b540aSrobert       result = (*u == 0 ? 0 : +1);
4093*404b540aSrobert     }
4094*404b540aSrobert   /* clean up and return the result */
4095*404b540aSrobert   if (allocacc != NULL)
4096*404b540aSrobert     free (allocacc);		/* drop any storage we used */
4097*404b540aSrobert   return result;
4098*404b540aSrobert }
4099*404b540aSrobert 
4100*404b540aSrobert /* ------------------------------------------------------------------ */
4101*404b540aSrobert /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
4102*404b540aSrobert /*                                                                    */
4103*404b540aSrobert /*  This routine performs the calculation:                            */
4104*404b540aSrobert /*                                                                    */
4105*404b540aSrobert /*  C=A+(B*M)                                                         */
4106*404b540aSrobert /*                                                                    */
4107*404b540aSrobert /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
4108*404b540aSrobert /*                                                                    */
4109*404b540aSrobert /*  A may be shorter or longer than B.                                */
4110*404b540aSrobert /*                                                                    */
4111*404b540aSrobert /*  Leading zeros are not removed after a calculation.  The result is */
4112*404b540aSrobert /*  either the same length as the longer of A and B (adding any       */
4113*404b540aSrobert /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
4114*404b540aSrobert /*                                                                    */
4115*404b540aSrobert /*  A and B content are not altered unless C is also A or B.          */
4116*404b540aSrobert /*  C may be the same array as A or B, but only if no zero padding is */
4117*404b540aSrobert /*  requested (that is, C may be B only if bshift==0).                */
4118*404b540aSrobert /*  C is filled from the lsu; only those units necessary to complete  */
4119*404b540aSrobert /*  the calculation are referenced.                                   */
4120*404b540aSrobert /*                                                                    */
4121*404b540aSrobert /*  Arg1 is A first Unit (lsu)                                        */
4122*404b540aSrobert /*  Arg2 is A length in Units                                         */
4123*404b540aSrobert /*  Arg3 is B first Unit (lsu)                                        */
4124*404b540aSrobert /*  Arg4 is B length in Units                                         */
4125*404b540aSrobert /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
4126*404b540aSrobert /*  Arg6 is C first Unit (lsu)                                        */
4127*404b540aSrobert /*  Arg7 is M, the multiplier                                         */
4128*404b540aSrobert /*                                                                    */
4129*404b540aSrobert /*  returns the count of Units written to C, which will be non-zero   */
4130*404b540aSrobert /*  and negated if the result is negative.  That is, the sign of the  */
4131*404b540aSrobert /*  returned Int is the sign of the result (positive for zero) and    */
4132*404b540aSrobert /*  the absolute value of the Int is the count of Units.              */
4133*404b540aSrobert /*                                                                    */
4134*404b540aSrobert /*  It is the caller's responsibility to make sure that C size is     */
4135*404b540aSrobert /*  safe, allowing space if necessary for a one-Unit carry.           */
4136*404b540aSrobert /*                                                                    */
4137*404b540aSrobert /*  This routine is severely performance-critical; *any* change here  */
4138*404b540aSrobert /*  must be measured (timed) to assure no performance degradation.    */
4139*404b540aSrobert /*  In particular, trickery here tends to be counter-productive, as   */
4140*404b540aSrobert /*  increased complexity of code hurts register optimizations on      */
4141*404b540aSrobert /*  register-poor architectures.  Avoiding divisions is nearly        */
4142*404b540aSrobert /*  always a Good Idea, however.                                      */
4143*404b540aSrobert /*                                                                    */
4144*404b540aSrobert /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
4145*404b540aSrobert /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
4146*404b540aSrobert /* ------------------------------------------------------------------ */
4147*404b540aSrobert static Int
decUnitAddSub(const Unit * a,Int alength,const Unit * b,Int blength,Int bshift,Unit * c,Int m)4148*404b540aSrobert decUnitAddSub (const Unit * a, Int alength,
4149*404b540aSrobert 	       const Unit * b, Int blength, Int bshift, Unit * c, Int m)
4150*404b540aSrobert {
4151*404b540aSrobert   const Unit *alsu = a;		/* A lsu [need to remember it] */
4152*404b540aSrobert   Unit *clsu = c;		/* C ditto */
4153*404b540aSrobert   Unit *minC;			/* low water mark for C */
4154*404b540aSrobert   Unit *maxC;			/* high water mark for C */
4155*404b540aSrobert   eInt carry = 0;		/* carry integer (could be Long) */
4156*404b540aSrobert   Int add;			/* work */
4157*404b540aSrobert #if DECDPUN==4			/* myriadal */
4158*404b540aSrobert   Int est;			/* estimated quotient */
4159*404b540aSrobert #endif
4160*404b540aSrobert 
4161*404b540aSrobert #if DECTRACE
4162*404b540aSrobert   if (alength < 1 || blength < 1)
4163*404b540aSrobert     printf ("decUnitAddSub: alen blen m %d %d [%d]\n", alength, blength, m);
4164*404b540aSrobert #endif
4165*404b540aSrobert 
4166*404b540aSrobert   maxC = c + alength;		/* A is usually the longer */
4167*404b540aSrobert   minC = c + blength;		/* .. and B the shorter */
4168*404b540aSrobert   if (bshift != 0)
4169*404b540aSrobert     {				/* B is shifted; low As copy across */
4170*404b540aSrobert       minC += bshift;
4171*404b540aSrobert       /* if in place [common], skip copy unless there's a gap [rare] */
4172*404b540aSrobert       if (a == c && bshift <= alength)
4173*404b540aSrobert 	{
4174*404b540aSrobert 	  c += bshift;
4175*404b540aSrobert 	  a += bshift;
4176*404b540aSrobert 	}
4177*404b540aSrobert       else
4178*404b540aSrobert 	for (; c < clsu + bshift; a++, c++)
4179*404b540aSrobert 	  {			/* copy needed */
4180*404b540aSrobert 	    if (a < alsu + alength)
4181*404b540aSrobert 	      *c = *a;
4182*404b540aSrobert 	    else
4183*404b540aSrobert 	      *c = 0;
4184*404b540aSrobert 	  }
4185*404b540aSrobert     }
4186*404b540aSrobert   if (minC > maxC)
4187*404b540aSrobert     {				/* swap */
4188*404b540aSrobert       Unit *hold = minC;
4189*404b540aSrobert       minC = maxC;
4190*404b540aSrobert       maxC = hold;
4191*404b540aSrobert     }
4192*404b540aSrobert 
4193*404b540aSrobert   /* For speed, we do the addition as two loops; the first where both A */
4194*404b540aSrobert   /* and B contribute, and the second (if necessary) where only one or */
4195*404b540aSrobert   /* other of the numbers contribute. */
4196*404b540aSrobert   /* Carry handling is the same (i.e., duplicated) in each case. */
4197*404b540aSrobert   for (; c < minC; c++)
4198*404b540aSrobert     {
4199*404b540aSrobert       carry += *a;
4200*404b540aSrobert       a++;
4201*404b540aSrobert       carry += ((eInt) * b) * m;	/* [special-casing m=1/-1 */
4202*404b540aSrobert       b++;			/* here is not a win] */
4203*404b540aSrobert       /* here carry is new Unit of digits; it could be +ve or -ve */
4204*404b540aSrobert       if ((ueInt) carry <= DECDPUNMAX)
4205*404b540aSrobert 	{			/* fastpath 0-DECDPUNMAX */
4206*404b540aSrobert 	  *c = (Unit) carry;
4207*404b540aSrobert 	  carry = 0;
4208*404b540aSrobert 	  continue;
4209*404b540aSrobert 	}
4210*404b540aSrobert       /* remainder operator is undefined if negative, so we must test */
4211*404b540aSrobert #if DECDPUN==4			/* use divide-by-multiply */
4212*404b540aSrobert       if (carry >= 0)
4213*404b540aSrobert 	{
4214*404b540aSrobert 	  est = (((ueInt) carry >> 11) * 53687) >> 18;
4215*404b540aSrobert 	  *c = (Unit) (carry - est * (DECDPUNMAX + 1));	/* remainder */
4216*404b540aSrobert 	  carry = est;		/* likely quotient [89%] */
4217*404b540aSrobert 	  if (*c < DECDPUNMAX + 1)
4218*404b540aSrobert 	    continue;		/* estimate was correct */
4219*404b540aSrobert 	  carry++;
4220*404b540aSrobert 	  *c -= DECDPUNMAX + 1;
4221*404b540aSrobert 	  continue;
4222*404b540aSrobert 	}
4223*404b540aSrobert       /* negative case */
4224*404b540aSrobert       carry = carry + (eInt) (DECDPUNMAX + 1) * (DECDPUNMAX + 1);	/* make positive */
4225*404b540aSrobert       est = (((ueInt) carry >> 11) * 53687) >> 18;
4226*404b540aSrobert       *c = (Unit) (carry - est * (DECDPUNMAX + 1));
4227*404b540aSrobert       carry = est - (DECDPUNMAX + 1);	/* correctly negative */
4228*404b540aSrobert       if (*c < DECDPUNMAX + 1)
4229*404b540aSrobert 	continue;		/* was OK */
4230*404b540aSrobert       carry++;
4231*404b540aSrobert       *c -= DECDPUNMAX + 1;
4232*404b540aSrobert #else
4233*404b540aSrobert       if ((ueInt) carry < (DECDPUNMAX + 1) * 2)
4234*404b540aSrobert 	{			/* fastpath carry +1 */
4235*404b540aSrobert 	  *c = (Unit) (carry - (DECDPUNMAX + 1));	/* [helps additions] */
4236*404b540aSrobert 	  carry = 1;
4237*404b540aSrobert 	  continue;
4238*404b540aSrobert 	}
4239*404b540aSrobert       if (carry >= 0)
4240*404b540aSrobert 	{
4241*404b540aSrobert 	  *c = (Unit) (carry % (DECDPUNMAX + 1));
4242*404b540aSrobert 	  carry = carry / (DECDPUNMAX + 1);
4243*404b540aSrobert 	  continue;
4244*404b540aSrobert 	}
4245*404b540aSrobert       /* negative case */
4246*404b540aSrobert       carry = carry + (eInt) (DECDPUNMAX + 1) * (DECDPUNMAX + 1);	/* make positive */
4247*404b540aSrobert       *c = (Unit) (carry % (DECDPUNMAX + 1));
4248*404b540aSrobert       carry = carry / (DECDPUNMAX + 1) - (DECDPUNMAX + 1);
4249*404b540aSrobert #endif
4250*404b540aSrobert     }				/* c */
4251*404b540aSrobert 
4252*404b540aSrobert   /* we now may have one or other to complete */
4253*404b540aSrobert   /* [pretest to avoid loop setup/shutdown] */
4254*404b540aSrobert   if (c < maxC)
4255*404b540aSrobert     for (; c < maxC; c++)
4256*404b540aSrobert       {
4257*404b540aSrobert 	if (a < alsu + alength)
4258*404b540aSrobert 	  {			/* still in A */
4259*404b540aSrobert 	    carry += *a;
4260*404b540aSrobert 	    a++;
4261*404b540aSrobert 	  }
4262*404b540aSrobert 	else
4263*404b540aSrobert 	  {			/* inside B */
4264*404b540aSrobert 	    carry += ((eInt) * b) * m;
4265*404b540aSrobert 	    b++;
4266*404b540aSrobert 	  }
4267*404b540aSrobert 	/* here carry is new Unit of digits; it could be +ve or -ve and */
4268*404b540aSrobert 	/* magnitude up to DECDPUNMAX squared */
4269*404b540aSrobert 	if ((ueInt) carry <= DECDPUNMAX)
4270*404b540aSrobert 	  {			/* fastpath 0-DECDPUNMAX */
4271*404b540aSrobert 	    *c = (Unit) carry;
4272*404b540aSrobert 	    carry = 0;
4273*404b540aSrobert 	    continue;
4274*404b540aSrobert 	  }
4275*404b540aSrobert 	/* result for this unit is negative or >DECDPUNMAX */
4276*404b540aSrobert #if DECDPUN==4			/* use divide-by-multiply */
4277*404b540aSrobert 	/* remainder is undefined if negative, so we must test */
4278*404b540aSrobert 	if (carry >= 0)
4279*404b540aSrobert 	  {
4280*404b540aSrobert 	    est = (((ueInt) carry >> 11) * 53687) >> 18;
4281*404b540aSrobert 	    *c = (Unit) (carry - est * (DECDPUNMAX + 1));	/* remainder */
4282*404b540aSrobert 	    carry = est;	/* likely quotient [79.7%] */
4283*404b540aSrobert 	    if (*c < DECDPUNMAX + 1)
4284*404b540aSrobert 	      continue;		/* estimate was correct */
4285*404b540aSrobert 	    carry++;
4286*404b540aSrobert 	    *c -= DECDPUNMAX + 1;
4287*404b540aSrobert 	    continue;
4288*404b540aSrobert 	  }
4289*404b540aSrobert 	/* negative case */
4290*404b540aSrobert 	carry = carry + (eInt) (DECDPUNMAX + 1) * (DECDPUNMAX + 1);	/* make positive */
4291*404b540aSrobert 	est = (((ueInt) carry >> 11) * 53687) >> 18;
4292*404b540aSrobert 	*c = (Unit) (carry - est * (DECDPUNMAX + 1));
4293*404b540aSrobert 	carry = est - (DECDPUNMAX + 1);	/* correctly negative */
4294*404b540aSrobert 	if (*c < DECDPUNMAX + 1)
4295*404b540aSrobert 	  continue;		/* was OK */
4296*404b540aSrobert 	carry++;
4297*404b540aSrobert 	*c -= DECDPUNMAX + 1;
4298*404b540aSrobert #else
4299*404b540aSrobert 	if ((ueInt) carry < (DECDPUNMAX + 1) * 2)
4300*404b540aSrobert 	  {			/* fastpath carry 1 */
4301*404b540aSrobert 	    *c = (Unit) (carry - (DECDPUNMAX + 1));
4302*404b540aSrobert 	    carry = 1;
4303*404b540aSrobert 	    continue;
4304*404b540aSrobert 	  }
4305*404b540aSrobert 	/* remainder is undefined if negative, so we must test */
4306*404b540aSrobert 	if (carry >= 0)
4307*404b540aSrobert 	  {
4308*404b540aSrobert 	    *c = (Unit) (carry % (DECDPUNMAX + 1));
4309*404b540aSrobert 	    carry = carry / (DECDPUNMAX + 1);
4310*404b540aSrobert 	    continue;
4311*404b540aSrobert 	  }
4312*404b540aSrobert 	/* negative case */
4313*404b540aSrobert 	carry = carry + (eInt) (DECDPUNMAX + 1) * (DECDPUNMAX + 1);	/* make positive */
4314*404b540aSrobert 	*c = (Unit) (carry % (DECDPUNMAX + 1));
4315*404b540aSrobert 	carry = carry / (DECDPUNMAX + 1) - (DECDPUNMAX + 1);
4316*404b540aSrobert #endif
4317*404b540aSrobert       }				/* c */
4318*404b540aSrobert 
4319*404b540aSrobert   /* OK, all A and B processed; might still have carry or borrow */
4320*404b540aSrobert   /* return number of Units in the result, negated if a borrow */
4321*404b540aSrobert   if (carry == 0)
4322*404b540aSrobert     return c - clsu;		/* no carry, we're done */
4323*404b540aSrobert   if (carry > 0)
4324*404b540aSrobert     {				/* positive carry */
4325*404b540aSrobert       *c = (Unit) carry;	/* place as new unit */
4326*404b540aSrobert       c++;			/* .. */
4327*404b540aSrobert       return c - clsu;
4328*404b540aSrobert     }
4329*404b540aSrobert   /* -ve carry: it's a borrow; complement needed */
4330*404b540aSrobert   add = 1;			/* temporary carry... */
4331*404b540aSrobert   for (c = clsu; c < maxC; c++)
4332*404b540aSrobert     {
4333*404b540aSrobert       add = DECDPUNMAX + add - *c;
4334*404b540aSrobert       if (add <= DECDPUNMAX)
4335*404b540aSrobert 	{
4336*404b540aSrobert 	  *c = (Unit) add;
4337*404b540aSrobert 	  add = 0;
4338*404b540aSrobert 	}
4339*404b540aSrobert       else
4340*404b540aSrobert 	{
4341*404b540aSrobert 	  *c = 0;
4342*404b540aSrobert 	  add = 1;
4343*404b540aSrobert 	}
4344*404b540aSrobert     }
4345*404b540aSrobert   /* add an extra unit iff it would be non-zero */
4346*404b540aSrobert #if DECTRACE
4347*404b540aSrobert   printf ("UAS borrow: add %d, carry %d\n", add, carry);
4348*404b540aSrobert #endif
4349*404b540aSrobert   if ((add - carry - 1) != 0)
4350*404b540aSrobert     {
4351*404b540aSrobert       *c = (Unit) (add - carry - 1);
4352*404b540aSrobert       c++;			/* interesting, include it */
4353*404b540aSrobert     }
4354*404b540aSrobert   return clsu - c;		/* -ve result indicates borrowed */
4355*404b540aSrobert }
4356*404b540aSrobert 
4357*404b540aSrobert /* ------------------------------------------------------------------ */
4358*404b540aSrobert /* decTrim -- trim trailing zeros or normalize                        */
4359*404b540aSrobert /*                                                                    */
4360*404b540aSrobert /*   dn is the number to trim or normalize                            */
4361*404b540aSrobert /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
4362*404b540aSrobert /*   dropped returns the number of discarded trailing zeros           */
4363*404b540aSrobert /*   returns dn                                                       */
4364*404b540aSrobert /*                                                                    */
4365*404b540aSrobert /* All fields are updated as required.  This is a utility operation,  */
4366*404b540aSrobert /* so special values are unchanged and no error is possible.          */
4367*404b540aSrobert /* ------------------------------------------------------------------ */
4368*404b540aSrobert static decNumber *
decTrim(decNumber * dn,Flag all,Int * dropped)4369*404b540aSrobert decTrim (decNumber * dn, Flag all, Int * dropped)
4370*404b540aSrobert {
4371*404b540aSrobert   Int d, exp;			/* work */
4372*404b540aSrobert   uInt cut;			/* .. */
4373*404b540aSrobert   Unit *up;			/* -> current Unit */
4374*404b540aSrobert 
4375*404b540aSrobert #if DECCHECK
4376*404b540aSrobert   if (decCheckOperands (dn, DECUNUSED, DECUNUSED, DECUNUSED))
4377*404b540aSrobert     return dn;
4378*404b540aSrobert #endif
4379*404b540aSrobert 
4380*404b540aSrobert   *dropped = 0;			/* assume no zeros dropped */
4381*404b540aSrobert   if ((dn->bits & DECSPECIAL)	/* fast exit if special .. */
4382*404b540aSrobert       || (*dn->lsu & 0x01))
4383*404b540aSrobert     return dn;			/* .. or odd */
4384*404b540aSrobert   if (ISZERO (dn))
4385*404b540aSrobert     {				/* .. or 0 */
4386*404b540aSrobert       dn->exponent = 0;		/* (sign is preserved) */
4387*404b540aSrobert       return dn;
4388*404b540aSrobert     }
4389*404b540aSrobert 
4390*404b540aSrobert   /* we have a finite number which is even */
4391*404b540aSrobert   exp = dn->exponent;
4392*404b540aSrobert   cut = 1;			/* digit (1-DECDPUN) in Unit */
4393*404b540aSrobert   up = dn->lsu;			/* -> current Unit */
4394*404b540aSrobert   for (d = 0; d < dn->digits - 1; d++)
4395*404b540aSrobert     {				/* [don't strip the final digit] */
4396*404b540aSrobert       /* slice by powers */
4397*404b540aSrobert #if DECDPUN<=4
4398*404b540aSrobert       uInt quot = QUOT10 (*up, cut);
4399*404b540aSrobert       if ((*up - quot * powers[cut]) != 0)
4400*404b540aSrobert 	break;			/* found non-0 digit */
4401*404b540aSrobert #else
4402*404b540aSrobert       if (*up % powers[cut] != 0)
4403*404b540aSrobert 	break;			/* found non-0 digit */
4404*404b540aSrobert #endif
4405*404b540aSrobert       /* have a trailing 0 */
4406*404b540aSrobert       if (!all)
4407*404b540aSrobert 	{			/* trimming */
4408*404b540aSrobert 	  /* [if exp>0 then all trailing 0s are significant for trim] */
4409*404b540aSrobert 	  if (exp <= 0)
4410*404b540aSrobert 	    {			/* if digit might be significant */
4411*404b540aSrobert 	      if (exp == 0)
4412*404b540aSrobert 		break;		/* then quit */
4413*404b540aSrobert 	      exp++;		/* next digit might be significant */
4414*404b540aSrobert 	    }
4415*404b540aSrobert 	}
4416*404b540aSrobert       cut++;			/* next power */
4417*404b540aSrobert       if (cut > DECDPUN)
4418*404b540aSrobert 	{			/* need new Unit */
4419*404b540aSrobert 	  up++;
4420*404b540aSrobert 	  cut = 1;
4421*404b540aSrobert 	}
4422*404b540aSrobert     }				/* d */
4423*404b540aSrobert   if (d == 0)
4424*404b540aSrobert     return dn;			/* none dropped */
4425*404b540aSrobert 
4426*404b540aSrobert   /* effect the drop */
4427*404b540aSrobert   decShiftToLeast (dn->lsu, D2U (dn->digits), d);
4428*404b540aSrobert   dn->exponent += d;		/* maintain numerical value */
4429*404b540aSrobert   dn->digits -= d;		/* new length */
4430*404b540aSrobert   *dropped = d;			/* report the count */
4431*404b540aSrobert   return dn;
4432*404b540aSrobert }
4433*404b540aSrobert 
4434*404b540aSrobert /* ------------------------------------------------------------------ */
4435*404b540aSrobert /* decShiftToMost -- shift digits in array towards most significant   */
4436*404b540aSrobert /*                                                                    */
4437*404b540aSrobert /*   uar    is the array                                              */
4438*404b540aSrobert /*   digits is the count of digits in use in the array                */
4439*404b540aSrobert /*   shift  is the number of zeros to pad with (least significant);   */
4440*404b540aSrobert /*     it must be zero or positive                                    */
4441*404b540aSrobert /*                                                                    */
4442*404b540aSrobert /*   returns the new length of the integer in the array, in digits    */
4443*404b540aSrobert /*                                                                    */
4444*404b540aSrobert /* No overflow is permitted (that is, the uar array must be known to  */
4445*404b540aSrobert /* be large enough to hold the result, after shifting).               */
4446*404b540aSrobert /* ------------------------------------------------------------------ */
4447*404b540aSrobert static Int
decShiftToMost(Unit * uar,Int digits,Int shift)4448*404b540aSrobert decShiftToMost (Unit * uar, Int digits, Int shift)
4449*404b540aSrobert {
4450*404b540aSrobert   Unit *target, *source, *first;	/* work */
4451*404b540aSrobert   uInt rem;			/* for division */
4452*404b540aSrobert   Int cut;			/* odd 0's to add */
4453*404b540aSrobert   uInt next;			/* work */
4454*404b540aSrobert 
4455*404b540aSrobert   if (shift == 0)
4456*404b540aSrobert     return digits;		/* [fastpath] nothing to do */
4457*404b540aSrobert   if ((digits + shift) <= DECDPUN)
4458*404b540aSrobert     {				/* [fastpath] single-unit case */
4459*404b540aSrobert       *uar = (Unit) (*uar * powers[shift]);
4460*404b540aSrobert       return digits + shift;
4461*404b540aSrobert     }
4462*404b540aSrobert 
4463*404b540aSrobert   cut = (DECDPUN - shift % DECDPUN) % DECDPUN;
4464*404b540aSrobert   source = uar + D2U (digits) - 1;	/* where msu comes from */
4465*404b540aSrobert   first = uar + D2U (digits + shift) - 1;	/* where msu of source will end up */
4466*404b540aSrobert   target = source + D2U (shift);	/* where upper part of first cut goes */
4467*404b540aSrobert   next = 0;
4468*404b540aSrobert 
4469*404b540aSrobert   for (; source >= uar; source--, target--)
4470*404b540aSrobert     {
4471*404b540aSrobert       /* split the source Unit and accumulate remainder for next */
4472*404b540aSrobert #if DECDPUN<=4
4473*404b540aSrobert       uInt quot = QUOT10 (*source, cut);
4474*404b540aSrobert       rem = *source - quot * powers[cut];
4475*404b540aSrobert       next += quot;
4476*404b540aSrobert #else
4477*404b540aSrobert       rem = *source % powers[cut];
4478*404b540aSrobert       next += *source / powers[cut];
4479*404b540aSrobert #endif
4480*404b540aSrobert       if (target <= first)
4481*404b540aSrobert 	*target = (Unit) next;	/* write to target iff valid */
4482*404b540aSrobert       next = rem * powers[DECDPUN - cut];	/* save remainder for next Unit */
4483*404b540aSrobert     }
4484*404b540aSrobert   /* propagate to one below and clear the rest */
4485*404b540aSrobert   for (; target >= uar; target--)
4486*404b540aSrobert     {
4487*404b540aSrobert       *target = (Unit) next;
4488*404b540aSrobert       next = 0;
4489*404b540aSrobert     }
4490*404b540aSrobert   return digits + shift;
4491*404b540aSrobert }
4492*404b540aSrobert 
4493*404b540aSrobert /* ------------------------------------------------------------------ */
4494*404b540aSrobert /* decShiftToLeast -- shift digits in array towards least significant */
4495*404b540aSrobert /*                                                                    */
4496*404b540aSrobert /*   uar   is the array                                               */
4497*404b540aSrobert /*   units is length of the array, in units                           */
4498*404b540aSrobert /*   shift is the number of digits to remove from the lsu end; it     */
4499*404b540aSrobert /*     must be zero or positive and less than units*DECDPUN.          */
4500*404b540aSrobert /*                                                                    */
4501*404b540aSrobert /*   returns the new length of the integer in the array, in units     */
4502*404b540aSrobert /*                                                                    */
4503*404b540aSrobert /* Removed digits are discarded (lost).  Units not required to hold   */
4504*404b540aSrobert /* the final result are unchanged.                                    */
4505*404b540aSrobert /* ------------------------------------------------------------------ */
4506*404b540aSrobert static Int
decShiftToLeast(Unit * uar,Int units,Int shift)4507*404b540aSrobert decShiftToLeast (Unit * uar, Int units, Int shift)
4508*404b540aSrobert {
4509*404b540aSrobert   Unit *target, *up;		/* work */
4510*404b540aSrobert   Int cut, count;		/* work */
4511*404b540aSrobert   Int quot, rem;		/* for division */
4512*404b540aSrobert 
4513*404b540aSrobert   if (shift == 0)
4514*404b540aSrobert     return units;		/* [fastpath] nothing to do */
4515*404b540aSrobert 
4516*404b540aSrobert   up = uar + shift / DECDPUN;	/* source; allow for whole Units */
4517*404b540aSrobert   cut = shift % DECDPUN;	/* odd 0's to drop */
4518*404b540aSrobert   target = uar;			/* both paths */
4519*404b540aSrobert   if (cut == 0)
4520*404b540aSrobert     {				/* whole units shift */
4521*404b540aSrobert       for (; up < uar + units; target++, up++)
4522*404b540aSrobert 	*target = *up;
4523*404b540aSrobert       return target - uar;
4524*404b540aSrobert     }
4525*404b540aSrobert   /* messier */
4526*404b540aSrobert   count = units * DECDPUN - shift;	/* the maximum new length */
4527*404b540aSrobert #if DECDPUN<=4
4528*404b540aSrobert   quot = QUOT10 (*up, cut);
4529*404b540aSrobert #else
4530*404b540aSrobert   quot = *up / powers[cut];
4531*404b540aSrobert #endif
4532*404b540aSrobert   for (;; target++)
4533*404b540aSrobert     {
4534*404b540aSrobert       *target = (Unit) quot;
4535*404b540aSrobert       count -= (DECDPUN - cut);
4536*404b540aSrobert       if (count <= 0)
4537*404b540aSrobert 	break;
4538*404b540aSrobert       up++;
4539*404b540aSrobert       quot = *up;
4540*404b540aSrobert #if DECDPUN<=4
4541*404b540aSrobert       quot = QUOT10 (quot, cut);
4542*404b540aSrobert       rem = *up - quot * powers[cut];
4543*404b540aSrobert #else
4544*404b540aSrobert       rem = quot % powers[cut];
4545*404b540aSrobert       quot = quot / powers[cut];
4546*404b540aSrobert #endif
4547*404b540aSrobert       *target = (Unit) (*target + rem * powers[DECDPUN - cut]);
4548*404b540aSrobert       count -= cut;
4549*404b540aSrobert       if (count <= 0)
4550*404b540aSrobert 	break;
4551*404b540aSrobert     }
4552*404b540aSrobert   return target - uar + 1;
4553*404b540aSrobert }
4554*404b540aSrobert 
4555*404b540aSrobert #if DECSUBSET
4556*404b540aSrobert /* ------------------------------------------------------------------ */
4557*404b540aSrobert /* decRoundOperand -- round an operand  [used for subset only]        */
4558*404b540aSrobert /*                                                                    */
4559*404b540aSrobert /*   dn is the number to round (dn->digits is > set->digits)          */
4560*404b540aSrobert /*   set is the relevant context                                      */
4561*404b540aSrobert /*   status is the status accumulator                                 */
4562*404b540aSrobert /*                                                                    */
4563*404b540aSrobert /*   returns an allocated decNumber with the rounded result.          */
4564*404b540aSrobert /*                                                                    */
4565*404b540aSrobert /* lostDigits and other status may be set by this.                    */
4566*404b540aSrobert /*                                                                    */
4567*404b540aSrobert /* Since the input is an operand, we are not permitted to modify it.  */
4568*404b540aSrobert /* We therefore return an allocated decNumber, rounded as required.   */
4569*404b540aSrobert /* It is the caller's responsibility to free the allocated storage.   */
4570*404b540aSrobert /*                                                                    */
4571*404b540aSrobert /* If no storage is available then the result cannot be used, so NULL */
4572*404b540aSrobert /* is returned.                                                       */
4573*404b540aSrobert /* ------------------------------------------------------------------ */
4574*404b540aSrobert static decNumber *
decRoundOperand(const decNumber * dn,decContext * set,uInt * status)4575*404b540aSrobert decRoundOperand (const decNumber * dn, decContext * set, uInt * status)
4576*404b540aSrobert {
4577*404b540aSrobert   decNumber *res;		/* result structure */
4578*404b540aSrobert   uInt newstatus = 0;		/* status from round */
4579*404b540aSrobert   Int residue = 0;		/* rounding accumulator */
4580*404b540aSrobert 
4581*404b540aSrobert   /* Allocate storage for the returned decNumber, big enough for the */
4582*404b540aSrobert   /* length specified by the context */
4583*404b540aSrobert   res = (decNumber *) malloc (sizeof (decNumber)
4584*404b540aSrobert 			      + (D2U (set->digits) - 1) * sizeof (Unit));
4585*404b540aSrobert   if (res == NULL)
4586*404b540aSrobert     {
4587*404b540aSrobert       *status |= DEC_Insufficient_storage;
4588*404b540aSrobert       return NULL;
4589*404b540aSrobert     }
4590*404b540aSrobert   decCopyFit (res, dn, set, &residue, &newstatus);
4591*404b540aSrobert   decApplyRound (res, set, residue, &newstatus);
4592*404b540aSrobert 
4593*404b540aSrobert   /* If that set Inexact then we "lost digits" */
4594*404b540aSrobert   if (newstatus & DEC_Inexact)
4595*404b540aSrobert     newstatus |= DEC_Lost_digits;
4596*404b540aSrobert   *status |= newstatus;
4597*404b540aSrobert   return res;
4598*404b540aSrobert }
4599*404b540aSrobert #endif
4600*404b540aSrobert 
4601*404b540aSrobert /* ------------------------------------------------------------------ */
4602*404b540aSrobert /* decCopyFit -- copy a number, shortening the coefficient if needed  */
4603*404b540aSrobert /*                                                                    */
4604*404b540aSrobert /*   dest is the target decNumber                                     */
4605*404b540aSrobert /*   src  is the source decNumber                                     */
4606*404b540aSrobert /*   set is the context [used for length (digits) and rounding mode]  */
4607*404b540aSrobert /*   residue is the residue accumulator                               */
4608*404b540aSrobert /*   status contains the current status to be updated                 */
4609*404b540aSrobert /*                                                                    */
4610*404b540aSrobert /* (dest==src is allowed and will be a no-op if fits)                 */
4611*404b540aSrobert /* All fields are updated as required.                                */
4612*404b540aSrobert /* ------------------------------------------------------------------ */
4613*404b540aSrobert static void
decCopyFit(decNumber * dest,const decNumber * src,decContext * set,Int * residue,uInt * status)4614*404b540aSrobert decCopyFit (decNumber * dest, const decNumber * src, decContext * set,
4615*404b540aSrobert 	    Int * residue, uInt * status)
4616*404b540aSrobert {
4617*404b540aSrobert   dest->bits = src->bits;
4618*404b540aSrobert   dest->exponent = src->exponent;
4619*404b540aSrobert   decSetCoeff (dest, set, src->lsu, src->digits, residue, status);
4620*404b540aSrobert }
4621*404b540aSrobert 
4622*404b540aSrobert /* ------------------------------------------------------------------ */
4623*404b540aSrobert /* decSetCoeff -- set the coefficient of a number                     */
4624*404b540aSrobert /*                                                                    */
4625*404b540aSrobert /*   dn    is the number whose coefficient array is to be set.        */
4626*404b540aSrobert /*         It must have space for set->digits digits                  */
4627*404b540aSrobert /*   set   is the context [for size]                                  */
4628*404b540aSrobert /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
4629*404b540aSrobert /*   len   is digits in the source coefficient [may be dn->digits]    */
4630*404b540aSrobert /*   residue is the residue accumulator.  This has values as in       */
4631*404b540aSrobert /*         decApplyRound, and will be unchanged unless the            */
4632*404b540aSrobert /*         target size is less than len.  In this case, the           */
4633*404b540aSrobert /*         coefficient is truncated and the residue is updated to     */
4634*404b540aSrobert /*         reflect the previous residue and the dropped digits.       */
4635*404b540aSrobert /*   status is the status accumulator, as usual                       */
4636*404b540aSrobert /*                                                                    */
4637*404b540aSrobert /* The coefficient may already be in the number, or it can be an      */
4638*404b540aSrobert /* external intermediate array.  If it is in the number, lsu must ==  */
4639*404b540aSrobert /* dn->lsu and len must == dn->digits.                                */
4640*404b540aSrobert /*                                                                    */
4641*404b540aSrobert /* Note that the coefficient length (len) may be < set->digits, and   */
4642*404b540aSrobert /* in this case this merely copies the coefficient (or is a no-op     */
4643*404b540aSrobert /* if dn->lsu==lsu).                                                  */
4644*404b540aSrobert /*                                                                    */
4645*404b540aSrobert /* Note also that (only internally, from decNumberRescale and         */
4646*404b540aSrobert /* decSetSubnormal) the value of set->digits may be less than one,    */
4647*404b540aSrobert /* indicating a round to left.                                        */
4648*404b540aSrobert /* This routine handles that case correctly; caller ensures space.    */
4649*404b540aSrobert /*                                                                    */
4650*404b540aSrobert /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
4651*404b540aSrobert /* updated as necessary.   dn->bits (sign) is unchanged.              */
4652*404b540aSrobert /*                                                                    */
4653*404b540aSrobert /* DEC_Rounded status is set if any digits are discarded.             */
4654*404b540aSrobert /* DEC_Inexact status is set if any non-zero digits are discarded, or */
4655*404b540aSrobert /*                       incoming residue was non-0 (implies rounded) */
4656*404b540aSrobert /* ------------------------------------------------------------------ */
4657*404b540aSrobert /* mapping array: maps 0-9 to canonical residues, so that we can */
4658*404b540aSrobert /* adjust by a residue in range [-1, +1] and achieve correct rounding */
4659*404b540aSrobert /*                             0  1  2  3  4  5  6  7  8  9 */
4660*404b540aSrobert static const uByte resmap[10] = { 0, 3, 3, 3, 3, 5, 7, 7, 7, 7 };
4661*404b540aSrobert static void
decSetCoeff(decNumber * dn,decContext * set,const Unit * lsu,Int len,Int * residue,uInt * status)4662*404b540aSrobert decSetCoeff (decNumber * dn, decContext * set, const Unit * lsu,
4663*404b540aSrobert 	     Int len, Int * residue, uInt * status)
4664*404b540aSrobert {
4665*404b540aSrobert   Int discard;			/* number of digits to discard */
4666*404b540aSrobert   uInt discard1;		/* first discarded digit */
4667*404b540aSrobert   uInt cut;			/* cut point in Unit */
4668*404b540aSrobert   uInt quot, rem;		/* for divisions */
4669*404b540aSrobert   Unit *target;			/* work */
4670*404b540aSrobert   const Unit *up;		/* work */
4671*404b540aSrobert   Int count;			/* .. */
4672*404b540aSrobert #if DECDPUN<=4
4673*404b540aSrobert   uInt temp;			/* .. */
4674*404b540aSrobert #endif
4675*404b540aSrobert 
4676*404b540aSrobert   discard = len - set->digits;	/* digits to discard */
4677*404b540aSrobert   if (discard <= 0)
4678*404b540aSrobert     {				/* no digits are being discarded */
4679*404b540aSrobert       if (dn->lsu != lsu)
4680*404b540aSrobert 	{			/* copy needed */
4681*404b540aSrobert 	  /* copy the coefficient array to the result number; no shift needed */
4682*404b540aSrobert 	  up = lsu;
4683*404b540aSrobert 	  for (target = dn->lsu; target < dn->lsu + D2U (len); target++, up++)
4684*404b540aSrobert 	    {
4685*404b540aSrobert 	      *target = *up;
4686*404b540aSrobert 	    }
4687*404b540aSrobert 	  dn->digits = len;	/* set the new length */
4688*404b540aSrobert 	}
4689*404b540aSrobert       /* dn->exponent and residue are unchanged */
4690*404b540aSrobert       if (*residue != 0)
4691*404b540aSrobert 	*status |= (DEC_Inexact | DEC_Rounded);	/* record inexactitude */
4692*404b540aSrobert       return;
4693*404b540aSrobert     }
4694*404b540aSrobert 
4695*404b540aSrobert   /* we have to discard some digits */
4696*404b540aSrobert   *status |= DEC_Rounded;	/* accumulate Rounded status */
4697*404b540aSrobert   if (*residue > 1)
4698*404b540aSrobert     *residue = 1;		/* previous residue now to right, so -1 to +1 */
4699*404b540aSrobert 
4700*404b540aSrobert   if (discard > len)
4701*404b540aSrobert     {				/* everything, +1, is being discarded */
4702*404b540aSrobert       /* guard digit is 0 */
4703*404b540aSrobert       /* residue is all the number [NB could be all 0s] */
4704*404b540aSrobert       if (*residue <= 0)
4705*404b540aSrobert 	for (up = lsu + D2U (len) - 1; up >= lsu; up--)
4706*404b540aSrobert 	  {
4707*404b540aSrobert 	    if (*up != 0)
4708*404b540aSrobert 	      {			/* found a non-0 */
4709*404b540aSrobert 		*residue = 1;
4710*404b540aSrobert 		break;		/* no need to check any others */
4711*404b540aSrobert 	      }
4712*404b540aSrobert 	  }
4713*404b540aSrobert       if (*residue != 0)
4714*404b540aSrobert 	*status |= DEC_Inexact;	/* record inexactitude */
4715*404b540aSrobert       *dn->lsu = 0;		/* coefficient will now be 0 */
4716*404b540aSrobert       dn->digits = 1;		/* .. */
4717*404b540aSrobert       dn->exponent += discard;	/* maintain numerical value */
4718*404b540aSrobert       return;
4719*404b540aSrobert     }				/* total discard */
4720*404b540aSrobert 
4721*404b540aSrobert   /* partial discard [most common case] */
4722*404b540aSrobert   /* here, at least the first (most significant) discarded digit exists */
4723*404b540aSrobert 
4724*404b540aSrobert   /* spin up the number, noting residue as we pass, until we get to */
4725*404b540aSrobert   /* the Unit with the first discarded digit.  When we get there, */
4726*404b540aSrobert   /* extract it and remember where we're at */
4727*404b540aSrobert   count = 0;
4728*404b540aSrobert   for (up = lsu;; up++)
4729*404b540aSrobert     {
4730*404b540aSrobert       count += DECDPUN;
4731*404b540aSrobert       if (count >= discard)
4732*404b540aSrobert 	break;			/* full ones all checked */
4733*404b540aSrobert       if (*up != 0)
4734*404b540aSrobert 	*residue = 1;
4735*404b540aSrobert     }				/* up */
4736*404b540aSrobert 
4737*404b540aSrobert   /* here up -> Unit with discarded digit */
4738*404b540aSrobert   cut = discard - (count - DECDPUN) - 1;
4739*404b540aSrobert   if (cut == DECDPUN - 1)
4740*404b540aSrobert     {				/* discard digit is at top */
4741*404b540aSrobert #if DECDPUN<=4
4742*404b540aSrobert       discard1 = QUOT10 (*up, DECDPUN - 1);
4743*404b540aSrobert       rem = *up - discard1 * powers[DECDPUN - 1];
4744*404b540aSrobert #else
4745*404b540aSrobert       rem = *up % powers[DECDPUN - 1];
4746*404b540aSrobert       discard1 = *up / powers[DECDPUN - 1];
4747*404b540aSrobert #endif
4748*404b540aSrobert       if (rem != 0)
4749*404b540aSrobert 	*residue = 1;
4750*404b540aSrobert       up++;			/* move to next */
4751*404b540aSrobert       cut = 0;			/* bottom digit of result */
4752*404b540aSrobert       quot = 0;			/* keep a certain compiler happy */
4753*404b540aSrobert     }
4754*404b540aSrobert   else
4755*404b540aSrobert     {
4756*404b540aSrobert       /* discard digit is in low digit(s), not top digit */
4757*404b540aSrobert       if (cut == 0)
4758*404b540aSrobert 	quot = *up;
4759*404b540aSrobert       else			/* cut>0 */
4760*404b540aSrobert 	{			/* it's not at bottom of Unit */
4761*404b540aSrobert #if DECDPUN<=4
4762*404b540aSrobert 	  quot = QUOT10 (*up, cut);
4763*404b540aSrobert 	  rem = *up - quot * powers[cut];
4764*404b540aSrobert #else
4765*404b540aSrobert 	  rem = *up % powers[cut];
4766*404b540aSrobert 	  quot = *up / powers[cut];
4767*404b540aSrobert #endif
4768*404b540aSrobert 	  if (rem != 0)
4769*404b540aSrobert 	    *residue = 1;
4770*404b540aSrobert 	}
4771*404b540aSrobert       /* discard digit is now at bottom of quot */
4772*404b540aSrobert #if DECDPUN<=4
4773*404b540aSrobert       temp = (quot * 6554) >> 16;	/* fast /10 */
4774*404b540aSrobert       /* Vowels algorithm here not a win (9 instructions) */
4775*404b540aSrobert       discard1 = quot - X10 (temp);
4776*404b540aSrobert       quot = temp;
4777*404b540aSrobert #else
4778*404b540aSrobert       discard1 = quot % 10;
4779*404b540aSrobert       quot = quot / 10;
4780*404b540aSrobert #endif
4781*404b540aSrobert       cut++;			/* update cut */
4782*404b540aSrobert     }
4783*404b540aSrobert 
4784*404b540aSrobert   /* here: up -> Unit of the array with discarded digit */
4785*404b540aSrobert   /*       cut is the division point for each Unit */
4786*404b540aSrobert   /*       quot holds the uncut high-order digits for the current */
4787*404b540aSrobert   /*            Unit, unless cut==0 in which case it's still in *up */
4788*404b540aSrobert   /* copy the coefficient array to the result number, shifting as we go */
4789*404b540aSrobert   count = set->digits;		/* digits to end up with */
4790*404b540aSrobert   if (count <= 0)
4791*404b540aSrobert     {				/* special for Rescale/Subnormal :-( */
4792*404b540aSrobert       *dn->lsu = 0;		/* .. result is 0 */
4793*404b540aSrobert       dn->digits = 1;		/* .. */
4794*404b540aSrobert     }
4795*404b540aSrobert   else
4796*404b540aSrobert     {				/* shift to least */
4797*404b540aSrobert       /* [this is similar to decShiftToLeast code, with copy] */
4798*404b540aSrobert       dn->digits = count;	/* set the new length */
4799*404b540aSrobert       if (cut == 0)
4800*404b540aSrobert 	{
4801*404b540aSrobert 	  /* on unit boundary, so simple shift down copy loop suffices */
4802*404b540aSrobert 	  for (target = dn->lsu; target < dn->lsu + D2U (count);
4803*404b540aSrobert 	       target++, up++)
4804*404b540aSrobert 	    {
4805*404b540aSrobert 	      *target = *up;
4806*404b540aSrobert 	    }
4807*404b540aSrobert 	}
4808*404b540aSrobert       else
4809*404b540aSrobert 	for (target = dn->lsu;; target++)
4810*404b540aSrobert 	  {
4811*404b540aSrobert 	    *target = (Unit) quot;
4812*404b540aSrobert 	    count -= (DECDPUN - cut);
4813*404b540aSrobert 	    if (count <= 0)
4814*404b540aSrobert 	      break;
4815*404b540aSrobert 	    up++;
4816*404b540aSrobert 	    quot = *up;
4817*404b540aSrobert #if DECDPUN<=4
4818*404b540aSrobert 	    quot = QUOT10 (quot, cut);
4819*404b540aSrobert 	    rem = *up - quot * powers[cut];
4820*404b540aSrobert #else
4821*404b540aSrobert 	    rem = quot % powers[cut];
4822*404b540aSrobert 	    quot = quot / powers[cut];
4823*404b540aSrobert #endif
4824*404b540aSrobert 	    *target = (Unit) (*target + rem * powers[DECDPUN - cut]);
4825*404b540aSrobert 	    count -= cut;
4826*404b540aSrobert 	    if (count <= 0)
4827*404b540aSrobert 	      break;
4828*404b540aSrobert 	  }
4829*404b540aSrobert     }				/* shift to least needed */
4830*404b540aSrobert   dn->exponent += discard;	/* maintain numerical value */
4831*404b540aSrobert 
4832*404b540aSrobert   /* here, discard1 is the guard digit, and residue is everything else */
4833*404b540aSrobert   /* [use mapping to accumulate residue safely] */
4834*404b540aSrobert   *residue += resmap[discard1];
4835*404b540aSrobert 
4836*404b540aSrobert   if (*residue != 0)
4837*404b540aSrobert     *status |= DEC_Inexact;	/* record inexactitude */
4838*404b540aSrobert   return;
4839*404b540aSrobert }
4840*404b540aSrobert 
4841*404b540aSrobert /* ------------------------------------------------------------------ */
4842*404b540aSrobert /* decApplyRound -- apply pending rounding to a number                */
4843*404b540aSrobert /*                                                                    */
4844*404b540aSrobert /*   dn    is the number, with space for set->digits digits           */
4845*404b540aSrobert /*   set   is the context [for size and rounding mode]                */
4846*404b540aSrobert /*   residue indicates pending rounding, being any accumulated        */
4847*404b540aSrobert /*         guard and sticky information.  It may be:                  */
4848*404b540aSrobert /*         6-9: rounding digit is >5                                  */
4849*404b540aSrobert /*         5:   rounding digit is exactly half-way                    */
4850*404b540aSrobert /*         1-4: rounding digit is <5 and >0                           */
4851*404b540aSrobert /*         0:   the coefficient is exact                              */
4852*404b540aSrobert /*        -1:   as 1, but the hidden digits are subtractive, that     */
4853*404b540aSrobert /*              is, of the opposite sign to dn.  In this case the     */
4854*404b540aSrobert /*              coefficient must be non-0.                            */
4855*404b540aSrobert /*   status is the status accumulator, as usual                       */
4856*404b540aSrobert /*                                                                    */
4857*404b540aSrobert /* This routine applies rounding while keeping the length of the      */
4858*404b540aSrobert /* coefficient constant.  The exponent and status are unchanged       */
4859*404b540aSrobert /* except if:                                                         */
4860*404b540aSrobert /*                                                                    */
4861*404b540aSrobert /*   -- the coefficient was increased and is all nines (in which      */
4862*404b540aSrobert /*      case Overflow could occur, and is handled directly here so    */
4863*404b540aSrobert /*      the caller does not need to re-test for overflow)             */
4864*404b540aSrobert /*                                                                    */
4865*404b540aSrobert /*   -- the coefficient was decreased and becomes all nines (in which */
4866*404b540aSrobert /*      case Underflow could occur, and is also handled directly).    */
4867*404b540aSrobert /*                                                                    */
4868*404b540aSrobert /* All fields in dn are updated as required.                          */
4869*404b540aSrobert /*                                                                    */
4870*404b540aSrobert /* ------------------------------------------------------------------ */
4871*404b540aSrobert static void
decApplyRound(decNumber * dn,decContext * set,Int residue,uInt * status)4872*404b540aSrobert decApplyRound (decNumber * dn, decContext * set, Int residue, uInt * status)
4873*404b540aSrobert {
4874*404b540aSrobert   Int bump;			/* 1 if coefficient needs to be incremented */
4875*404b540aSrobert   /* -1 if coefficient needs to be decremented */
4876*404b540aSrobert 
4877*404b540aSrobert   if (residue == 0)
4878*404b540aSrobert     return;			/* nothing to apply */
4879*404b540aSrobert 
4880*404b540aSrobert   bump = 0;			/* assume a smooth ride */
4881*404b540aSrobert 
4882*404b540aSrobert   /* now decide whether, and how, to round, depending on mode */
4883*404b540aSrobert   switch (set->round)
4884*404b540aSrobert     {
4885*404b540aSrobert     case DEC_ROUND_DOWN:
4886*404b540aSrobert       {
4887*404b540aSrobert 	/* no change, except if negative residue */
4888*404b540aSrobert 	if (residue < 0)
4889*404b540aSrobert 	  bump = -1;
4890*404b540aSrobert 	break;
4891*404b540aSrobert       }				/* r-d */
4892*404b540aSrobert 
4893*404b540aSrobert     case DEC_ROUND_HALF_DOWN:
4894*404b540aSrobert       {
4895*404b540aSrobert 	if (residue > 5)
4896*404b540aSrobert 	  bump = 1;
4897*404b540aSrobert 	break;
4898*404b540aSrobert       }				/* r-h-d */
4899*404b540aSrobert 
4900*404b540aSrobert     case DEC_ROUND_HALF_EVEN:
4901*404b540aSrobert       {
4902*404b540aSrobert 	if (residue > 5)
4903*404b540aSrobert 	  bump = 1;		/* >0.5 goes up */
4904*404b540aSrobert 	else if (residue == 5)
4905*404b540aSrobert 	  {			/* exactly 0.5000... */
4906*404b540aSrobert 	    /* 0.5 goes up iff [new] lsd is odd */
4907*404b540aSrobert 	    if (*dn->lsu & 0x01)
4908*404b540aSrobert 	      bump = 1;
4909*404b540aSrobert 	  }
4910*404b540aSrobert 	break;
4911*404b540aSrobert       }				/* r-h-e */
4912*404b540aSrobert 
4913*404b540aSrobert     case DEC_ROUND_HALF_UP:
4914*404b540aSrobert       {
4915*404b540aSrobert 	if (residue >= 5)
4916*404b540aSrobert 	  bump = 1;
4917*404b540aSrobert 	break;
4918*404b540aSrobert       }				/* r-h-u */
4919*404b540aSrobert 
4920*404b540aSrobert     case DEC_ROUND_UP:
4921*404b540aSrobert       {
4922*404b540aSrobert 	if (residue > 0)
4923*404b540aSrobert 	  bump = 1;
4924*404b540aSrobert 	break;
4925*404b540aSrobert       }				/* r-u */
4926*404b540aSrobert 
4927*404b540aSrobert     case DEC_ROUND_CEILING:
4928*404b540aSrobert       {
4929*404b540aSrobert 	/* same as _UP for positive numbers, and as _DOWN for negatives */
4930*404b540aSrobert 	/* [negative residue cannot occur on 0] */
4931*404b540aSrobert 	if (decNumberIsNegative (dn))
4932*404b540aSrobert 	  {
4933*404b540aSrobert 	    if (residue < 0)
4934*404b540aSrobert 	      bump = -1;
4935*404b540aSrobert 	  }
4936*404b540aSrobert 	else
4937*404b540aSrobert 	  {
4938*404b540aSrobert 	    if (residue > 0)
4939*404b540aSrobert 	      bump = 1;
4940*404b540aSrobert 	  }
4941*404b540aSrobert 	break;
4942*404b540aSrobert       }				/* r-c */
4943*404b540aSrobert 
4944*404b540aSrobert     case DEC_ROUND_FLOOR:
4945*404b540aSrobert       {
4946*404b540aSrobert 	/* same as _UP for negative numbers, and as _DOWN for positive */
4947*404b540aSrobert 	/* [negative residue cannot occur on 0] */
4948*404b540aSrobert 	if (!decNumberIsNegative (dn))
4949*404b540aSrobert 	  {
4950*404b540aSrobert 	    if (residue < 0)
4951*404b540aSrobert 	      bump = -1;
4952*404b540aSrobert 	  }
4953*404b540aSrobert 	else
4954*404b540aSrobert 	  {
4955*404b540aSrobert 	    if (residue > 0)
4956*404b540aSrobert 	      bump = 1;
4957*404b540aSrobert 	  }
4958*404b540aSrobert 	break;
4959*404b540aSrobert       }				/* r-f */
4960*404b540aSrobert 
4961*404b540aSrobert     default:
4962*404b540aSrobert       {				/* e.g., DEC_ROUND_MAX */
4963*404b540aSrobert 	*status |= DEC_Invalid_context;
4964*404b540aSrobert #if DECTRACE
4965*404b540aSrobert 	printf ("Unknown rounding mode: %d\n", set->round);
4966*404b540aSrobert #endif
4967*404b540aSrobert 	break;
4968*404b540aSrobert       }
4969*404b540aSrobert     }				/* switch */
4970*404b540aSrobert 
4971*404b540aSrobert   /* now bump the number, up or down, if need be */
4972*404b540aSrobert   if (bump == 0)
4973*404b540aSrobert     return;			/* no action required */
4974*404b540aSrobert 
4975*404b540aSrobert   /* Simply use decUnitAddSub unless we are bumping up and the number */
4976*404b540aSrobert   /* is all nines.  In this special case we set to 1000... and adjust */
4977*404b540aSrobert   /* the exponent by one (as otherwise we could overflow the array) */
4978*404b540aSrobert   /* Similarly handle all-nines result if bumping down. */
4979*404b540aSrobert   if (bump > 0)
4980*404b540aSrobert     {
4981*404b540aSrobert       Unit *up;			/* work */
4982*404b540aSrobert       uInt count = dn->digits;	/* digits to be checked */
4983*404b540aSrobert       for (up = dn->lsu;; up++)
4984*404b540aSrobert 	{
4985*404b540aSrobert 	  if (count <= DECDPUN)
4986*404b540aSrobert 	    {
4987*404b540aSrobert 	      /* this is the last Unit (the msu) */
4988*404b540aSrobert 	      if (*up != powers[count] - 1)
4989*404b540aSrobert 		break;		/* not still 9s */
4990*404b540aSrobert 	      /* here if it, too, is all nines */
4991*404b540aSrobert 	      *up = (Unit) powers[count - 1];	/* here 999 -> 100 etc. */
4992*404b540aSrobert 	      for (up = up - 1; up >= dn->lsu; up--)
4993*404b540aSrobert 		*up = 0;	/* others all to 0 */
4994*404b540aSrobert 	      dn->exponent++;	/* and bump exponent */
4995*404b540aSrobert 	      /* [which, very rarely, could cause Overflow...] */
4996*404b540aSrobert 	      if ((dn->exponent + dn->digits) > set->emax + 1)
4997*404b540aSrobert 		{
4998*404b540aSrobert 		  decSetOverflow (dn, set, status);
4999*404b540aSrobert 		}
5000*404b540aSrobert 	      return;		/* done */
5001*404b540aSrobert 	    }
5002*404b540aSrobert 	  /* a full unit to check, with more to come */
5003*404b540aSrobert 	  if (*up != DECDPUNMAX)
5004*404b540aSrobert 	    break;		/* not still 9s */
5005*404b540aSrobert 	  count -= DECDPUN;
5006*404b540aSrobert 	}			/* up */
5007*404b540aSrobert     }				/* bump>0 */
5008*404b540aSrobert   else
5009*404b540aSrobert     {				/* -1 */
5010*404b540aSrobert       /* here we are lookng for a pre-bump of 1000... (leading 1, */
5011*404b540aSrobert       /* all other digits zero) */
5012*404b540aSrobert       Unit *up, *sup;		/* work */
5013*404b540aSrobert       uInt count = dn->digits;	/* digits to be checked */
5014*404b540aSrobert       for (up = dn->lsu;; up++)
5015*404b540aSrobert 	{
5016*404b540aSrobert 	  if (count <= DECDPUN)
5017*404b540aSrobert 	    {
5018*404b540aSrobert 	      /* this is the last Unit (the msu) */
5019*404b540aSrobert 	      if (*up != powers[count - 1])
5020*404b540aSrobert 		break;		/* not 100.. */
5021*404b540aSrobert 	      /* here if we have the 1000... case */
5022*404b540aSrobert 	      sup = up;		/* save msu pointer */
5023*404b540aSrobert 	      *up = (Unit) powers[count] - 1;	/* here 100 in msu -> 999 */
5024*404b540aSrobert 	      /* others all to all-nines, too */
5025*404b540aSrobert 	      for (up = up - 1; up >= dn->lsu; up--)
5026*404b540aSrobert 		*up = (Unit) powers[DECDPUN] - 1;
5027*404b540aSrobert 	      dn->exponent--;	/* and bump exponent */
5028*404b540aSrobert 
5029*404b540aSrobert 	      /* iff the number was at the subnormal boundary (exponent=etiny) */
5030*404b540aSrobert 	      /* then the exponent is now out of range, so it will in fact get */
5031*404b540aSrobert 	      /* clamped to etiny and the final 9 dropped. */
5032*404b540aSrobert 	      /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
5033*404b540aSrobert 	      /*        dn->exponent, set->digits); */
5034*404b540aSrobert 	      if (dn->exponent + 1 == set->emin - set->digits + 1)
5035*404b540aSrobert 		{
5036*404b540aSrobert 		  if (count == 1 && dn->digits == 1)
5037*404b540aSrobert 		    *sup = 0;	/* here 9 -> 0[.9] */
5038*404b540aSrobert 		  else
5039*404b540aSrobert 		    {
5040*404b540aSrobert 		      *sup = (Unit) powers[count - 1] - 1;	/* here 999.. in msu -> 99.. */
5041*404b540aSrobert 		      dn->digits--;
5042*404b540aSrobert 		    }
5043*404b540aSrobert 		  dn->exponent++;
5044*404b540aSrobert 		  *status |=
5045*404b540aSrobert 		    DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
5046*404b540aSrobert 		}
5047*404b540aSrobert 	      return;		/* done */
5048*404b540aSrobert 	    }
5049*404b540aSrobert 
5050*404b540aSrobert 	  /* a full unit to check, with more to come */
5051*404b540aSrobert 	  if (*up != 0)
5052*404b540aSrobert 	    break;		/* not still 0s */
5053*404b540aSrobert 	  count -= DECDPUN;
5054*404b540aSrobert 	}			/* up */
5055*404b540aSrobert 
5056*404b540aSrobert     }				/* bump<0 */
5057*404b540aSrobert 
5058*404b540aSrobert   /* Actual bump needed.  Do it. */
5059*404b540aSrobert   decUnitAddSub (dn->lsu, D2U (dn->digits), one, 1, 0, dn->lsu, bump);
5060*404b540aSrobert }
5061*404b540aSrobert 
5062*404b540aSrobert #if DECSUBSET
5063*404b540aSrobert /* ------------------------------------------------------------------ */
5064*404b540aSrobert /* decFinish -- finish processing a number                            */
5065*404b540aSrobert /*                                                                    */
5066*404b540aSrobert /*   dn is the number                                                 */
5067*404b540aSrobert /*   set is the context                                               */
5068*404b540aSrobert /*   residue is the rounding accumulator (as in decApplyRound)        */
5069*404b540aSrobert /*   status is the accumulator                                        */
5070*404b540aSrobert /*                                                                    */
5071*404b540aSrobert /* This finishes off the current number by:                           */
5072*404b540aSrobert /*    1. If not extended:                                             */
5073*404b540aSrobert /*       a. Converting a zero result to clean '0'                     */
5074*404b540aSrobert /*       b. Reducing positive exponents to 0, if would fit in digits  */
5075*404b540aSrobert /*    2. Checking for overflow and subnormals (always)                */
5076*404b540aSrobert /* Note this is just Finalize when no subset arithmetic.              */
5077*404b540aSrobert /* All fields are updated as required.                                */
5078*404b540aSrobert /* ------------------------------------------------------------------ */
5079*404b540aSrobert static void
decFinish(decNumber * dn,decContext * set,Int * residue,uInt * status)5080*404b540aSrobert decFinish (decNumber * dn, decContext * set, Int * residue, uInt * status)
5081*404b540aSrobert {
5082*404b540aSrobert   if (!set->extended)
5083*404b540aSrobert     {
5084*404b540aSrobert       if ISZERO
5085*404b540aSrobert 	(dn)
5086*404b540aSrobert 	{			/* value is zero */
5087*404b540aSrobert 	  dn->exponent = 0;	/* clean exponent .. */
5088*404b540aSrobert 	  dn->bits = 0;		/* .. and sign */
5089*404b540aSrobert 	  return;		/* no error possible */
5090*404b540aSrobert 	}
5091*404b540aSrobert       if (dn->exponent >= 0)
5092*404b540aSrobert 	{			/* non-negative exponent */
5093*404b540aSrobert 	  /* >0; reduce to integer if possible */
5094*404b540aSrobert 	  if (set->digits >= (dn->exponent + dn->digits))
5095*404b540aSrobert 	    {
5096*404b540aSrobert 	      dn->digits = decShiftToMost (dn->lsu, dn->digits, dn->exponent);
5097*404b540aSrobert 	      dn->exponent = 0;
5098*404b540aSrobert 	    }
5099*404b540aSrobert 	}
5100*404b540aSrobert     }				/* !extended */
5101*404b540aSrobert 
5102*404b540aSrobert   decFinalize (dn, set, residue, status);
5103*404b540aSrobert }
5104*404b540aSrobert #endif
5105*404b540aSrobert 
5106*404b540aSrobert /* ------------------------------------------------------------------ */
5107*404b540aSrobert /* decFinalize -- final check, clamp, and round of a number           */
5108*404b540aSrobert /*                                                                    */
5109*404b540aSrobert /*   dn is the number                                                 */
5110*404b540aSrobert /*   set is the context                                               */
5111*404b540aSrobert /*   residue is the rounding accumulator (as in decApplyRound)        */
5112*404b540aSrobert /*   status is the status accumulator                                 */
5113*404b540aSrobert /*                                                                    */
5114*404b540aSrobert /* This finishes off the current number by checking for subnormal     */
5115*404b540aSrobert /* results, applying any pending rounding, checking for overflow,     */
5116*404b540aSrobert /* and applying any clamping.                                         */
5117*404b540aSrobert /* Underflow and overflow conditions are raised as appropriate.       */
5118*404b540aSrobert /* All fields are updated as required.                                */
5119*404b540aSrobert /* ------------------------------------------------------------------ */
5120*404b540aSrobert static void
decFinalize(decNumber * dn,decContext * set,Int * residue,uInt * status)5121*404b540aSrobert decFinalize (decNumber * dn, decContext * set, Int * residue, uInt * status)
5122*404b540aSrobert {
5123*404b540aSrobert   Int shift;			/* shift needed if clamping */
5124*404b540aSrobert 
5125*404b540aSrobert   /* We have to be careful when checking the exponent as the adjusted */
5126*404b540aSrobert   /* exponent could overflow 31 bits [because it may already be up */
5127*404b540aSrobert   /* to twice the expected]. */
5128*404b540aSrobert 
5129*404b540aSrobert   /* First test for subnormal.  This must be done before any final */
5130*404b540aSrobert   /* round as the result could be rounded to Nmin or 0. */
5131*404b540aSrobert   if (dn->exponent < 0		/* negative exponent */
5132*404b540aSrobert       && (dn->exponent < set->emin - dn->digits + 1))
5133*404b540aSrobert     {
5134*404b540aSrobert       /* Go handle subnormals; this will apply round if needed. */
5135*404b540aSrobert       decSetSubnormal (dn, set, residue, status);
5136*404b540aSrobert       return;
5137*404b540aSrobert     }
5138*404b540aSrobert 
5139*404b540aSrobert   /* now apply any pending round (this could raise overflow). */
5140*404b540aSrobert   if (*residue != 0)
5141*404b540aSrobert     decApplyRound (dn, set, *residue, status);
5142*404b540aSrobert 
5143*404b540aSrobert   /* Check for overflow [redundant in the 'rare' case] or clamp */
5144*404b540aSrobert   if (dn->exponent <= set->emax - set->digits + 1)
5145*404b540aSrobert     return;			/* neither needed */
5146*404b540aSrobert 
5147*404b540aSrobert   /* here when we might have an overflow or clamp to do */
5148*404b540aSrobert   if (dn->exponent > set->emax - dn->digits + 1)
5149*404b540aSrobert     {				/* too big */
5150*404b540aSrobert       decSetOverflow (dn, set, status);
5151*404b540aSrobert       return;
5152*404b540aSrobert     }
5153*404b540aSrobert   /* here when the result is normal but in clamp range */
5154*404b540aSrobert   if (!set->clamp)
5155*404b540aSrobert     return;
5156*404b540aSrobert 
5157*404b540aSrobert   /* here when we need to apply the IEEE exponent clamp (fold-down) */
5158*404b540aSrobert   shift = dn->exponent - (set->emax - set->digits + 1);
5159*404b540aSrobert 
5160*404b540aSrobert   /* shift coefficient (if non-zero) */
5161*404b540aSrobert   if (!ISZERO (dn))
5162*404b540aSrobert     {
5163*404b540aSrobert       dn->digits = decShiftToMost (dn->lsu, dn->digits, shift);
5164*404b540aSrobert     }
5165*404b540aSrobert   dn->exponent -= shift;	/* adjust the exponent to match */
5166*404b540aSrobert   *status |= DEC_Clamped;	/* and record the dirty deed */
5167*404b540aSrobert   return;
5168*404b540aSrobert }
5169*404b540aSrobert 
5170*404b540aSrobert /* ------------------------------------------------------------------ */
5171*404b540aSrobert /* decSetOverflow -- set number to proper overflow value              */
5172*404b540aSrobert /*                                                                    */
5173*404b540aSrobert /*   dn is the number (used for sign [only] and result)               */
5174*404b540aSrobert /*   set is the context [used for the rounding mode]                  */
5175*404b540aSrobert /*   status contains the current status to be updated                 */
5176*404b540aSrobert /*                                                                    */
5177*404b540aSrobert /* This sets the sign of a number and sets its value to either        */
5178*404b540aSrobert /* Infinity or the maximum finite value, depending on the sign of     */
5179*404b540aSrobert /* dn and therounding mode, following IEEE 854 rules.                 */
5180*404b540aSrobert /* ------------------------------------------------------------------ */
5181*404b540aSrobert static void
decSetOverflow(decNumber * dn,decContext * set,uInt * status)5182*404b540aSrobert decSetOverflow (decNumber * dn, decContext * set, uInt * status)
5183*404b540aSrobert {
5184*404b540aSrobert   Flag needmax = 0;		/* result is maximum finite value */
5185*404b540aSrobert   uByte sign = dn->bits & DECNEG;	/* clean and save sign bit */
5186*404b540aSrobert 
5187*404b540aSrobert   if (ISZERO (dn))
5188*404b540aSrobert     {				/* zero does not overflow magnitude */
5189*404b540aSrobert       Int emax = set->emax;	/* limit value */
5190*404b540aSrobert       if (set->clamp)
5191*404b540aSrobert 	emax -= set->digits - 1;	/* lower if clamping */
5192*404b540aSrobert       if (dn->exponent > emax)
5193*404b540aSrobert 	{			/* clamp required */
5194*404b540aSrobert 	  dn->exponent = emax;
5195*404b540aSrobert 	  *status |= DEC_Clamped;
5196*404b540aSrobert 	}
5197*404b540aSrobert       return;
5198*404b540aSrobert     }
5199*404b540aSrobert 
5200*404b540aSrobert   decNumberZero (dn);
5201*404b540aSrobert   switch (set->round)
5202*404b540aSrobert     {
5203*404b540aSrobert     case DEC_ROUND_DOWN:
5204*404b540aSrobert       {
5205*404b540aSrobert 	needmax = 1;		/* never Infinity */
5206*404b540aSrobert 	break;
5207*404b540aSrobert       }				/* r-d */
5208*404b540aSrobert     case DEC_ROUND_CEILING:
5209*404b540aSrobert       {
5210*404b540aSrobert 	if (sign)
5211*404b540aSrobert 	  needmax = 1;		/* Infinity if non-negative */
5212*404b540aSrobert 	break;
5213*404b540aSrobert       }				/* r-c */
5214*404b540aSrobert     case DEC_ROUND_FLOOR:
5215*404b540aSrobert       {
5216*404b540aSrobert 	if (!sign)
5217*404b540aSrobert 	  needmax = 1;		/* Infinity if negative */
5218*404b540aSrobert 	break;
5219*404b540aSrobert       }				/* r-f */
5220*404b540aSrobert     default:
5221*404b540aSrobert       break;			/* Infinity in all other cases */
5222*404b540aSrobert     }
5223*404b540aSrobert   if (needmax)
5224*404b540aSrobert     {
5225*404b540aSrobert       Unit *up;			/* work */
5226*404b540aSrobert       Int count = set->digits;	/* nines to add */
5227*404b540aSrobert       dn->digits = count;
5228*404b540aSrobert       /* fill in all nines to set maximum value */
5229*404b540aSrobert       for (up = dn->lsu;; up++)
5230*404b540aSrobert 	{
5231*404b540aSrobert 	  if (count > DECDPUN)
5232*404b540aSrobert 	    *up = DECDPUNMAX;	/* unit full o'nines */
5233*404b540aSrobert 	  else
5234*404b540aSrobert 	    {			/* this is the msu */
5235*404b540aSrobert 	      *up = (Unit) (powers[count] - 1);
5236*404b540aSrobert 	      break;
5237*404b540aSrobert 	    }
5238*404b540aSrobert 	  count -= DECDPUN;	/* we filled those digits */
5239*404b540aSrobert 	}			/* up */
5240*404b540aSrobert       dn->bits = sign;		/* sign */
5241*404b540aSrobert       dn->exponent = set->emax - set->digits + 1;
5242*404b540aSrobert     }
5243*404b540aSrobert   else
5244*404b540aSrobert     dn->bits = sign | DECINF;	/* Value is +/-Infinity */
5245*404b540aSrobert   *status |= DEC_Overflow | DEC_Inexact | DEC_Rounded;
5246*404b540aSrobert }
5247*404b540aSrobert 
5248*404b540aSrobert /* ------------------------------------------------------------------ */
5249*404b540aSrobert /* decSetSubnormal -- process value whose exponent is <Emin           */
5250*404b540aSrobert /*                                                                    */
5251*404b540aSrobert /*   dn is the number (used as input as well as output; it may have   */
5252*404b540aSrobert /*         an allowed subnormal value, which may need to be rounded)  */
5253*404b540aSrobert /*   set is the context [used for the rounding mode]                  */
5254*404b540aSrobert /*   residue is any pending residue                                   */
5255*404b540aSrobert /*   status contains the current status to be updated                 */
5256*404b540aSrobert /*                                                                    */
5257*404b540aSrobert /* If subset mode, set result to zero and set Underflow flags.        */
5258*404b540aSrobert /*                                                                    */
5259*404b540aSrobert /* Value may be zero with a low exponent; this does not set Subnormal */
5260*404b540aSrobert /* but the exponent will be clamped to Etiny.                         */
5261*404b540aSrobert /*                                                                    */
5262*404b540aSrobert /* Otherwise ensure exponent is not out of range, and round as        */
5263*404b540aSrobert /* necessary.  Underflow is set if the result is Inexact.             */
5264*404b540aSrobert /* ------------------------------------------------------------------ */
5265*404b540aSrobert static void
decSetSubnormal(decNumber * dn,decContext * set,Int * residue,uInt * status)5266*404b540aSrobert decSetSubnormal (decNumber * dn, decContext * set,
5267*404b540aSrobert 		 Int * residue, uInt * status)
5268*404b540aSrobert {
5269*404b540aSrobert   decContext workset;		/* work */
5270*404b540aSrobert   Int etiny, adjust;		/* .. */
5271*404b540aSrobert 
5272*404b540aSrobert #if DECSUBSET
5273*404b540aSrobert   /* simple set to zero and 'hard underflow' for subset */
5274*404b540aSrobert   if (!set->extended)
5275*404b540aSrobert     {
5276*404b540aSrobert       decNumberZero (dn);
5277*404b540aSrobert       /* always full overflow */
5278*404b540aSrobert       *status |= DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
5279*404b540aSrobert       return;
5280*404b540aSrobert     }
5281*404b540aSrobert #endif
5282*404b540aSrobert 
5283*404b540aSrobert   /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
5284*404b540aSrobert   /* (Etiny) if needed */
5285*404b540aSrobert   etiny = set->emin - (set->digits - 1);	/* smallest allowed exponent */
5286*404b540aSrobert 
5287*404b540aSrobert   if ISZERO
5288*404b540aSrobert     (dn)
5289*404b540aSrobert     {				/* value is zero */
5290*404b540aSrobert       /* residue can never be non-zero here */
5291*404b540aSrobert #if DECCHECK
5292*404b540aSrobert       if (*residue != 0)
5293*404b540aSrobert 	{
5294*404b540aSrobert 	  printf ("++ Subnormal 0 residue %d\n", *residue);
5295*404b540aSrobert 	  *status |= DEC_Invalid_operation;
5296*404b540aSrobert 	}
5297*404b540aSrobert #endif
5298*404b540aSrobert       if (dn->exponent < etiny)
5299*404b540aSrobert 	{			/* clamp required */
5300*404b540aSrobert 	  dn->exponent = etiny;
5301*404b540aSrobert 	  *status |= DEC_Clamped;
5302*404b540aSrobert 	}
5303*404b540aSrobert       return;
5304*404b540aSrobert     }
5305*404b540aSrobert 
5306*404b540aSrobert   *status |= DEC_Subnormal;	/* we have a non-zero subnormal */
5307*404b540aSrobert 
5308*404b540aSrobert   adjust = etiny - dn->exponent;	/* calculate digits to remove */
5309*404b540aSrobert   if (adjust <= 0)
5310*404b540aSrobert     {				/* not out of range; unrounded */
5311*404b540aSrobert       /* residue can never be non-zero here, so fast-path out */
5312*404b540aSrobert #if DECCHECK
5313*404b540aSrobert       if (*residue != 0)
5314*404b540aSrobert 	{
5315*404b540aSrobert 	  printf ("++ Subnormal no-adjust residue %d\n", *residue);
5316*404b540aSrobert 	  *status |= DEC_Invalid_operation;
5317*404b540aSrobert 	}
5318*404b540aSrobert #endif
5319*404b540aSrobert       /* it may already be inexact (from setting the coefficient) */
5320*404b540aSrobert       if (*status & DEC_Inexact)
5321*404b540aSrobert 	*status |= DEC_Underflow;
5322*404b540aSrobert       return;
5323*404b540aSrobert     }
5324*404b540aSrobert 
5325*404b540aSrobert   /* adjust>0.  we need to rescale the result so exponent becomes Etiny */
5326*404b540aSrobert   /* [this code is similar to that in rescale] */
5327*404b540aSrobert   workset = *set;		/* clone rounding, etc. */
5328*404b540aSrobert   workset.digits = dn->digits - adjust;	/* set requested length */
5329*404b540aSrobert   workset.emin -= adjust;	/* and adjust emin to match */
5330*404b540aSrobert   /* [note that the latter can be <1, here, similar to Rescale case] */
5331*404b540aSrobert   decSetCoeff (dn, &workset, dn->lsu, dn->digits, residue, status);
5332*404b540aSrobert   decApplyRound (dn, &workset, *residue, status);
5333*404b540aSrobert 
5334*404b540aSrobert   /* Use 754R/854 default rule: Underflow is set iff Inexact */
5335*404b540aSrobert   /* [independent of whether trapped] */
5336*404b540aSrobert   if (*status & DEC_Inexact)
5337*404b540aSrobert     *status |= DEC_Underflow;
5338*404b540aSrobert 
5339*404b540aSrobert   /* if we rounded up a 999s case, exponent will be off by one; adjust */
5340*404b540aSrobert   /* back if so [it will fit, because we shortened] */
5341*404b540aSrobert   if (dn->exponent > etiny)
5342*404b540aSrobert     {
5343*404b540aSrobert       dn->digits = decShiftToMost (dn->lsu, dn->digits, 1);
5344*404b540aSrobert       dn->exponent--;		/* (re)adjust the exponent. */
5345*404b540aSrobert     }
5346*404b540aSrobert }
5347*404b540aSrobert 
5348*404b540aSrobert /* ------------------------------------------------------------------ */
5349*404b540aSrobert /* decGetInt -- get integer from a number                             */
5350*404b540aSrobert /*                                                                    */
5351*404b540aSrobert /*   dn is the number [which will not be altered]                     */
5352*404b540aSrobert /*   set is the context [requested digits], subset only               */
5353*404b540aSrobert /*   returns the converted integer, or BADINT if error                */
5354*404b540aSrobert /*                                                                    */
5355*404b540aSrobert /* This checks and gets a whole number from the input decNumber.      */
5356*404b540aSrobert /* The magnitude of the integer must be <2^31.                        */
5357*404b540aSrobert /* Any discarded fractional part must be 0.                           */
5358*404b540aSrobert /* If subset it must also fit in set->digits                          */
5359*404b540aSrobert /* ------------------------------------------------------------------ */
5360*404b540aSrobert #if DECSUBSET
5361*404b540aSrobert static Int
decGetInt(const decNumber * dn,decContext * set)5362*404b540aSrobert decGetInt (const decNumber * dn, decContext * set)
5363*404b540aSrobert {
5364*404b540aSrobert #else
5365*404b540aSrobert static Int
5366*404b540aSrobert decGetInt (const decNumber * dn)
5367*404b540aSrobert {
5368*404b540aSrobert #endif
5369*404b540aSrobert   Int theInt;			/* result accumulator */
5370*404b540aSrobert   const Unit *up;		/* work */
5371*404b540aSrobert   Int got;			/* digits (real or not) processed */
5372*404b540aSrobert   Int ilength = dn->digits + dn->exponent;	/* integral length */
5373*404b540aSrobert 
5374*404b540aSrobert   /* The number must be an integer that fits in 10 digits */
5375*404b540aSrobert   /* Assert, here, that 10 is enough for any rescale Etiny */
5376*404b540aSrobert #if DEC_MAX_EMAX > 999999999
5377*404b540aSrobert #error GetInt may need updating [for Emax]
5378*404b540aSrobert #endif
5379*404b540aSrobert #if DEC_MIN_EMIN < -999999999
5380*404b540aSrobert #error GetInt may need updating [for Emin]
5381*404b540aSrobert #endif
5382*404b540aSrobert   if (ISZERO (dn))
5383*404b540aSrobert     return 0;			/* zeros are OK, with any exponent */
5384*404b540aSrobert   if (ilength > 10)
5385*404b540aSrobert     return BADINT;		/* always too big */
5386*404b540aSrobert #if DECSUBSET
5387*404b540aSrobert   if (!set->extended && ilength > set->digits)
5388*404b540aSrobert     return BADINT;
5389*404b540aSrobert #endif
5390*404b540aSrobert 
5391*404b540aSrobert   up = dn->lsu;			/* ready for lsu */
5392*404b540aSrobert   theInt = 0;			/* ready to accumulate */
5393*404b540aSrobert   if (dn->exponent >= 0)
5394*404b540aSrobert     {				/* relatively easy */
5395*404b540aSrobert       /* no fractional part [usual]; allow for positive exponent */
5396*404b540aSrobert       got = dn->exponent;
5397*404b540aSrobert     }
5398*404b540aSrobert   else
5399*404b540aSrobert     {				/* -ve exponent; some fractional part to check and discard */
5400*404b540aSrobert       Int count = -dn->exponent;	/* digits to discard */
5401*404b540aSrobert       /* spin up whole units until we get to the Unit with the unit digit */
5402*404b540aSrobert       for (; count >= DECDPUN; up++)
5403*404b540aSrobert 	{
5404*404b540aSrobert 	  if (*up != 0)
5405*404b540aSrobert 	    return BADINT;	/* non-zero Unit to discard */
5406*404b540aSrobert 	  count -= DECDPUN;
5407*404b540aSrobert 	}
5408*404b540aSrobert       if (count == 0)
5409*404b540aSrobert 	got = 0;		/* [a multiple of DECDPUN] */
5410*404b540aSrobert       else
5411*404b540aSrobert 	{			/* [not multiple of DECDPUN] */
5412*404b540aSrobert 	  Int rem;		/* work */
5413*404b540aSrobert 	  /* slice off fraction digits and check for non-zero */
5414*404b540aSrobert #if DECDPUN<=4
5415*404b540aSrobert 	  theInt = QUOT10 (*up, count);
5416*404b540aSrobert 	  rem = *up - theInt * powers[count];
5417*404b540aSrobert #else
5418*404b540aSrobert 	  rem = *up % powers[count];	/* slice off discards */
5419*404b540aSrobert 	  theInt = *up / powers[count];
5420*404b540aSrobert #endif
5421*404b540aSrobert 	  if (rem != 0)
5422*404b540aSrobert 	    return BADINT;	/* non-zero fraction */
5423*404b540aSrobert 	  /* OK, we're good */
5424*404b540aSrobert 	  got = DECDPUN - count;	/* number of digits so far */
5425*404b540aSrobert 	  up++;			/* ready for next */
5426*404b540aSrobert 	}
5427*404b540aSrobert     }
5428*404b540aSrobert   /* collect the rest */
5429*404b540aSrobert   for (; got < ilength; up++)
5430*404b540aSrobert     {
5431*404b540aSrobert       theInt += *up * powers[got];
5432*404b540aSrobert       got += DECDPUN;
5433*404b540aSrobert     }
5434*404b540aSrobert   if ((ilength == 10)		/* check no wrap */
5435*404b540aSrobert       && (theInt / (Int) powers[got - DECDPUN] != *(up - 1)))
5436*404b540aSrobert     return BADINT;
5437*404b540aSrobert   /* [that test also disallows the BADINT result case] */
5438*404b540aSrobert 
5439*404b540aSrobert   /* apply any sign and return */
5440*404b540aSrobert   if (decNumberIsNegative (dn))
5441*404b540aSrobert     theInt = -theInt;
5442*404b540aSrobert   return theInt;
5443*404b540aSrobert }
5444*404b540aSrobert 
5445*404b540aSrobert /* ------------------------------------------------------------------ */
5446*404b540aSrobert /* decStrEq -- caseless comparison of strings                         */
5447*404b540aSrobert /*                                                                    */
5448*404b540aSrobert /*   str1 is one of the strings to compare                            */
5449*404b540aSrobert /*   str2 is the other                                                */
5450*404b540aSrobert /*                                                                    */
5451*404b540aSrobert /*   returns 1 if strings caseless-compare equal, 0 otherwise         */
5452*404b540aSrobert /*                                                                    */
5453*404b540aSrobert /* Note that the strings must be the same length if they are to       */
5454*404b540aSrobert /* compare equal; there is no padding.                                */
5455*404b540aSrobert /* ------------------------------------------------------------------ */
5456*404b540aSrobert /* [strcmpi is not in ANSI C] */
5457*404b540aSrobert static Flag
5458*404b540aSrobert decStrEq (const char *str1, const char *str2)
5459*404b540aSrobert {
5460*404b540aSrobert   for (;; str1++, str2++)
5461*404b540aSrobert     {
5462*404b540aSrobert       unsigned char u1 = (unsigned char) *str1;
5463*404b540aSrobert       unsigned char u2 = (unsigned char) *str2;
5464*404b540aSrobert       if (u1 == u2)
5465*404b540aSrobert 	{
5466*404b540aSrobert 	  if (u1 == '\0')
5467*404b540aSrobert 	    break;
5468*404b540aSrobert 	}
5469*404b540aSrobert       else
5470*404b540aSrobert 	{
5471*404b540aSrobert 	  if (tolower (u1) != tolower (u2))
5472*404b540aSrobert 	    return 0;
5473*404b540aSrobert 	}
5474*404b540aSrobert     }				/* stepping */
5475*404b540aSrobert   return 1;
5476*404b540aSrobert }
5477*404b540aSrobert 
5478*404b540aSrobert /* ------------------------------------------------------------------ */
5479*404b540aSrobert /* decNaNs -- handle NaN operand or operands                          */
5480*404b540aSrobert /*                                                                    */
5481*404b540aSrobert /*   res    is the result number                                      */
5482*404b540aSrobert /*   lhs    is the first operand                                      */
5483*404b540aSrobert /*   rhs    is the second operand, or NULL if none                    */
5484*404b540aSrobert /*   status contains the current status                               */
5485*404b540aSrobert /*   returns res in case convenient                                   */
5486*404b540aSrobert /*                                                                    */
5487*404b540aSrobert /* Called when one or both operands is a NaN, and propagates the      */
5488*404b540aSrobert /* appropriate result to res.  When an sNaN is found, it is changed   */
5489*404b540aSrobert /* to a qNaN and Invalid operation is set.                            */
5490*404b540aSrobert /* ------------------------------------------------------------------ */
5491*404b540aSrobert static decNumber *
5492*404b540aSrobert decNaNs (decNumber * res, const decNumber * lhs, const decNumber * rhs, uInt * status)
5493*404b540aSrobert {
5494*404b540aSrobert   /* This decision tree ends up with LHS being the source pointer, */
5495*404b540aSrobert   /* and status updated if need be */
5496*404b540aSrobert   if (lhs->bits & DECSNAN)
5497*404b540aSrobert     *status |= DEC_Invalid_operation | DEC_sNaN;
5498*404b540aSrobert   else if (rhs == NULL);
5499*404b540aSrobert   else if (rhs->bits & DECSNAN)
5500*404b540aSrobert     {
5501*404b540aSrobert       lhs = rhs;
5502*404b540aSrobert       *status |= DEC_Invalid_operation | DEC_sNaN;
5503*404b540aSrobert     }
5504*404b540aSrobert   else if (lhs->bits & DECNAN);
5505*404b540aSrobert   else
5506*404b540aSrobert     lhs = rhs;
5507*404b540aSrobert 
5508*404b540aSrobert   decNumberCopy (res, lhs);
5509*404b540aSrobert   res->bits &= ~DECSNAN;	/* convert any sNaN to NaN, while */
5510*404b540aSrobert   res->bits |= DECNAN;		/* .. preserving sign */
5511*404b540aSrobert   res->exponent = 0;		/* clean exponent */
5512*404b540aSrobert   /* [coefficient was copied] */
5513*404b540aSrobert   return res;
5514*404b540aSrobert }
5515*404b540aSrobert 
5516*404b540aSrobert /* ------------------------------------------------------------------ */
5517*404b540aSrobert /* decStatus -- apply non-zero status                                 */
5518*404b540aSrobert /*                                                                    */
5519*404b540aSrobert /*   dn     is the number to set if error                             */
5520*404b540aSrobert /*   status contains the current status (not yet in context)          */
5521*404b540aSrobert /*   set    is the context                                            */
5522*404b540aSrobert /*                                                                    */
5523*404b540aSrobert /* If the status is an error status, the number is set to a NaN,      */
5524*404b540aSrobert /* unless the error was an overflow, divide-by-zero, or underflow,    */
5525*404b540aSrobert /* in which case the number will have already been set.               */
5526*404b540aSrobert /*                                                                    */
5527*404b540aSrobert /* The context status is then updated with the new status.  Note that */
5528*404b540aSrobert /* this may raise a signal, so control may never return from this     */
5529*404b540aSrobert /* routine (hence resources must be recovered before it is called).   */
5530*404b540aSrobert /* ------------------------------------------------------------------ */
5531*404b540aSrobert static void
5532*404b540aSrobert decStatus (decNumber * dn, uInt status, decContext * set)
5533*404b540aSrobert {
5534*404b540aSrobert   if (status & DEC_NaNs)
5535*404b540aSrobert     {				/* error status -> NaN */
5536*404b540aSrobert       /* if cause was an sNaN, clear and propagate [NaN is already set up] */
5537*404b540aSrobert       if (status & DEC_sNaN)
5538*404b540aSrobert 	status &= ~DEC_sNaN;
5539*404b540aSrobert       else
5540*404b540aSrobert 	{
5541*404b540aSrobert 	  decNumberZero (dn);	/* other error: clean throughout */
5542*404b540aSrobert 	  dn->bits = DECNAN;	/* and make a quiet NaN */
5543*404b540aSrobert 	}
5544*404b540aSrobert     }
5545*404b540aSrobert   decContextSetStatus (set, status);
5546*404b540aSrobert   return;
5547*404b540aSrobert }
5548*404b540aSrobert 
5549*404b540aSrobert /* ------------------------------------------------------------------ */
5550*404b540aSrobert /* decGetDigits -- count digits in a Units array                      */
5551*404b540aSrobert /*                                                                    */
5552*404b540aSrobert /*   uar is the Unit array holding the number [this is often an       */
5553*404b540aSrobert /*          accumulator of some sort]                                 */
5554*404b540aSrobert /*   len is the length of the array in units                          */
5555*404b540aSrobert /*                                                                    */
5556*404b540aSrobert /*   returns the number of (significant) digits in the array          */
5557*404b540aSrobert /*                                                                    */
5558*404b540aSrobert /* All leading zeros are excluded, except the last if the array has   */
5559*404b540aSrobert /* only zero Units.                                                   */
5560*404b540aSrobert /* ------------------------------------------------------------------ */
5561*404b540aSrobert /* This may be called twice during some operations. */
5562*404b540aSrobert static Int
5563*404b540aSrobert decGetDigits (const Unit * uar, Int len)
5564*404b540aSrobert {
5565*404b540aSrobert   const Unit *up = uar + len - 1;	/* -> msu */
5566*404b540aSrobert   Int digits = len * DECDPUN;	/* maximum possible digits */
5567*404b540aSrobert   uInt const *pow;		/* work */
5568*404b540aSrobert 
5569*404b540aSrobert   for (; up >= uar; up--)
5570*404b540aSrobert     {
5571*404b540aSrobert       digits -= DECDPUN;
5572*404b540aSrobert       if (*up == 0)
5573*404b540aSrobert 	{			/* unit is 0 */
5574*404b540aSrobert 	  if (digits != 0)
5575*404b540aSrobert 	    continue;		/* more to check */
5576*404b540aSrobert 	  /* all units were 0 */
5577*404b540aSrobert 	  digits++;		/* .. so bump digits to 1 */
5578*404b540aSrobert 	  break;
5579*404b540aSrobert 	}
5580*404b540aSrobert       /* found the first non-zero Unit */
5581*404b540aSrobert       digits++;
5582*404b540aSrobert       if (*up < 10)
5583*404b540aSrobert 	break;			/* fastpath 1-9 */
5584*404b540aSrobert       digits++;
5585*404b540aSrobert       for (pow = &powers[2]; *up >= *pow; pow++)
5586*404b540aSrobert 	digits++;
5587*404b540aSrobert       break;
5588*404b540aSrobert     }				/* up */
5589*404b540aSrobert 
5590*404b540aSrobert   return digits;
5591*404b540aSrobert }
5592*404b540aSrobert 
5593*404b540aSrobert 
5594*404b540aSrobert #if DECTRACE | DECCHECK
5595*404b540aSrobert /* ------------------------------------------------------------------ */
5596*404b540aSrobert /* decNumberShow -- display a number [debug aid]                      */
5597*404b540aSrobert /*   dn is the number to show                                         */
5598*404b540aSrobert /*                                                                    */
5599*404b540aSrobert /* Shows: sign, exponent, coefficient (msu first), digits             */
5600*404b540aSrobert /*    or: sign, special-value                                         */
5601*404b540aSrobert /* ------------------------------------------------------------------ */
5602*404b540aSrobert /* this is public so other modules can use it */
5603*404b540aSrobert void
5604*404b540aSrobert decNumberShow (const decNumber * dn)
5605*404b540aSrobert {
5606*404b540aSrobert   const Unit *up;		/* work */
5607*404b540aSrobert   uInt u, d;			/* .. */
5608*404b540aSrobert   Int cut;			/* .. */
5609*404b540aSrobert   char isign = '+';		/* main sign */
5610*404b540aSrobert   if (dn == NULL)
5611*404b540aSrobert     {
5612*404b540aSrobert       printf ("NULL\n");
5613*404b540aSrobert       return;
5614*404b540aSrobert     }
5615*404b540aSrobert   if (decNumberIsNegative (dn))
5616*404b540aSrobert     isign = '-';
5617*404b540aSrobert   printf (" >> %c ", isign);
5618*404b540aSrobert   if (dn->bits & DECSPECIAL)
5619*404b540aSrobert     {				/* Is a special value */
5620*404b540aSrobert       if (decNumberIsInfinite (dn))
5621*404b540aSrobert 	printf ("Infinity");
5622*404b540aSrobert       else
5623*404b540aSrobert 	{			/* a NaN */
5624*404b540aSrobert 	  if (dn->bits & DECSNAN)
5625*404b540aSrobert 	    printf ("sNaN");	/* signalling NaN */
5626*404b540aSrobert 	  else
5627*404b540aSrobert 	    printf ("NaN");
5628*404b540aSrobert 	}
5629*404b540aSrobert       /* if coefficient and exponent are 0, we're done */
5630*404b540aSrobert       if (dn->exponent == 0 && dn->digits == 1 && *dn->lsu == 0)
5631*404b540aSrobert 	{
5632*404b540aSrobert 	  printf ("\n");
5633*404b540aSrobert 	  return;
5634*404b540aSrobert 	}
5635*404b540aSrobert       /* drop through to report other information */
5636*404b540aSrobert       printf (" ");
5637*404b540aSrobert     }
5638*404b540aSrobert 
5639*404b540aSrobert   /* now carefully display the coefficient */
5640*404b540aSrobert   up = dn->lsu + D2U (dn->digits) - 1;	/* msu */
5641*404b540aSrobert   printf ("%d", *up);
5642*404b540aSrobert   for (up = up - 1; up >= dn->lsu; up--)
5643*404b540aSrobert     {
5644*404b540aSrobert       u = *up;
5645*404b540aSrobert       printf (":");
5646*404b540aSrobert       for (cut = DECDPUN - 1; cut >= 0; cut--)
5647*404b540aSrobert 	{
5648*404b540aSrobert 	  d = u / powers[cut];
5649*404b540aSrobert 	  u -= d * powers[cut];
5650*404b540aSrobert 	  printf ("%d", d);
5651*404b540aSrobert 	}			/* cut */
5652*404b540aSrobert     }				/* up */
5653*404b540aSrobert   if (dn->exponent != 0)
5654*404b540aSrobert     {
5655*404b540aSrobert       char esign = '+';
5656*404b540aSrobert       if (dn->exponent < 0)
5657*404b540aSrobert 	esign = '-';
5658*404b540aSrobert       printf (" E%c%d", esign, abs (dn->exponent));
5659*404b540aSrobert     }
5660*404b540aSrobert   printf (" [%d]\n", dn->digits);
5661*404b540aSrobert }
5662*404b540aSrobert #endif
5663*404b540aSrobert 
5664*404b540aSrobert #if DECTRACE || DECCHECK
5665*404b540aSrobert /* ------------------------------------------------------------------ */
5666*404b540aSrobert /* decDumpAr -- display a unit array [debug aid]                      */
5667*404b540aSrobert /*   name is a single-character tag name                              */
5668*404b540aSrobert /*   ar   is the array to display                                     */
5669*404b540aSrobert /*   len  is the length of the array in Units                         */
5670*404b540aSrobert /* ------------------------------------------------------------------ */
5671*404b540aSrobert static void
5672*404b540aSrobert decDumpAr (char name, const Unit * ar, Int len)
5673*404b540aSrobert {
5674*404b540aSrobert   Int i;
5675*404b540aSrobert #if DECDPUN==4
5676*404b540aSrobert   const char *spec = "%04d ";
5677*404b540aSrobert #else
5678*404b540aSrobert   const char *spec = "%d ";
5679*404b540aSrobert #endif
5680*404b540aSrobert   printf ("  :%c: ", name);
5681*404b540aSrobert   for (i = len - 1; i >= 0; i--)
5682*404b540aSrobert     {
5683*404b540aSrobert       if (i == len - 1)
5684*404b540aSrobert 	printf ("%d ", ar[i]);
5685*404b540aSrobert       else
5686*404b540aSrobert 	printf (spec, ar[i]);
5687*404b540aSrobert     }
5688*404b540aSrobert   printf ("\n");
5689*404b540aSrobert   return;
5690*404b540aSrobert }
5691*404b540aSrobert #endif
5692*404b540aSrobert 
5693*404b540aSrobert #if DECCHECK
5694*404b540aSrobert /* ------------------------------------------------------------------ */
5695*404b540aSrobert /* decCheckOperands -- check operand(s) to a routine                  */
5696*404b540aSrobert /*   res is the result structure (not checked; it will be set to      */
5697*404b540aSrobert /*          quiet NaN if error found (and it is not NULL))            */
5698*404b540aSrobert /*   lhs is the first operand (may be DECUNUSED)                      */
5699*404b540aSrobert /*   rhs is the second (may be DECUNUSED)                             */
5700*404b540aSrobert /*   set is the context (may be DECUNUSED)                            */
5701*404b540aSrobert /*   returns 0 if both operands, and the context are clean, or 1      */
5702*404b540aSrobert /*     otherwise (in which case the context will show an error,       */
5703*404b540aSrobert /*     unless NULL).  Note that res is not cleaned; caller should     */
5704*404b540aSrobert /*     handle this so res=NULL case is safe.                          */
5705*404b540aSrobert /* The caller is expected to abandon immediately if 1 is returned.    */
5706*404b540aSrobert /* ------------------------------------------------------------------ */
5707*404b540aSrobert static Flag
5708*404b540aSrobert decCheckOperands (decNumber * res, const decNumber * lhs,
5709*404b540aSrobert 		  const decNumber * rhs, decContext * set)
5710*404b540aSrobert {
5711*404b540aSrobert   Flag bad = 0;
5712*404b540aSrobert   if (set == NULL)
5713*404b540aSrobert     {				/* oops; hopeless */
5714*404b540aSrobert #if DECTRACE
5715*404b540aSrobert       printf ("Context is NULL.\n");
5716*404b540aSrobert #endif
5717*404b540aSrobert       bad = 1;
5718*404b540aSrobert       return 1;
5719*404b540aSrobert     }
5720*404b540aSrobert   else if (set != DECUNUSED
5721*404b540aSrobert 	   && (set->digits < 1 || set->round < 0
5722*404b540aSrobert 	       || set->round >= DEC_ROUND_MAX))
5723*404b540aSrobert     {
5724*404b540aSrobert       bad = 1;
5725*404b540aSrobert #if DECTRACE
5726*404b540aSrobert       printf ("Bad context [digits=%d round=%d].\n", set->digits, set->round);
5727*404b540aSrobert #endif
5728*404b540aSrobert     }
5729*404b540aSrobert   else
5730*404b540aSrobert     {
5731*404b540aSrobert       if (res == NULL)
5732*404b540aSrobert 	{
5733*404b540aSrobert 	  bad = 1;
5734*404b540aSrobert #if DECTRACE
5735*404b540aSrobert 	  printf ("Bad result [is NULL].\n");
5736*404b540aSrobert #endif
5737*404b540aSrobert 	}
5738*404b540aSrobert       if (!bad && lhs != DECUNUSED)
5739*404b540aSrobert 	bad = (decCheckNumber (lhs, set));
5740*404b540aSrobert       if (!bad && rhs != DECUNUSED)
5741*404b540aSrobert 	bad = (decCheckNumber (rhs, set));
5742*404b540aSrobert     }
5743*404b540aSrobert   if (bad)
5744*404b540aSrobert     {
5745*404b540aSrobert       if (set != DECUNUSED)
5746*404b540aSrobert 	decContextSetStatus (set, DEC_Invalid_operation);
5747*404b540aSrobert       if (res != DECUNUSED && res != NULL)
5748*404b540aSrobert 	{
5749*404b540aSrobert 	  decNumberZero (res);
5750*404b540aSrobert 	  res->bits = DECNAN;	/* qNaN */
5751*404b540aSrobert 	}
5752*404b540aSrobert     }
5753*404b540aSrobert   return bad;
5754*404b540aSrobert }
5755*404b540aSrobert 
5756*404b540aSrobert /* ------------------------------------------------------------------ */
5757*404b540aSrobert /* decCheckNumber -- check a number                                   */
5758*404b540aSrobert /*   dn is the number to check                                        */
5759*404b540aSrobert /*   set is the context (may be DECUNUSED)                            */
5760*404b540aSrobert /*   returns 0 if the number is clean, or 1 otherwise                 */
5761*404b540aSrobert /*                                                                    */
5762*404b540aSrobert /* The number is considered valid if it could be a result from some   */
5763*404b540aSrobert /* operation in some valid context (not necessarily the current one). */
5764*404b540aSrobert /* ------------------------------------------------------------------ */
5765*404b540aSrobert Flag
5766*404b540aSrobert decCheckNumber (const decNumber * dn, decContext * set)
5767*404b540aSrobert {
5768*404b540aSrobert   const Unit *up;		/* work */
5769*404b540aSrobert   uInt maxuint;			/* .. */
5770*404b540aSrobert   Int ae, d, digits;		/* .. */
5771*404b540aSrobert   Int emin, emax;		/* .. */
5772*404b540aSrobert 
5773*404b540aSrobert   if (dn == NULL)
5774*404b540aSrobert     {				/* hopeless */
5775*404b540aSrobert #if DECTRACE
5776*404b540aSrobert       printf ("Reference to decNumber is NULL.\n");
5777*404b540aSrobert #endif
5778*404b540aSrobert       return 1;
5779*404b540aSrobert     }
5780*404b540aSrobert 
5781*404b540aSrobert   /* check special values */
5782*404b540aSrobert   if (dn->bits & DECSPECIAL)
5783*404b540aSrobert     {
5784*404b540aSrobert       if (dn->exponent != 0)
5785*404b540aSrobert 	{
5786*404b540aSrobert #if DECTRACE
5787*404b540aSrobert 	  printf ("Exponent %d (not 0) for a special value.\n", dn->exponent);
5788*404b540aSrobert #endif
5789*404b540aSrobert 	  return 1;
5790*404b540aSrobert 	}
5791*404b540aSrobert 
5792*404b540aSrobert       /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
5793*404b540aSrobert       if (decNumberIsInfinite (dn))
5794*404b540aSrobert 	{
5795*404b540aSrobert 	  if (dn->digits != 1)
5796*404b540aSrobert 	    {
5797*404b540aSrobert #if DECTRACE
5798*404b540aSrobert 	      printf ("Digits %d (not 1) for an infinity.\n", dn->digits);
5799*404b540aSrobert #endif
5800*404b540aSrobert 	      return 1;
5801*404b540aSrobert 	    }
5802*404b540aSrobert 	  if (*dn->lsu != 0)
5803*404b540aSrobert 	    {
5804*404b540aSrobert #if DECTRACE
5805*404b540aSrobert 	      printf ("LSU %d (not 0) for an infinity.\n", *dn->lsu);
5806*404b540aSrobert #endif
5807*404b540aSrobert 	      return 1;
5808*404b540aSrobert 	    }
5809*404b540aSrobert 	}			/* Inf */
5810*404b540aSrobert       /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
5811*404b540aSrobert       /*             concrete formats (decimal64, etc.), though they are */
5812*404b540aSrobert       /*             never visible in strings. */
5813*404b540aSrobert       return 0;
5814*404b540aSrobert 
5815*404b540aSrobert       /* if ((dn->bits & DECINF) || (dn->bits & DECNEG)==0) return 0; */
5816*404b540aSrobert       /* #if DECTRACE */
5817*404b540aSrobert       /* printf("Negative NaN in number.\n"); */
5818*404b540aSrobert       /* #endif */
5819*404b540aSrobert       /* return 1; */
5820*404b540aSrobert     }
5821*404b540aSrobert 
5822*404b540aSrobert   /* check the coefficient */
5823*404b540aSrobert   if (dn->digits < 1 || dn->digits > DECNUMMAXP)
5824*404b540aSrobert     {
5825*404b540aSrobert #if DECTRACE
5826*404b540aSrobert       printf ("Digits %d in number.\n", dn->digits);
5827*404b540aSrobert #endif
5828*404b540aSrobert       return 1;
5829*404b540aSrobert     }
5830*404b540aSrobert 
5831*404b540aSrobert   d = dn->digits;
5832*404b540aSrobert 
5833*404b540aSrobert   for (up = dn->lsu; d > 0; up++)
5834*404b540aSrobert     {
5835*404b540aSrobert       if (d > DECDPUN)
5836*404b540aSrobert 	maxuint = DECDPUNMAX;
5837*404b540aSrobert       else
5838*404b540aSrobert 	{			/* we are at the msu */
5839*404b540aSrobert 	  maxuint = powers[d] - 1;
5840*404b540aSrobert 	  if (dn->digits > 1 && *up < powers[d - 1])
5841*404b540aSrobert 	    {
5842*404b540aSrobert #if DECTRACE
5843*404b540aSrobert 	      printf ("Leading 0 in number.\n");
5844*404b540aSrobert 	      decNumberShow (dn);
5845*404b540aSrobert #endif
5846*404b540aSrobert 	      return 1;
5847*404b540aSrobert 	    }
5848*404b540aSrobert 	}
5849*404b540aSrobert       if (*up > maxuint)
5850*404b540aSrobert 	{
5851*404b540aSrobert #if DECTRACE
5852*404b540aSrobert 	  printf ("Bad Unit [%08x] in number at offset %d [maxuint %d].\n",
5853*404b540aSrobert 		  *up, up - dn->lsu, maxuint);
5854*404b540aSrobert #endif
5855*404b540aSrobert 	  return 1;
5856*404b540aSrobert 	}
5857*404b540aSrobert       d -= DECDPUN;
5858*404b540aSrobert     }
5859*404b540aSrobert 
5860*404b540aSrobert   /* check the exponent.  Note that input operands can have exponents */
5861*404b540aSrobert   /* which are out of the set->emin/set->emax and set->digits range */
5862*404b540aSrobert   /* (just as they can have more digits than set->digits). */
5863*404b540aSrobert   ae = dn->exponent + dn->digits - 1;	/* adjusted exponent */
5864*404b540aSrobert   emax = DECNUMMAXE;
5865*404b540aSrobert   emin = DECNUMMINE;
5866*404b540aSrobert   digits = DECNUMMAXP;
5867*404b540aSrobert   if (ae < emin - (digits - 1))
5868*404b540aSrobert     {
5869*404b540aSrobert #if DECTRACE
5870*404b540aSrobert       printf ("Adjusted exponent underflow [%d].\n", ae);
5871*404b540aSrobert       decNumberShow (dn);
5872*404b540aSrobert #endif
5873*404b540aSrobert       return 1;
5874*404b540aSrobert     }
5875*404b540aSrobert   if (ae > +emax)
5876*404b540aSrobert     {
5877*404b540aSrobert #if DECTRACE
5878*404b540aSrobert       printf ("Adjusted exponent overflow [%d].\n", ae);
5879*404b540aSrobert       decNumberShow (dn);
5880*404b540aSrobert #endif
5881*404b540aSrobert       return 1;
5882*404b540aSrobert     }
5883*404b540aSrobert 
5884*404b540aSrobert   return 0;			/* it's OK */
5885*404b540aSrobert }
5886*404b540aSrobert #endif
5887*404b540aSrobert 
5888*404b540aSrobert #if DECALLOC
5889*404b540aSrobert #undef malloc
5890*404b540aSrobert #undef free
5891*404b540aSrobert /* ------------------------------------------------------------------ */
5892*404b540aSrobert /* decMalloc -- accountable allocation routine                        */
5893*404b540aSrobert /*   n is the number of bytes to allocate                             */
5894*404b540aSrobert /*                                                                    */
5895*404b540aSrobert /* Semantics is the same as the stdlib malloc routine, but bytes      */
5896*404b540aSrobert /* allocated are accounted for globally, and corruption fences are    */
5897*404b540aSrobert /* added before and after the 'actual' storage.                       */
5898*404b540aSrobert /* ------------------------------------------------------------------ */
5899*404b540aSrobert /* This routine allocates storage with an extra twelve bytes; 8 are   */
5900*404b540aSrobert /* at the start and hold:                                             */
5901*404b540aSrobert /*   0-3 the original length requested                                */
5902*404b540aSrobert /*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
5903*404b540aSrobert /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
5904*404b540aSrobert /* ------------------------------------------------------------------ */
5905*404b540aSrobert static void *
5906*404b540aSrobert decMalloc (uInt n)
5907*404b540aSrobert {
5908*404b540aSrobert   uInt size = n + 12;		/* true size */
5909*404b540aSrobert   void *alloc;			/* -> allocated storage */
5910*404b540aSrobert   uInt *j;			/* work */
5911*404b540aSrobert   uByte *b, *b0;		/* .. */
5912*404b540aSrobert 
5913*404b540aSrobert   alloc = malloc (size);	/* -> allocated storage */
5914*404b540aSrobert   if (alloc == NULL)
5915*404b540aSrobert     return NULL;		/* out of strorage */
5916*404b540aSrobert   b0 = (uByte *) alloc;		/* as bytes */
5917*404b540aSrobert   decAllocBytes += n;		/* account for storage */
5918*404b540aSrobert   j = (uInt *) alloc;		/* -> first four bytes */
5919*404b540aSrobert   *j = n;			/* save n */
5920*404b540aSrobert   /* printf("++ alloc(%d)\n", n); */
5921*404b540aSrobert   for (b = b0 + 4; b < b0 + 8; b++)
5922*404b540aSrobert     *b = DECFENCE;
5923*404b540aSrobert   for (b = b0 + n + 8; b < b0 + n + 12; b++)
5924*404b540aSrobert     *b = DECFENCE;
5925*404b540aSrobert   return b0 + 8;		/* -> play area */
5926*404b540aSrobert }
5927*404b540aSrobert 
5928*404b540aSrobert /* ------------------------------------------------------------------ */
5929*404b540aSrobert /* decFree -- accountable free routine                                */
5930*404b540aSrobert /*   alloc is the storage to free                                     */
5931*404b540aSrobert /*                                                                    */
5932*404b540aSrobert /* Semantics is the same as the stdlib malloc routine, except that    */
5933*404b540aSrobert /* the global storage accounting is updated and the fences are        */
5934*404b540aSrobert /* checked to ensure that no routine has written 'out of bounds'.     */
5935*404b540aSrobert /* ------------------------------------------------------------------ */
5936*404b540aSrobert /* This routine first checks that the fences have not been corrupted. */
5937*404b540aSrobert /* It then frees the storage using the 'truw' storage address (that   */
5938*404b540aSrobert /* is, offset by 8).                                                  */
5939*404b540aSrobert /* ------------------------------------------------------------------ */
5940*404b540aSrobert static void
5941*404b540aSrobert decFree (void *alloc)
5942*404b540aSrobert {
5943*404b540aSrobert   uInt *j, n;			/* pointer, original length */
5944*404b540aSrobert   uByte *b, *b0;		/* work */
5945*404b540aSrobert 
5946*404b540aSrobert   if (alloc == NULL)
5947*404b540aSrobert     return;			/* allowed; it's a nop */
5948*404b540aSrobert   b0 = (uByte *) alloc;		/* as bytes */
5949*404b540aSrobert   b0 -= 8;			/* -> true start of storage */
5950*404b540aSrobert   j = (uInt *) b0;		/* -> first four bytes */
5951*404b540aSrobert   n = *j;			/* lift */
5952*404b540aSrobert   for (b = b0 + 4; b < b0 + 8; b++)
5953*404b540aSrobert     if (*b != DECFENCE)
5954*404b540aSrobert       printf ("=== Corrupt byte [%02x] at offset %d from %d ===\n", *b,
5955*404b540aSrobert 	      b - b0 - 8, (Int) b0);
5956*404b540aSrobert   for (b = b0 + n + 8; b < b0 + n + 12; b++)
5957*404b540aSrobert     if (*b != DECFENCE)
5958*404b540aSrobert       printf ("=== Corrupt byte [%02x] at offset +%d from %d, n=%d ===\n", *b,
5959*404b540aSrobert 	      b - b0 - 8, (Int) b0, n);
5960*404b540aSrobert   free (b0);			/* drop the storage */
5961*404b540aSrobert   decAllocBytes -= n;		/* account for storage */
5962*404b540aSrobert }
5963*404b540aSrobert #endif
5964