forked from gcc-mirror/gcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decNumber.c
8137 lines (7636 loc) · 321 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 for the decNumber C Library.
Copyright (C) 2005-2020 Free Software Foundation, Inc.
Contributed by IBM Corporation. Author Mike Cowlishaw.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
/* ------------------------------------------------------------------ */
/* Decimal Number arithmetic module */
/* ------------------------------------------------------------------ */
/* This module comprises the routines for arbitrary-precision General */
/* Decimal Arithmetic as defined in the specification which may be */
/* found on the General Decimal Arithmetic 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). */
/* */
/* The code also conforms to C99 restrictions; in particular, */
/* strict aliasing rules are observed. */
/* */
/* 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. Logical functions are further restricted; their operands must */
/* be finite, positive, have an exponent of zero, and all digits */
/* must be either 0 or 1. The result will only contain digits */
/* which are 0 or 1 (and will have exponent=0 and a sign of 0). */
/* */
/* 4. 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. */
/* */
/* 5. 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). */
/* */
/* 6. 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. */
/* */
/* 7. 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.) */
/* */
/* 8. 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. */
#include <stdio.h> /* for printf [if needed] */
#include <string.h> /* for strcpy */
#include <ctype.h> /* for lower */
#include "dconfig.h" /* for GCC definitions */
#include "decNumber.h" /* base number library */
#include "decNumberLocal.h" /* decNumber local types, etc. */
/* Constants */
/* Public lookup table used by the D2U macro */
const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
#define DECVERB 1 /* set to 1 for verbose DECCHECK */
#define powers DECPOWERS /* old internal name */
/* 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 COMPSIG 0x06 /* .. [signaling COMPARE] */
#define COMPMAXMAG 0x07 /* .. */
#define COMPMINMAG 0x08 /* .. */
#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 BIGEVEN (Int)0x80000002
#define BIGODD (Int)0x80000003
static 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
/* 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 * decDecap(decNumber *, Int);
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 *, decContext *, uInt *);
static decNumber * decQuantizeOp(decNumber *, const decNumber *,
const decNumber *, decContext *, Flag,
uInt *);
static void decReverse(Unit *, Unit *);
static void decSetCoeff(decNumber *, decContext *, const Unit *,
Int, Int *, uInt *);
static void decSetMaxValue(decNumber *, decContext *);
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 *, decContext *, Flag, Flag, Int *);
static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
Unit *, Int);
static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
#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)
/* 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. */
#endif
#if DECCHECK
/* Optional 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'. */
/* decCheckInexact is used to check that inexact results have a full */
/* complement of digits (where appropriate -- this is not the case */
/* for Quantize, for example) */
#define DECUNRESU ((decNumber *)(void *)0xffffffff)
#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
#define DECUNCONT ((decContext *)(void *)(0xffffffff))
static Flag decCheckOperands(decNumber *, const decNumber *,
const decNumber *, decContext *);
static Flag decCheckNumber(const decNumber *);
static void decCheckInexact(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 */
/* ================================================================== */
/* ------------------------------------------------------------------ */
/* from-int32 -- conversion from Int or uInt */
/* */
/* dn is the decNumber to receive the integer */
/* in or uin is the integer to be converted */
/* returns dn */
/* */
/* No error is possible. */
/* ------------------------------------------------------------------ */
decNumber * decNumberFromInt32(decNumber *dn, Int in) {
uInt unsig;
if (in>=0) unsig=in;
else { /* negative (possibly BADINT) */
if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
else unsig=-in; /* invert */
}
/* in is now positive */
decNumberFromUInt32(dn, unsig);
if (in<0) dn->bits=DECNEG; /* sign needed */
return dn;
} /* decNumberFromInt32 */
decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
Unit *up; /* work pointer */
decNumberZero(dn); /* clean */
if (uin==0) return dn; /* [or decGetDigits bad call] */
for (up=dn->lsu; uin>0; up++) {
*up=(Unit)(uin%(DECDPUNMAX+1));
uin=uin/(DECDPUNMAX+1);
}
dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
return dn;
} /* decNumberFromUInt32 */
/* ------------------------------------------------------------------ */
/* to-int32 -- conversion to Int or uInt */
/* */
/* dn is the decNumber to convert */
/* set is the context for reporting errors */
/* returns the converted decNumber, or 0 if Invalid is set */
/* */
/* Invalid is set if the decNumber does not have exponent==0 or if */
/* it is a NaN, Infinite, or out-of-range. */
/* ------------------------------------------------------------------ */
Int decNumberToInt32(const decNumber *dn, decContext *set) {
#if DECCHECK
if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
#endif
/* special or too many digits, or bad exponent */
if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
else { /* is a finite integer with 10 or fewer digits */
Int d; /* work */
const Unit *up; /* .. */
uInt hi=0, lo; /* .. */
up=dn->lsu; /* -> lsu */
lo=*up; /* get 1 to 9 digits */
#if DECDPUN>1 /* split to higher */
hi=lo/10;
lo=lo%10;
#endif
up++;
/* collect remaining Units, if any, into hi */
for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
/* now low has the lsd, hi the remainder */
if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
/* most-negative is a reprieve */
if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
/* bad -- drop through */
}
else { /* in-range always */
Int i=X10(hi)+lo;
if (dn->bits&DECNEG) return -i;
return i;
}
} /* integer */
decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
return 0;
} /* decNumberToInt32 */
uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
#if DECCHECK
if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
#endif
/* special or too many digits, or bad exponent, or negative (<0) */
if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
|| (dn->bits&DECNEG && !ISZERO(dn))); /* bad */
else { /* is a finite integer with 10 or fewer digits */
Int d; /* work */
const Unit *up; /* .. */
uInt hi=0, lo; /* .. */
up=dn->lsu; /* -> lsu */
lo=*up; /* get 1 to 9 digits */
#if DECDPUN>1 /* split to higher */
hi=lo/10;
lo=lo%10;
#endif
up++;
/* collect remaining Units, if any, into hi */
for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
/* now low has the lsd, hi the remainder */
if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
else return X10(hi)+lo;
} /* integer */
decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
return 0;
} /* decNumberToUInt32 */
/* ------------------------------------------------------------------ */
/* 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 */
char * decNumberToEngString(const decNumber *dn, char *string){
decToString(dn, string, 1);
return string;
} /* DecNumberToEngString */
/* ------------------------------------------------------------------ */
/* 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+9)];/* local buffer in case need temporary */
/* [+9 allows for ln() constants] */
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(DECUNRESU, 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 */
if (dotchar!=NULL) break; /* .. unless had a dot */
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-1) {
/* [NB: payload in a decNumber can be full length unless */
/* clamped, in which case can only be digits-1] */
if (set->clamp) break;
if (d>set->digits) break;
} /* too many digits? */
/* 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] */
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 */
/* */
/* See also decNumberCopyAbs for a quiet bitwise version of this. */
/* 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);
#if DECCHECK
decCheckInexact(res, set);
#endif
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);
#if DECCHECK
decCheckInexact(res, set);
#endif
return res;
} /* decNumberAdd */
/* ------------------------------------------------------------------ */
/* decNumberAnd -- AND two Numbers, digitwise */
/* */
/* 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 (used for result length and error report) */
/* */
/* C must have space for set->digits digits. */
/* */
/* Logical function restrictions apply (see above); a NaN is */
/* returned with Invalid_operation if a restriction is violated. */
/* ------------------------------------------------------------------ */
decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
const Unit *ua, *ub; /* -> operands */
const Unit *msua, *msub; /* -> operand msus */
Unit *uc, *msuc; /* -> result and its msu */
Int msudigs; /* digits in res msu */
#if DECCHECK
if (decCheckOperands(res, lhs, rhs, set)) return res;
#endif
if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
|| rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
decStatus(res, DEC_Invalid_operation, set);
return res;
}
/* operands are valid */
ua=lhs->lsu; /* bottom-up */
ub=rhs->lsu; /* .. */
uc=res->lsu; /* .. */
msua=ua+D2U(lhs->digits)-1; /* -> msu of lhs */
msub=ub+D2U(rhs->digits)-1; /* -> msu of rhs */
msuc=uc+D2U(set->digits)-1; /* -> msu of result */
msudigs=MSUDIGITS(set->digits); /* [faster than remainder] */
for (; uc<=msuc; ua++, ub++, uc++) { /* Unit loop */
Unit a, b; /* extract units */
if (ua>msua) a=0;
else a=*ua;
if (ub>msub) b=0;
else b=*ub;
*uc=0; /* can now write back */
if (a|b) { /* maybe 1 bits to examine */
Int i, j;
*uc=0; /* can now write back */
/* This loop could be unrolled and/or use BIN2BCD tables */
for (i=0; i<DECDPUN; i++) {
if (a&b&1) *uc=*uc+(Unit)powers[i]; /* effect AND */
j=a%10;
a=a/10;
j|=b%10;
b=b/10;
if (j>1) {
decStatus(res, DEC_Invalid_operation, set);
return res;
}
if (uc==msuc && i==msudigs-1) break; /* just did final digit */
} /* each digit */
} /* both OK */
} /* each unit */
/* [here uc-1 is the msu of the result] */
res->digits=decGetDigits(res->lsu, uc-res->lsu);
res->exponent=0; /* integer */
res->bits=0; /* sign=0 */
return res; /* [no status to set] */
} /* decNumberAnd */
/* ------------------------------------------------------------------ */
/* 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);
return res;
} /* decNumberCompare */
/* ------------------------------------------------------------------ */
/* decNumberCompareSignal -- compare, signalling on all NaNs */
/* */
/* 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 * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; /* accumulator */
decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
if (status!=0) decStatus(res, status, set);
return res;
} /* decNumberCompareSignal */
/* ------------------------------------------------------------------ */
/* 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. */
/* ------------------------------------------------------------------ */
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 */
/* ------------------------------------------------------------------ */
/* decNumberCompareTotalMag -- compare, total ordering of magnitudes */
/* */
/* 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. */
/* ------------------------------------------------------------------ */
decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
const decNumber *rhs, decContext *set) {
uInt status=0; /* accumulator */
uInt needbytes; /* for space calculations */
decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
decNumber *allocbufa=NULL; /* -> allocated bufa, iff allocated */
decNumber bufb[D2N(DECBUFFER+1)];
decNumber *allocbufb=NULL; /* -> allocated bufb, iff allocated */
decNumber *a, *b; /* temporary pointers */
#if DECCHECK
if (decCheckOperands(res, lhs, rhs, set)) return res;
#endif
do { /* protect allocated storage */
/* if either is negative, take a copy and absolute */
if (decNumberIsNegative(lhs)) { /* lhs<0 */
a=bufa;
needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
if (needbytes>sizeof(bufa)) { /* need malloc space */
allocbufa=(decNumber *)malloc(needbytes);
if (allocbufa==NULL) { /* hopeless -- abandon */
status|=DEC_Insufficient_storage;
break;}
a=allocbufa; /* use the allocated space */
}
decNumberCopy(a, lhs); /* copy content */
a->bits&=~DECNEG; /* .. and clear the sign */
lhs=a; /* use copy from here on */
}
if (decNumberIsNegative(rhs)) { /* rhs<0 */
b=bufb;
needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
if (needbytes>sizeof(bufb)) { /* need malloc space */
allocbufb=(decNumber *)malloc(needbytes);
if (allocbufb==NULL) { /* hopeless -- abandon */
status|=DEC_Insufficient_storage;
break;}
b=allocbufb; /* use the allocated space */
}
decNumberCopy(b, rhs); /* copy content */
b->bits&=~DECNEG; /* .. and clear the sign */
rhs=b; /* use copy from here on */
}
decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
} while(0); /* end protected */
free(allocbufa); /* drop any storage used */
free(allocbufb); /* .. */
if (status!=0) decStatus(res, status, set);
return res;
} /* decNumberCompareTotalMag */
/* ------------------------------------------------------------------ */
/* 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);
#if DECCHECK
decCheckInexact(res, set);
#endif
return res;
} /* decNumberDivide */