-
Notifications
You must be signed in to change notification settings - Fork 0
/
decNumber.c
6702 lines (6268 loc) · 306 KB
/
decNumber.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------------------------------------------------------------------ */
/* Decimal Number arithmetic module */
/* ------------------------------------------------------------------ */
/* Copyright (c) IBM Corporation, 2000, 2006. All rights reserved. */
/* */
/* This software is made available under the terms of the */
/* ICU License -- ICU 1.8.1 and later. */
/* */
/* The description and User's Guide ("The decNumber C Library") for */
/* this software is called decNumber.pdf. This document is */
/* available, together with arithmetic and format specifications, */
/* testcases, and Web links, at: http://www2.hursley.ibm.com/decimal */
/* */
/* Please send comments, suggestions, and corrections to the author: */
/* mfc@uk.ibm.com */
/* Mike Cowlishaw, IBM Fellow */
/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */
/* ------------------------------------------------------------------ */
/* This module comprises the routines for General Decimal Arithmetic */
/* as defined in the specification which may be found on the */
/* http://www2.hursley.ibm.com/decimal web pages. It implements both */
/* the full ('extended') arithmetic and the simpler ('subset') */
/* arithmetic. */
/* */
/* Usage notes: */
/* */
/* 1. This code is ANSI C89 except: */
/* */
/* a) C99 line comments (double forward slash) are used. (Most C */
/* compilers accept these. If yours does not, a simple script */
/* can be used to convert them to ANSI C comments.) */
/* */
/* b) Types from C99 stdint.h are used. If you do not have this */
/* header file, see the User's Guide section of the decNumber */
/* documentation; this lists the necessary definitions. */
/* */
/* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */
/* uint64_t types may be used. To avoid these, set DECUSE64=0 */
/* and DECDPUN<=4 (see documentation). */
/* */
/* 2. The decNumber format which this library uses is optimized for */
/* efficient processing of relatively short numbers; in particular */
/* it allows the use of fixed sized structures and minimizes copy */
/* and move operations. It does, however, support arbitrary */
/* precision (up to 999,999,999 digits) and arbitrary exponent */
/* range (Emax in the range 0 through 999,999,999 and Emin in the */
/* range -999,999,999 through 0). Mathematical functions (for */
/* example decNumberExp) as identified below are restricted more */
/* tightly: digits, emax, and -emin in the context must be <= */
/* DEC_MAX_MATH (999999), and their operand(s) must be within */
/* these bounds. */
/* */
/* 3. Operands to operator functions are never modified unless they */
/* are also specified to be the result number (which is always */
/* permitted). Other than that case, operands must not overlap. */
/* */
/* 4. Error handling: the type of the error is ORed into the status */
/* flags in the current context (decContext structure). The */
/* SIGFPE signal is then raised if the corresponding trap-enabler */
/* flag in the decContext is set (is 1). */
/* */
/* It is the responsibility of the caller to clear the status */
/* flags as required. */
/* */
/* The result of any routine which returns a number will always */
/* be a valid number (which may be a special value, such as an */
/* Infinity or NaN). */
/* */
/* 5. The decNumber format is not an exchangeable concrete */
/* representation as it comprises fields which may be machine- */
/* dependent (packed or unpacked, or special length, for example). */
/* Canonical conversions to and from strings are provided; other */
/* conversions are available in separate modules. */
/* */
/* 6. Normally, input operands are assumed to be valid. Set DECCHECK */
/* to 1 for extended operand checking (including NULL operands). */
/* Results are undefined if a badly-formed structure (or a NULL */
/* pointer to a structure) is provided, though with DECCHECK */
/* enabled the operator routines are protected against exceptions. */
/* (Except if the result pointer is NULL, which is unrecoverable.) */
/* */
/* However, the routines will never cause exceptions if they are */
/* given well-formed operands, even if the value of the operands */
/* is inappropriate for the operation and DECCHECK is not set. */
/* (Except for SIGFPE, as and where documented.) */
/* */
/* 7. Subset arithmetic is available only if DECSUBSET is set to 1. */
/* ------------------------------------------------------------------ */
/* Implementation notes for maintenance of this module: */
/* */
/* 1. Storage leak protection: Routines which use malloc are not */
/* permitted to use return for fastpath or error exits (i.e., */
/* they follow strict structured programming conventions). */
/* Instead they have a do{}while(0); construct surrounding the */
/* code which is protected -- break may be used to exit this. */
/* Other routines can safely use the return statement inline. */
/* */
/* Storage leak accounting can be enabled using DECALLOC. */
/* */
/* 2. All loops use the for(;;) construct. Any do construct does */
/* not loop; it is for allocation protection as just described. */
/* */
/* 3. Setting status in the context must always be the very last */
/* action in a routine, as non-0 status may raise a trap and hence */
/* the call to set status may not return (if the handler uses long */
/* jump). Therefore all cleanup must be done first. In general, */
/* to achieve this status is accumulated and is only applied just */
/* before return by calling decContextSetStatus (via decStatus). */
/* */
/* Routines which allocate storage cannot, in general, use the */
/* 'top level' routines which could cause a non-returning */
/* transfer of control. The decXxxxOp routines are safe (do not */
/* call decStatus even if traps are set in the context) and should */
/* be used instead (they are also a little faster). */
/* */
/* 4. Exponent checking is minimized by allowing the exponent to */
/* grow outside its limits during calculations, provided that */
/* the decFinalize function is called later. Multiplication and */
/* division, and intermediate calculations in exponentiation, */
/* require more careful checks because of the risk of 31-bit */
/* overflow (the most negative valid exponent is -1999999997, for */
/* a 999999999-digit number with adjusted exponent of -999999999). */
/* */
/* 5. Rounding is deferred until finalization of results, with any */
/* 'off to the right' data being represented as a single digit */
/* residue (in the range -1 through 9). This avoids any double- */
/* rounding when more than one shortening takes place (for */
/* example, when a result is subnormal). */
/* */
/* 6. The digits count is allowed to rise to a multiple of DECDPUN */
/* during many operations, so whole Units are handled and exact */
/* accounting of digits is not needed. The correct digits value */
/* is found by decGetDigits, which accounts for leading zeros. */
/* This must be called before any rounding if the number of digits */
/* is not known exactly. */
/* */
/* 7. The multiply-by-reciprocal 'trick' is used for partitioning */
/* numbers up to four digits, using appropriate constants. This */
/* is not useful for longer numbers because overflow of 32 bits */
/* would lead to 4 multiplies, which is almost as expensive as */
/* a divide (unless a floating-point or 64-bit multiply is */
/* assumed to be available). */
/* */
/* 8. Unusual abbreviations that may be used in the commentary: */
/* lhs -- left hand side (operand, of an operation) */
/* lsd -- least significant digit (of coefficient) */
/* lsu -- least significant Unit (of coefficient) */
/* msd -- most significant digit (of coefficient) */
/* msi -- most significant item (in an array) */
/* msu -- most significant Unit (of coefficient) */
/* rhs -- right hand side (operand, of an operation) */
/* +ve -- positive */
/* -ve -- negative */
/* ** -- raise to the power */
/* ------------------------------------------------------------------ */
//#include <stdlib.h> // for malloc, free, etc.
#if DECTRACE | DECCHECK
#include <stdio.h> // for printf [if needed]
#endif
#include "decNumber.h" // base number library
#include "decNumberLocal.h" // decNumber local types, etc.
#include <string.h> // form xcopy == memcpy
/* Constants */
// Public constant array: powers of ten (powers[n]==10**n, 0<=n<=9)
const uInt powers[10]={1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000};
// Public lookup table used by the D2U macro
//const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
// Local constants
#define DIVIDE 0x80 // Divide operators
#define REMAINDER 0x40 // ..
#define DIVIDEINT 0x20 // ..
#define REMNEAR 0x10 // ..
#define COMPARE 0x01 // Compare operators
#define COMPMAX 0x02 // ..
#define COMPMIN 0x03 // ..
#define COMPTOTAL 0x04 // ..
#define COMPNAN 0x05 // .. [NaN processing]
#define DEC_sNaN 0x40000000 // local status: sNaN signal
#define BADINT (Int)0x80000000 // most-negative Int; error indicator
// Next two indicate an integer >= 10**6, and its parity (bottom bit)
#define BIGODD (Int)0x80000001
#define BIGEVEN (Int)0x80000001
static const Unit uarrone[1]={1}; // Unit array of 1, used for incrementing
/* Granularity-dependent code */
#if DECDPUN<=4
#define eInt Int // extended integer
#define ueInt uInt // unsigned extended integer
// Constant multipliers for divide-by-power-of five using reciprocal
// multiply, after removing powers of 2 by shifting, and final shift
// of 17 [we only need up to **4]
static const uInt multies[]={131073, 26215, 5243, 1049, 210};
// QUOT10 -- macro to return the quotient of unit u divided by 10**n
#define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
#else
// For DECDPUN>4 non-ANSI-89 64-bit types are needed.
#if !DECUSE64
#error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
#endif
#define eInt Long // extended integer
#define ueInt uLong // unsigned extended integer
#endif
#ifdef DECNUMBER_PROFILE
/* Profiling info */
int dnpf_add, dnpf_mul, dnpf_div;
#define PF_ADD() (++dnpf_add)
#define PF_MUL() (++dnpf_mul)
#define PF_DIV() (++dnpf_div)
#else
#define PF_ADD()
#define PF_MUL()
#define PF_DIV()
#endif
/* Local routines */
static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
decContext *, uByte, uInt *);
static Flag decBiStr(const char *, const char *, const char *);
static uInt decCheckMath(const decNumber *, decContext *, uInt *);
static void decApplyRound(decNumber *, decContext *, Int, uInt *);
static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
static decNumber * decCompareOp(decNumber *, const decNumber *,
const decNumber *, decContext *,
Flag, uInt *);
static void decCopyFit(decNumber *, const decNumber *, decContext *,
Int *, uInt *);
static decNumber * decDivideOp(decNumber *, const decNumber *,
const decNumber *, decContext *, Flag, uInt *);
static decNumber * decExpOp(decNumber *, const decNumber *,
decContext *, uInt *);
static void decFinalize(decNumber *, decContext *, Int *, uInt *);
static Int decGetDigits(Unit *, Int);
/*static*/ Int decGetInt(const decNumber *);
//static decNumber * decLnOp(decNumber *, const decNumber *,
// decContext *, uInt *);
static decNumber * decMultiplyOp(decNumber *, const decNumber *,
const decNumber *, decContext *,
uInt *);
static decNumber * decNaNs(decNumber *, const decNumber *,
const decNumber *, uInt *);
//static decNumber * decPutInt(decNumber *, Int);
static decNumber * decQuantizeOp(decNumber *, const decNumber *,
const decNumber *, decContext *, Flag,
uInt *);
static void decSetCoeff(decNumber *, decContext *, const Unit *,
Int, Int *, uInt *);
static void decSetOverflow(decNumber *, decContext *, uInt *);
static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
static Int decShiftToLeast(Unit *, Int, Int);
static Int decShiftToMost(Unit *, Int, Int);
static void decStatus(decNumber *, uInt, decContext *);
static void decToString(const decNumber *, char[], Flag);
static decNumber * decTrim(decNumber *, Flag, Int *);
static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
Unit *, Int);
static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
//#ifndef xcopy
// extern void *xcopy(void *, const void *, int);
//#endif
#if !DECSUBSET
/* decFinish == decFinalize when no subset arithmetic needed */
#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
#else
static void decFinish(decNumber *, decContext *, Int *, uInt *);
static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
#endif
/* Local macros */
// masked special-values bits
#define SPECIALARG (rhs->bits & DECSPECIAL)
#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
#ifdef WIN32
static char xPool[2048];
static char* xPtr = xPool;
/* specialised malloc/free used for alloca replacement, either for
* windows or other compilers not supporting alloca.
*/
static void* xmalloc(unsigned int n)
{
char* p = xPtr;
if (p + n <= xPool + sizeof(xPool))
xPtr += n;
else
p = 0;
return p;
}
static void xfree(void* a)
{
if ((char*)a < xPtr) xPtr = (char*)a;
}
#endif // WIN32
/* Diagnostic macros, etc. */
#if DECALLOC
// Handle malloc/free accounting. If enabled, our accountable routines
// are used; otherwise the code just goes straight to the system malloc
// and free routines.
#define malloc(a) decMalloc(a)
#define free(a) decFree(a)
#define DECFENCE 0x5a // corruption detector
// 'Our' malloc and free:
static void *decMalloc(size_t);
static void decFree(void *);
uInt decAllocBytes=0; // count of bytes allocated
// Note that DECALLOC code only checks for storage buffer overflow.
// To check for memory leaks, the decAllocBytes variable must be
// checked to be 0 at appropriate times (e.g., after the test
// harness completes a set of tests). This checking may be unreliable
// if the testing is done in a multi-thread environment.
#else
#ifndef WIN32
#define malloc(a) __builtin_alloca(a)
#define free(a)
#else // WIN32
#define malloc(a) xmalloc(a)
#define free(a) xfree(a)
#endif // !WIN32
#endif
#if DECCHECK
// Optional operand checking routines. Enabling these means that
// decNumber and decContext operands to operator routines are checked
// for correctness. This roughly doubles the execution time of the
// fastest routines (and adds 600+ bytes), so should not normally be
// used in 'production'.
#define DECUNUSED (void *)(0xffffffff)
static Flag decCheckOperands(decNumber *, const decNumber *,
const decNumber *, decContext *);
static Flag decCheckNumber(const decNumber *, decContext *);
#endif
#if DECTRACE || DECCHECK
// Optional trace/debugging routines (may or may not be used)
void decNumberShow(const decNumber *); // displays the components of a number
static void decDumpAr(char, const Unit *, Int);
#endif
/* ================================================================== */
/* Conversions */
/* ================================================================== */
/* ------------------------------------------------------------------ */
/* to-scientific-string -- conversion to numeric string */
/* to-engineering-string -- conversion to numeric string */
/* */
/* decNumberToString(dn, string); */
/* decNumberToEngString(dn, string); */
/* */
/* dn is the decNumber to convert */
/* string is the string where the result will be laid out */
/* */
/* string must be at least dn->digits+14 characters long */
/* */
/* No error is possible, and no status can be set. */
/* ------------------------------------------------------------------ */
char * decNumberToString(const decNumber *dn, char *string){
decToString(dn, string, 0);
return string;
} // DecNumberToString
#if 0
char * decNumberToEngString(const decNumber *dn, char *string){
decToString(dn, string, 1);
return string;
} // DecNumberToEngString
#endif
/* ------------------------------------------------------------------ */
/* to-number -- conversion from numeric string */
/* */
/* decNumberFromString -- convert string to decNumber */
/* dn -- the number structure to fill */
/* chars[] -- the string to convert ('\0' terminated) */
/* set -- the context used for processing any error, */
/* determining the maximum precision available */
/* (set.digits), determining the maximum and minimum */
/* exponent (set.emax and set.emin), determining if */
/* extended values are allowed, and checking the */
/* rounding mode if overflow occurs or rounding is */
/* needed. */
/* */
/* The length of the coefficient and the size of the exponent are */
/* checked by this routine, so the correct error (Underflow or */
/* Overflow) can be reported or rounding applied, as necessary. */
/* */
/* If bad syntax is detected, the result will be a quiet NaN. */
/* ------------------------------------------------------------------ */
decNumber * decNumberFromString(decNumber *dn, const char chars[],
decContext *set) {
Int exponent=0; // working exponent [assume 0]
uByte bits=0; // working flags [assume +ve]
Unit *res; // where result will be built
Unit resbuff[SD2U(DECBUFFER+1)];// local buffer in case need temporary
Unit *allocres=NULL; // -> allocated result, iff allocated
Int d=0; // count of digits found in decimal part
const char *dotchar=NULL; // where dot was found
const char *cfirst=chars; // -> first character of decimal part
const char *last=NULL; // -> last digit of decimal part
const char *c; // work
Unit *up; // ..
#if DECDPUN>1
Int cut, out; // ..
#endif
Int residue; // rounding residue
uInt status=0; // error code
#if DECCHECK
if (decCheckOperands(DECUNUSED, DECUNUSED, DECUNUSED, set))
return decNumberZero(dn);
#endif
do { // status & malloc protection
for (c=chars;; c++) { // -> input character
if (*c>='0' && *c<='9') { // test for Arabic digit
last=c;
d++; // count of real digits
continue; // still in decimal part
}
if (*c=='.' && dotchar==NULL) { // first '.'
dotchar=c; // record offset into decimal part
if (c==cfirst) cfirst++; // first digit must follow
continue;}
if (c==chars) { // first in string...
if (*c=='-') { // valid - sign
cfirst++;
bits=DECNEG;
continue;}
if (*c=='+') { // valid + sign
cfirst++;
continue;}
}
// *c is not a digit, or a valid +, -, or '.'
break;
} // c
if (last==NULL) { // no digits yet
status=DEC_Conversion_syntax;// assume the worst
if (*c=='\0') break; // and no more to come...
#if DECSUBSET
// if subset then infinities and NaNs are not allowed
if (!set->extended) break; // hopeless
#endif
// Infinities and NaNs are possible, here
decNumberZero(dn); // be optimistic
if (decBiStr(c, "infinity", "INFINITY")
|| decBiStr(c, "inf", "INF")) {
dn->bits=bits | DECINF;
status=0; // is OK
break; // all done
}
// a NaN expected
// 2003.09.10 NaNs are now permitted to have a sign
dn->bits=bits | DECNAN; // assume simple NaN
if (*c=='s' || *c=='S') { // looks like an sNaN
c++;
dn->bits=bits | DECSNAN;
}
if (*c!='n' && *c!='N') break; // check caseless "NaN"
c++;
if (*c!='a' && *c!='A') break; // ..
c++;
if (*c!='n' && *c!='N') break; // ..
c++;
// now either nothing, or nnnn payload, expected
// -> start of integer and skip leading 0s [including plain 0]
for (cfirst=c; *cfirst=='0';) cfirst++;
if (*cfirst=='\0') { // "NaN" or "sNaN", maybe with all 0s
status=0; // it's good
break; // ..
}
// something other than 0s; setup last and d as usual [no dots]
for (c=cfirst;; c++, d++) {
if (*c<'0' || *c>'9') break; // test for Arabic digit
last=c;
}
if (*c!='\0') break; // not all digits
if (d>set->digits) break; // too many digits
// [NB: payload in a decNumber can be full length]
// good; drop through to convert the integer to coefficient
status=0; // syntax is OK
bits=dn->bits; // for copy-back
} // last==NULL
else if (*c!='\0') { // more to process...
// had some digits; exponent is only valid sequence now
Flag nege; // 1=negative exponent
const char *firstexp; // -> first significant exponent digit
status=DEC_Conversion_syntax;// assume the worst
if (*c!='e' && *c!='E') break;
/* Found 'e' or 'E' -- now process explicit exponent */
// 1998.07.11: sign no longer required
nege=0;
c++; // to (possible) sign
if (*c=='-') {nege=1; c++;}
else if (*c=='+') c++;
if (*c=='\0') break;
for (; *c=='0' && *(c+1)!='\0';) c++; // strip insignificant zeros
firstexp=c; // save exponent digit place
for (; ;c++) {
if (*c<'0' || *c>'9') break; // not a digit
exponent=X10(exponent)+(Int)*c-(Int)'0';
} // c
// if not now on a '\0', *c must not be a digit
if (*c!='\0') break;
// (this next test must be after the syntax checks)
// if it was too long the exponent may have wrapped, so check
// carefully and set it to a certain overflow if wrap possible
if (c>=firstexp+9+1) {
if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
// [up to 1999999999 is OK, for example 1E-1000000998]
}
if (nege) exponent=-exponent; // was negative
status=0; // is OK
} // stuff after digits
// Here when whole string has been inspected; syntax is good
// cfirst->first digit (never dot), last->last digit (ditto)
// strip leading zeros/dot [leave final 0 if all 0's]
if (*cfirst=='0') { // [cfirst has stepped over .]
for (c=cfirst; c<last; c++, cfirst++) {
if (*c=='.') continue; // ignore dots
if (*c!='0') break; // non-zero found
d--; // 0 stripped
} // c
#if DECSUBSET
// make a rapid exit for easy zeros if !extended
if (*cfirst=='0' && !set->extended) {
decNumberZero(dn); // clean result
break; // [could be return]
}
#endif
} // at least one leading 0
// Handle decimal point...
if (dotchar!=NULL && dotchar<last) // non-trailing '.' found?
exponent-=(last-dotchar); // adjust exponent
// [we can now ignore the .]
// OK, the digits string is good. Assemble in the decNumber, or in
// a temporary units array if rounding is needed
if (d<=set->digits) res=dn->lsu; // fits into supplied decNumber
else { // rounding needed
Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
res=resbuff; // assume use local buffer
if (needbytes>(Int)sizeof(resbuff)) { // too big for local
allocres=(Unit *)malloc(needbytes);
if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
res=allocres;
}
}
// res now -> number lsu, buffer, or allocated storage for Unit array
// Place the coefficient into the selected Unit array
// [this is often 70% of the cost of this function when DECDPUN>1]
#if DECDPUN>1
out=0; // accumulator
up=res+D2U(d)-1; // -> msu
cut=d-(up-res)*DECDPUN; // digits in top unit
for (c=cfirst;; c++) { // along the digits
if (*c=='.') continue; // ignore '.' [don't decrement cut]
out=X10(out)+(Int)*c-(Int)'0';
if (c==last) break; // done [never get to trailing '.']
cut--;
if (cut>0) continue; // more for this unit
*up=(Unit)out; // write unit
up--; // prepare for unit below..
cut=DECDPUN; // ..
out=0; // ..
} // c
*up=(Unit)out; // write lsu
#else
// DECDPUN==1
up=res; // -> lsu
for (c=last; c>=cfirst; c--) { // over each character, from least
if (*c=='.') continue; // ignore . [don't step up]
*up=(Unit)((Int)*c-(Int)'0');
up++;
} // c
#endif
dn->bits=bits;
dn->exponent=exponent;
dn->digits=d;
// if not in number (too long) shorten into the number
if (d>set->digits) {
residue=0;
decSetCoeff(dn, set, res, d, &residue, &status);
// always check for overflow or subnormal and round as needed
decFinalize(dn, set, &residue, &status);
}
else { // no rounding, but may still have overflow or subnormal
// [these tests are just for performance; finalize repeats them]
if ((dn->exponent-1<set->emin-dn->digits)
|| (dn->exponent-1>set->emax-set->digits)) {
residue=0;
decFinalize(dn, set, &residue, &status);
}
}
// decNumberShow(dn);
} while(0); // [for break]
if (allocres!=NULL) free(allocres); // drop any storage used
if (status!=0) decStatus(dn, status, set);
return dn;
} /* decNumberFromString */
/* ================================================================== */
/* Operators */
/* ================================================================== */
/* ------------------------------------------------------------------ */
/* decNumberAbs -- absolute value operator */
/* */
/* This computes C = abs(A) */
/* */
/* res is C, the result. C may be A */
/* rhs is A */
/* set is the context */
/* */
/* C must have space for set->digits digits. */
/* ------------------------------------------------------------------ */
/* This has the same effect as decNumberPlus unless A is negative, */
/* in which case it has the same effect as decNumberMinus. */
/* ------------------------------------------------------------------ */
decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
decContext *set) {
decNumber dzero; // for 0
uInt status=0; // accumulator
#if DECCHECK
if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
#endif
decNumberZero(&dzero); // set 0
dzero.exponent=rhs->exponent; // [no coefficient expansion]
decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
if (status!=0) decStatus(res, status, set);
return res;
} // decNumberAbs
/* ------------------------------------------------------------------ */
/* decNumberAdd -- add two Numbers */
/* */
/* This computes C = A + B */
/* */
/* res is C, the result. C may be A and/or B (e.g., X=X+X) */
/* lhs is A */
/* rhs is B */
/* set is the context */
/* */
/* C must have space for set->digits digits. */
/* ------------------------------------------------------------------ */
/* This just calls the routine shared with Subtract */
decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; // accumulator
decAddOp(res, lhs, rhs, set, 0, &status);
if (status!=0) decStatus(res, status, set);
PF_ADD();
return res;
} // decNumberAdd
/* ------------------------------------------------------------------ */
/* decNumberCompare -- compare two Numbers */
/* */
/* This computes C = A ? B */
/* */
/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
/* lhs is A */
/* rhs is B */
/* set is the context */
/* */
/* C must have space for one digit (or NaN). */
/* ------------------------------------------------------------------ */
decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; // accumulator
decCompareOp(res, lhs, rhs, set, COMPARE, &status);
if (status!=0) decStatus(res, status, set);
PF_ADD();
return res;
} // decNumberCompare
/* ------------------------------------------------------------------ */
/* decNumberCompareTotal -- compare two Numbers, using total ordering */
/* */
/* This computes C = A ? B, under total ordering */
/* */
/* res is C, the result. C may be A and/or B (e.g., X=X?X) */
/* lhs is A */
/* rhs is B */
/* set is the context */
/* */
/* C must have space for one digit; the result will always be one of */
/* -1, 0, or 1. */
/* ------------------------------------------------------------------ */
#if 0
decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; // accumulator
decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
if (status!=0) decStatus(res, status, set);
return res;
} // decNumberCompareTotal
#endif
/* ------------------------------------------------------------------ */
/* decNumberDivide -- divide one number by another */
/* */
/* This computes C = A / B */
/* */
/* res is C, the result. C may be A and/or B (e.g., X=X/X) */
/* lhs is A */
/* rhs is B */
/* set is the context */
/* */
/* C must have space for set->digits digits. */
/* ------------------------------------------------------------------ */
decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; // accumulator
decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
if (status!=0) decStatus(res, status, set);
PF_DIV();
return res;
} // decNumberDivide
/* ------------------------------------------------------------------ */
/* decNumberDivideInteger -- divide and return integer quotient */
/* */
/* This computes C = A # B, where # is the integer divide operator */
/* */
/* res is C, the result. C may be A and/or B (e.g., X=X#X) */
/* lhs is A */
/* rhs is B */
/* set is the context */
/* */
/* C must have space for set->digits digits. */
/* ------------------------------------------------------------------ */
#if 0
decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; // accumulator
decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
if (status!=0) decStatus(res, status, set);
return res;
} // decNumberDivideInteger
#endif
/* ------------------------------------------------------------------ */
/* decNumberExp -- exponentiation */
/* */
/* This computes C = exp(A) */
/* */
/* res is C, the result. C may be A */
/* rhs is A */
/* set is the context; note that rounding mode has no effect */
/* */
/* C must have space for set->digits digits. */
/* */
/* Mathematical function restrictions apply (see above); a NaN is */
/* returned with Invalid_operation if a restriction is violated. */
/* */
/* Finite results will always be full precision and Inexact, except */
/* when A is a zero or -Infinity (giving 1 or 0 respectively). */
/* */
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
/* almost always be correctly rounded, but may be up to 1 ulp in */
/* error in rare cases. */
/* ------------------------------------------------------------------ */
/* This is a wrapper for decExpOp which can handle the slightly wider */
/* (double) range needed by Ln (which has to be able to calculate */
/* exp(-a) where a can be the tiniest number (Ntiny). */
/* ------------------------------------------------------------------ */
decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
decContext *set) {
uInt status=0; // accumulator
#if DECSUBSET
decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
#endif
#if DECCHECK
if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
#endif
// Check restrictions; these restrictions ensure that if h=8 (see
// decExpOp) then the result will either overflow or underflow to 0.
// Other math functions restrict the input range, too, for inverses.
// If not violated then carry out the operation.
if (!decCheckMath(rhs, set, &status)) do { // protect allocation
#if DECSUBSET
if (!set->extended) {
// reduce operand and set lostDigits status, as needed
if (rhs->digits>set->digits) {
allocrhs=decRoundOperand(rhs, set, &status);
if (allocrhs==NULL) break;
rhs=allocrhs;
}
}
#endif
decExpOp(res, rhs, set, &status);
} while(0); // end protected
#if DECSUBSET
if (allocrhs !=NULL) free(allocrhs); // drop any storage used
#endif
// apply significant status
if (status!=0) decStatus(res, status, set);
return res;
} // decNumberExp
/* ------------------------------------------------------------------ */
/* decNumberLn -- natural logarithm */
/* */
/* This computes C = ln(A) */
/* */
/* res is C, the result. C may be A */
/* rhs is A */
/* set is the context; note that rounding mode has no effect */
/* */
/* C must have space for set->digits digits. */
/* */
/* Notable cases: */
/* A<0 -> Invalid */
/* A=0 -> -Infinity (Exact) */
/* A=+Infinity -> +Infinity (Exact) */
/* A=1 exactly -> 0 (Exact) */
/* */
/* Mathematical function restrictions apply (see above); a NaN is */
/* returned with Invalid_operation if a restriction is violated. */
/* */
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
/* almost always be correctly rounded, but may be up to 1 ulp in */
/* error in rare cases. */
/* ------------------------------------------------------------------ */
/* This is a wrapper for decLnOp which can handle the slightly wider */
/* (+11) range needed by Ln, Log10, etc. (which may have to be able */
/* to calculate at p+e+2). */
/* ------------------------------------------------------------------ */
#if 0
decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
decContext *set) {
uInt status=0; // accumulator
#if DECSUBSET
decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
#endif
#if DECCHECK
if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
#endif
// Check restrictions; this is a math function; if not violated
// then carry out the operation.
if (!decCheckMath(rhs, set, &status)) do { // protect allocation
#if DECSUBSET
if (!set->extended) {
// reduce operand and set lostDigits status, as needed
if (rhs->digits>set->digits) {
allocrhs=decRoundOperand(rhs, set, &status);
if (allocrhs==NULL) break;
rhs=allocrhs;
}
// special check in subset for rhs=0
if (ISZERO(rhs)) { // +/- zeros -> error
status|=DEC_Invalid_operation;
break;}
} // extended=0
#endif
decLnOp(res, rhs, set, &status);
} while(0); // end protected
#if DECSUBSET
if (allocrhs !=NULL) free(allocrhs); // drop any storage used
#endif
// apply significant status
if (status!=0) decStatus(res, status, set);
return res;
} // decNumberLn
#endif
#if 0
/* ------------------------------------------------------------------ */
/* decNumberLog10 -- logarithm in base 10 */
/* */
/* This computes C = log10(A) */
/* */
/* res is C, the result. C may be A */
/* rhs is A */
/* set is the context; note that rounding mode has no effect */
/* */
/* C must have space for set->digits digits. */
/* */
/* Notable cases: */
/* A<0 -> Invalid */
/* A=0 -> -Infinity (Exact) */
/* A=+Infinity -> +Infinity (Exact) */
/* A=10**n (if n is an integer) -> n (Exact) */
/* */
/* Mathematical function restrictions apply (see above); a NaN is */
/* returned with Invalid_operation if a restriction is violated. */
/* */
/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */
/* almost always be correctly rounded, but may be up to 1 ulp in */
/* error in rare cases. */
/* ------------------------------------------------------------------ */
/* This calculates ln(A)/ln(10) using appropriate precision. For */
/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */
/* requested digits and t is the number of digits in the exponent */
/* (maximum 6). For ln(10) it is p + 3; this is often handled by the */
/* fastpath in decLnOp. The final division is done to the requested */
/* precision. */
/* ------------------------------------------------------------------ */
decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
decContext *set) {
uInt status=0, ignore=0; // status accumulators
uInt needbytes; // for space calculations
Int p; // working precision
Int t; // digits in exponent of A
// buffers for a and b working decimals
// (adjustment calculator, same size)
decNumber bufa[D2N(DECBUFFER+2)];
decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated
decNumber *a=bufa; // temporary a
decNumber bufb[D2N(DECBUFFER+2)];
decNumber *allocbufb=NULL; // -> allocated bufa, iff allocated
decNumber *b=bufb; // temporary b
decNumber bufw[D2N(10)]; // working 2-10 digit number
decNumber *w=bufw; // ..
#if DECSUBSET
decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated
#endif
decContext aset; // working context
#if DECCHECK
if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
#endif
// Check restrictions; this is a math function; if not violated
// then carry out the operation.
if (!decCheckMath(rhs, set, &status)) do { // protect malloc
#if DECSUBSET
if (!set->extended) {
// reduce operand and set lostDigits status, as needed
if (rhs->digits>set->digits) {
allocrhs=decRoundOperand(rhs, set, &status);
if (allocrhs==NULL) break;
rhs=allocrhs;
}
// special check in subset for rhs=0
if (ISZERO(rhs)) { // +/- zeros -> error
status|=DEC_Invalid_operation;
break;}
} // extended=0
#endif
decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
// handle exact powers of 10; only check if +ve finite
if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
Int residue=0; // (no residue)
uInt copystat=0; // clean status
// round to a single digit...
aset.digits=1;
decCopyFit(w, rhs, &aset, &residue, ©stat); // copy & shorten
// if exact and the digit is 1, rhs is a power of 10
if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
// the exponent, conveniently, is the power of 10; making
// this the result needs a little care as it might not fit,
// so first convert it into the working number, and then move
// to res
decPutInt(w, w->exponent);
residue=0;
decCopyFit(res, w, set, &residue, &status); // copy & round
decFinish(res, set, &residue, &status); // cleanup/set flags
break;
} // not a power of 10
} // not a candidate for exact