-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
dtoa.cc
2478 lines (2252 loc) · 68.1 KB
/
dtoa.cc
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
/* Copyright (c) 2007, 2021, Oracle and/or its affiliates.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License, version 2.0, as published by the Free Software Foundation.
This library is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the library and your derivative works with the
separately licensed software that they have included with MySQL.
Without limiting anything contained in the foregoing, this file,
which is part of C Driver for MySQL (Connector/C), is also subject to the
Universal FOSS Exception, version 1.0, a copy of which can be found at
http://oss.oracle.com/licenses/universal-foss-exception.
This library 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
Library General Public License, version 2.0, for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301 USA */
/****************************************************************
This file incorporates work covered by the following copyright and
permission notice:
The author of this software is David M. Gay.
Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
Permission to use, copy, modify, and distribute this software for any
purpose without fee is hereby granted, provided that this entire notice
is included in all copies of any software which is or includes a copy
or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
***************************************************************/
#include "my_config.h"
#include <assert.h>
#include <algorithm>
#include <limits>
#include "decimal.h"
#include "my_inttypes.h"
#include "my_pointer_arithmetic.h"
#include <errno.h>
#include <float.h>
#include <stdlib.h>
#include <string.h>
#include "m_string.h"
#ifndef EOVERFLOW
#define EOVERFLOW 84
#endif
/**
Appears to suffice to not call malloc() in most cases.
@todo
see if it is possible to get rid of malloc().
this constant is sufficient to avoid malloc() on all inputs I have tried.
*/
#define DTOA_BUFF_SIZE (460 * sizeof(void *))
/* Magic value returned by dtoa() to indicate overflow */
#define DTOA_OVERFLOW 9999
static double my_strtod_int(const char *, const char **, int *, char *, size_t);
static char *dtoa(double, int, int, int *, int *, char **, char *, size_t);
static void dtoa_free(char *, char *, size_t);
/**
@brief
Converts a given floating point number to a zero-terminated string
representation using the 'f' format.
@details
This function is a wrapper around dtoa() to do the same as
sprintf(to, "%-.*f", precision, x), though the conversion is usually more
precise. The only difference is in handling [-,+]infinity and nan values,
in which case we print '0\0' to the output string and indicate an overflow.
@param x the input floating point number.
@param precision the number of digits after the decimal point.
All properties of sprintf() apply:
- if the number of significant digits after the decimal
point is less than precision, the resulting string is
right-padded with zeros
- if the precision is 0, no decimal point appears
- if a decimal point appears, at least one digit appears
before it
@param to pointer to the output buffer. The longest string which
my_fcvt() can return is FLOATING_POINT_BUFFER bytes
(including the terminating '\0').
@param error if not NULL, points to a location where the status of
conversion is stored upon return.
false successful conversion
true the input number is [-,+]infinity or nan.
The output string in this case is always '0'.
@param shorten Whether to minimize the number of significant digits. If
true, write only the minimum number of digits necessary to
reproduce the double value when parsing the string. If
false, zeros are added to the end to reach the precision
limit.
@return number of written characters (excluding terminating '\0')
*/
static size_t my_fcvt_internal(double x, int precision, bool shorten, char *to,
bool *error) {
int decpt, sign, len, i;
char *res, *src, *end, *dst = to;
char buf[DTOA_BUFF_SIZE];
assert(precision >= 0 && precision < DECIMAL_NOT_SPECIFIED && to != nullptr);
res = dtoa(x, 5, precision, &decpt, &sign, &end, buf, sizeof(buf));
if (decpt == DTOA_OVERFLOW) {
dtoa_free(res, buf, sizeof(buf));
*to++ = '0';
*to = '\0';
if (error != nullptr) *error = true;
return 1;
}
src = res;
len = (int)(end - src);
if (sign) *dst++ = '-';
if (decpt <= 0) {
*dst++ = '0';
*dst++ = '.';
for (i = decpt; i < 0; i++) *dst++ = '0';
}
for (i = 1; i <= len; i++) {
*dst++ = *src++;
if (i == decpt && i < len) *dst++ = '.';
}
while (i++ <= decpt) *dst++ = '0';
if (precision > 0 && !shorten) {
if (len <= decpt) *dst++ = '.';
for (i = precision - std::max(0, (len - decpt)); i > 0; i--) *dst++ = '0';
}
*dst = '\0';
if (error != nullptr) *error = false;
dtoa_free(res, buf, sizeof(buf));
return dst - to;
}
/**
@brief
Converts a given floating point number to a zero-terminated string
representation using the 'f' format.
@details
This function is a wrapper around dtoa() to do the same as
sprintf(to, "%-.*f", precision, x), though the conversion is usually more
precise. The only difference is in handling [-,+]infinity and nan values,
in which case we print '0\0' to the output string and indicate an overflow.
@param x the input floating point number.
@param precision the number of digits after the decimal point.
All properties of sprintf() apply:
- if the number of significant digits after the decimal
point is less than precision, the resulting string is
right-padded with zeros
- if the precision is 0, no decimal point appears
- if a decimal point appears, at least one digit appears
before it
@param to pointer to the output buffer. The longest string which
my_fcvt() can return is FLOATING_POINT_BUFFER bytes
(including the terminating '\0').
@param error if not NULL, points to a location where the status of
conversion is stored upon return.
false successful conversion
true the input number is [-,+]infinity or nan.
The output string in this case is always '0'.
@return number of written characters (excluding terminating '\0')
*/
size_t my_fcvt(double x, int precision, char *to, bool *error) {
return my_fcvt_internal(x, precision, false, to, error);
}
/**
@brief
Converts a given floating point number to a zero-terminated string
representation using the 'f' format.
@details
This function is a wrapper around dtoa() to do almost the same as
sprintf(to, "%-.*f", precision, x), though the conversion is usually more
precise. The only difference is in handling [-,+]infinity and nan values,
in which case we print '0\0' to the output string and indicate an overflow.
The string always contains the minimum number of digits necessary to
reproduce the same binary double value if the string is parsed back to a
double value.
@param x the input floating point number.
@param to pointer to the output buffer. The longest string which
my_fcvt() can return is FLOATING_POINT_BUFFER bytes
(including the terminating '\0').
@param error if not NULL, points to a location where the status of
conversion is stored upon return.
false successful conversion
true the input number is [-,+]infinity or nan.
The output string in this case is always '0'.
@return number of written characters (excluding terminating '\0')
*/
size_t my_fcvt_compact(double x, char *to, bool *error) {
return my_fcvt_internal(x, std::numeric_limits<double>::max_digits10, true,
to, error);
}
/**
@brief
Converts a given floating point number to a zero-terminated string
representation with a given field width using the 'e' format
(aka scientific notation) or the 'f' one.
@details
The format is chosen automatically to provide the most number of significant
digits (and thus, precision) with a given field width. In many cases, the
result is similar to that of sprintf(to, "%g", x) with a few notable
differences:
- the conversion is usually more precise than C library functions.
- there is no 'precision' argument. instead, we specify the number of
characters available for conversion (i.e. a field width).
- the result never exceeds the specified field width. If the field is too
short to contain even a rounded decimal representation, my_gcvt()
indicates overflow and truncates the output string to the specified width.
- float-type arguments are handled differently than double ones. For a
float input number (i.e. when the 'type' argument is MY_GCVT_ARG_FLOAT)
we deliberately limit the precision of conversion by FLT_DIG digits to
avoid garbage past the significant digits.
- unlike sprintf(), in cases where the 'e' format is preferred, we don't
zero-pad the exponent to save space for significant digits. The '+' sign
for a positive exponent does not appear for the same reason.
@param x the input floating point number.
@param type is either MY_GCVT_ARG_FLOAT or MY_GCVT_ARG_DOUBLE.
Specifies the type of the input number (see notes above).
@param width field width in characters. The minimal field width to
hold any number representation (albeit rounded) is 7
characters ("-Ne-NNN").
@param to pointer to the output buffer. The result is always
zero-terminated, and the longest returned string is thus
'width + 1' bytes.
@param error if not NULL, points to a location where the status of
conversion is stored upon return.
false successful conversion
true the input number is [-,+]infinity or nan.
The output string in this case is always '0'.
@return number of written characters (excluding terminating '\0')
@todo
Check if it is possible and makes sense to do our own rounding on top of
dtoa() instead of calling dtoa() twice in (rare) cases when the resulting
string representation does not fit in the specified field width and we want
to re-round the input number with fewer significant digits. Examples:
my_gcvt(-9e-3, ..., 4, ...);
my_gcvt(-9e-3, ..., 2, ...);
my_gcvt(1.87e-3, ..., 4, ...);
my_gcvt(55, ..., 1, ...);
We do our best to minimize such cases by:
- passing to dtoa() the field width as the number of significant digits
- removing the sign of the number early (and decreasing the width before
passing it to dtoa())
- choosing the proper format to preserve the most number of significant
digits.
*/
size_t my_gcvt(double x, my_gcvt_arg_type type, int width, char *to,
bool *error) {
int decpt, sign, len, exp_len;
char *res, *src, *end, *dst = to, *dend = dst + width;
char buf[DTOA_BUFF_SIZE];
bool have_space, force_e_format;
assert(width > 0 && to != nullptr);
/* We want to remove '-' from equations early */
if (x < 0.) width--;
res =
dtoa(x, 4, type == MY_GCVT_ARG_DOUBLE ? width : std::min(width, FLT_DIG),
&decpt, &sign, &end, buf, sizeof(buf));
if (decpt == DTOA_OVERFLOW) {
dtoa_free(res, buf, sizeof(buf));
*to++ = '0';
*to = '\0';
if (error != nullptr) *error = true;
return 1;
}
if (error != nullptr) *error = false;
src = res;
len = (int)(end - res);
/*
Number of digits in the exponent from the 'e' conversion.
The sign of the exponent is taken into account separetely, we don't need
to count it here.
*/
exp_len = 1 + (decpt >= 101 || decpt <= -99) + (decpt >= 11 || decpt <= -9);
/*
Do we have enough space for all digits in the 'f' format?
Let 'len' be the number of significant digits returned by dtoa,
and F be the length of the resulting decimal representation.
Consider the following cases:
1. decpt <= 0, i.e. we have "0.NNN" => F = len - decpt + 2
2. 0 < decpt < len, i.e. we have "NNN.NNN" => F = len + 1
3. len <= decpt, i.e. we have "NNN00" => F = decpt
*/
have_space =
(decpt <= 0 ? len - decpt + 2
: decpt > 0 && decpt < len ? len + 1 : decpt) <= width;
/*
The following is true when no significant digits can be placed with the
specified field width using the 'f' format, and the 'e' format
will not be truncated.
*/
force_e_format = (decpt <= 0 && width <= 2 - decpt && width >= 3 + exp_len);
/*
Assume that we don't have enough space to place all significant digits in
the 'f' format. We have to choose between the 'e' format and the 'f' one
to keep as many significant digits as possible.
Let E and F be the lengths of decimal representaion in the 'e' and 'f'
formats, respectively. We want to use the 'f' format if, and only if F <= E.
Consider the following cases:
1. decpt <= 0.
F = len - decpt + 2 (see above)
E = len + (len > 1) + 1 + 1 (decpt <= -99) + (decpt <= -9) + 1
("N.NNe-MMM")
(F <= E) <=> (len == 1 && decpt >= -1) || (len > 1 && decpt >= -2)
We also need to ensure that if the 'f' format is chosen,
the field width allows us to place at least one significant digit
(i.e. width > 2 - decpt). If not, we prefer the 'e' format.
2. 0 < decpt < len
F = len + 1 (see above)
E = len + 1 + 1 + ... ("N.NNeMMM")
F is always less than E.
3. len <= decpt <= width
In this case we have enough space to represent the number in the 'f'
format, so we prefer it with some exceptions.
4. width < decpt
The number cannot be represented in the 'f' format at all, always use
the 'e' 'one.
*/
if ((have_space ||
/*
Not enough space, let's see if the 'f' format provides the most number
of significant digits.
*/
((decpt <= width &&
(decpt >= -1 || (decpt == -2 && (len > 1 || !force_e_format)))) &&
!force_e_format)) &&
/*
Use the 'e' format in some cases even if we have enough space for the
'f' one. See comment for MAX_DECPT_FOR_F_FORMAT.
*/
(!have_space || (decpt >= -MAX_DECPT_FOR_F_FORMAT + 1 &&
(decpt <= MAX_DECPT_FOR_F_FORMAT || len > decpt)))) {
/* 'f' format */
int i;
width -= (decpt < len) + (decpt <= 0 ? 1 - decpt : 0);
/* Do we have to truncate any digits? */
if (width < len) {
if (width < decpt) {
if (error != nullptr) *error = true;
width = decpt;
}
/*
We want to truncate (len - width) least significant digits after the
decimal point. For this we are calling dtoa with mode=5, passing the
number of significant digits = (len-decpt) - (len-width) = width-decpt
*/
dtoa_free(res, buf, sizeof(buf));
res = dtoa(x, 5, width - decpt, &decpt, &sign, &end, buf, sizeof(buf));
src = res;
len = (int)(end - res);
}
if (len == 0) {
/* Underflow. Just print '0' and exit */
*dst++ = '0';
goto end;
}
/*
At this point we are sure we have enough space to put all digits
returned by dtoa
*/
if (sign && dst < dend) *dst++ = '-';
if (decpt <= 0) {
if (dst < dend) *dst++ = '0';
if (len > 0 && dst < dend) *dst++ = '.';
for (; decpt < 0 && dst < dend; decpt++) *dst++ = '0';
}
for (i = 1; i <= len && dst < dend; i++) {
*dst++ = *src++;
if (i == decpt && i < len && dst < dend) *dst++ = '.';
}
while (i++ <= decpt && dst < dend) *dst++ = '0';
} else {
/* 'e' format */
int decpt_sign = 0;
if (--decpt < 0) {
decpt = -decpt;
width--;
decpt_sign = 1;
}
width -= 1 + exp_len; /* eNNN */
if (len > 1) width--;
if (width <= 0) {
/* Overflow */
if (error != nullptr) *error = true;
width = 0;
}
/* Do we have to truncate any digits? */
if (width < len) {
/* Yes, re-convert with a smaller width */
dtoa_free(res, buf, sizeof(buf));
res = dtoa(x, 4, width, &decpt, &sign, &end, buf, sizeof(buf));
src = res;
len = (int)(end - res);
if (--decpt < 0) decpt = -decpt;
}
/*
At this point we are sure we have enough space to put all digits
returned by dtoa
*/
if (sign && dst < dend) *dst++ = '-';
if (dst < dend) *dst++ = *src++;
if (len > 1 && dst < dend) {
*dst++ = '.';
while (src < end && dst < dend) *dst++ = *src++;
}
if (dst < dend) *dst++ = 'e';
if (decpt_sign && dst < dend) *dst++ = '-';
if (decpt >= 100 && dst < dend) {
*dst++ = decpt / 100 + '0';
decpt %= 100;
if (dst < dend) *dst++ = decpt / 10 + '0';
} else if (decpt >= 10 && dst < dend)
*dst++ = decpt / 10 + '0';
if (dst < dend) *dst++ = decpt % 10 + '0';
}
end:
dtoa_free(res, buf, sizeof(buf));
*dst = '\0';
return dst - to;
}
/**
@brief
Converts string to double (string does not have to be zero-terminated)
@details
This is a wrapper around dtoa's version of strtod().
@param str input string
@param end address of a pointer to the first character after the input
string. Upon return the pointer is set to point to the first
rejected character.
@param error Upon return is set to EOVERFLOW in case of underflow or
overflow.
@return The resulting double value. In case of underflow, 0.0 is
returned. In case overflow, signed DBL_MAX is returned.
*/
double my_strtod(const char *str, const char **end, int *error) {
char buf[DTOA_BUFF_SIZE];
double res;
assert(end != nullptr &&
((str != nullptr && *end != nullptr) ||
(str == nullptr && *end == nullptr)) &&
error != nullptr);
res = my_strtod_int(str, end, error, buf, sizeof(buf));
return (*error == 0) ? res : (res < 0 ? -DBL_MAX : DBL_MAX);
}
/****************************************************************
*
* The author of this software is David M. Gay.
*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose without fee is hereby granted, provided that this entire notice
* is included in all copies of any software which is or includes a copy
* or modification of this software and in all copies of the supporting
* documentation for such software.
*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
* REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
* OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
*
***************************************************************/
/* Please send bug reports to David M. Gay (dmg at acm dot org,
* with " at " changed at "@" and " dot " changed to "."). */
/*
Original copy of the software is located at http://www.netlib.org/fp/dtoa.c
It was adjusted to serve MySQL server needs:
* strtod() was modified to not expect a zero-terminated string.
It now honors 'se' (end of string) argument as the input parameter,
not just as the output one.
* in dtoa(), in case of overflow/underflow/NaN result string now contains "0";
decpt is set to DTOA_OVERFLOW to indicate overflow.
* support for VAX, IBM mainframe and 16-bit hardware removed
* we always assume that 64-bit integer type is available
* support for Kernigan-Ritchie style headers (pre-ANSI compilers)
removed
* all gcc warnings ironed out
* we always assume multithreaded environment, so we had to change
memory allocation procedures to use stack in most cases;
malloc is used as the last resort.
* pow5mult rewritten to use pre-calculated pow5 list instead of
the one generated on the fly.
*/
/*
On a machine with IEEE extended-precision registers, it is
necessary to specify double-precision (53-bit) rounding precision
before invoking strtod or dtoa. If the machine uses (the equivalent
of) Intel 80x87 arithmetic, the call
_control87(PC_53, MCW_PC);
does this with many compilers. Whether this or another call is
appropriate depends on the compiler; for this to work, it may be
necessary to #include "float.h" or another system-dependent header
file.
*/
/*
#define Honor_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
and dtoa should round accordingly.
#define Check_FLT_ROUNDS if FLT_ROUNDS can assume the values 2 or 3
and Honor_FLT_ROUNDS is not #defined.
TODO: check if we can get rid of the above two
*/
typedef int32 Long;
typedef uint32 ULong;
typedef int64 LLong;
typedef uint64 ULLong;
typedef union {
double d;
ULong L[2];
} U;
#if defined(WORDS_BIGENDIAN)
#define word0(x) (x)->L[0]
#define word1(x) (x)->L[1]
#else
#define word0(x) (x)->L[1]
#define word1(x) (x)->L[0]
#endif
#define dval(x) (x)->d
/* #define P DBL_MANT_DIG */
/* Ten_pmax= floor(P*log(2)/log(5)) */
/* Bletch= (highest power of 2 < DBL_MAX_10_EXP) / 16 */
/* Quick_max= floor((P-1)*log(FLT_RADIX)/log(10) - 1) */
/* Int_max= floor(P*log(FLT_RADIX)/log(10) - 1) */
#define Exp_shift 20
#define Exp_shift1 20
#define Exp_msk1 0x100000
#define Exp_mask 0x7ff00000
#define P 53
#define Bias 1023
#define Emin (-1022)
#define Exp_1 0x3ff00000
#define Exp_11 0x3ff00000
#define Ebits 11
#define Frac_mask 0xfffff
#define Frac_mask1 0xfffff
#define Ten_pmax 22
#define Bletch 0x10
#define Bndry_mask 0xfffff
#define Bndry_mask1 0xfffff
#define LSB 1
#define Sign_bit 0x80000000
#define Log2P 1
#define Tiny1 1
#define Quick_max 14
#define Int_max 14
#ifndef Flt_Rounds
#ifdef FLT_ROUNDS
#define Flt_Rounds FLT_ROUNDS
#else
#define Flt_Rounds 1
#endif
#endif /*Flt_Rounds*/
#ifdef Honor_FLT_ROUNDS
#define Rounding rounding
#undef Check_FLT_ROUNDS
#define Check_FLT_ROUNDS
#endif
#define rounded_product(a, b) a *= b
#define rounded_quotient(a, b) a /= b
#define Big0 (Frac_mask1 | Exp_msk1 * (DBL_MAX_EXP + Bias - 1))
#define Big1 0xffffffff
#define FFFFFFFF 0xffffffffUL
/* This is tested to be enough for dtoa */
#define Kmax 15
#define Bcopy(x, y) \
memcpy((char *)&x->sign, (char *)&y->sign, \
2 * sizeof(int) + y->wds * sizeof(ULong))
/* Arbitrary-length integer */
typedef struct Bigint {
union {
ULong *x; /* points right after this Bigint object */
struct Bigint *next; /* to maintain free lists */
} p;
int k; /* 2^k = maxwds */
int maxwds; /* maximum length in 32-bit words */
int sign; /* not zero if number is negative */
int wds; /* current length in 32-bit words */
} Bigint;
/* A simple stack-memory based allocator for Bigints */
typedef struct Stack_alloc {
char *begin;
char *free;
char *end;
/*
Having list of free blocks lets us reduce maximum required amount
of memory from ~4000 bytes to < 1680 (tested on x86).
*/
Bigint *freelist[Kmax + 1];
} Stack_alloc;
/*
Try to allocate object on stack, and resort to malloc if all
stack memory is used. Ensure allocated objects to be aligned by the pointer
size in order to not break the alignment rules when storing a pointer to a
Bigint.
*/
static Bigint *Balloc(int k, Stack_alloc *alloc) {
Bigint *rv;
assert(k <= Kmax);
if (k <= Kmax && alloc->freelist[k]) {
rv = alloc->freelist[k];
alloc->freelist[k] = rv->p.next;
} else {
int x, len;
x = 1 << k;
len = MY_ALIGN(sizeof(Bigint) + x * sizeof(ULong), SIZEOF_CHARP);
if (alloc->free + len <= alloc->end) {
rv = (Bigint *)alloc->free;
alloc->free += len;
} else
rv = (Bigint *)malloc(len);
rv->k = k;
rv->maxwds = x;
}
rv->sign = rv->wds = 0;
rv->p.x = (ULong *)(rv + 1);
return rv;
}
/*
If object was allocated on stack, try putting it to the free
list. Otherwise call free().
*/
static void Bfree(Bigint *v, Stack_alloc *alloc) {
char *gptr = (char *)v; /* generic pointer */
if (gptr < alloc->begin || gptr >= alloc->end)
free(gptr);
else if (v->k <= Kmax) {
/*
Maintain free lists only for stack objects: this way we don't
have to bother with freeing lists in the end of dtoa;
heap should not be used normally anyway.
*/
v->p.next = alloc->freelist[v->k];
alloc->freelist[v->k] = v;
}
}
/*
This is to place return value of dtoa in: tries to use stack
as well, but passes by free lists management and just aligns len by
the pointer size in order to not break the alignment rules when storing a
pointer to a Bigint.
*/
static char *dtoa_alloc(int i, Stack_alloc *alloc) {
char *rv;
int aligned_size = MY_ALIGN(i, SIZEOF_CHARP);
if (alloc->free + aligned_size <= alloc->end) {
rv = alloc->free;
alloc->free += aligned_size;
} else
rv = static_cast<char *>(malloc(i));
return rv;
}
/*
dtoa_free() must be used to free values s returned by dtoa()
This is the counterpart of dtoa_alloc()
*/
static void dtoa_free(char *gptr, char *buf, size_t buf_size) {
if (gptr < buf || gptr >= buf + buf_size) free(gptr);
}
/* Bigint arithmetic functions */
/* Multiply by m and add a */
static Bigint *multadd(Bigint *b, int m, int a, Stack_alloc *alloc) {
int i, wds;
ULong *x;
ULLong carry, y;
Bigint *b1;
wds = b->wds;
x = b->p.x;
i = 0;
carry = a;
do {
y = *x * (ULLong)m + carry;
carry = y >> 32;
*x++ = (ULong)(y & FFFFFFFF);
} while (++i < wds);
if (carry) {
if (wds >= b->maxwds) {
b1 = Balloc(b->k + 1, alloc);
Bcopy(b1, b);
Bfree(b, alloc);
b = b1;
}
b->p.x[wds++] = (ULong)carry;
b->wds = wds;
}
return b;
}
/**
Converts a string to Bigint.
Now we have nd0 digits, starting at s, followed by a
decimal point, followed by nd-nd0 digits.
Unless nd0 == nd, in which case we have a number of the form:
".xxxxxx" or "xxxxxx."
@param s Input string, already partially parsed by my_strtod_int().
@param nd0 Number of digits before decimal point.
@param nd Total number of digits.
@param y9 Pre-computed value of the first nine digits.
@param alloc Stack allocator for Bigints.
*/
static Bigint *s2b(const char *s, int nd0, int nd, ULong y9,
Stack_alloc *alloc) {
Bigint *b;
int i, k;
Long x, y;
x = (nd + 8) / 9;
for (k = 0, y = 1; x > y; y <<= 1, k++)
;
b = Balloc(k, alloc);
b->p.x[0] = y9;
b->wds = 1;
i = 9;
if (9 < nd0) {
s += 9;
do
b = multadd(b, 10, *s++ - '0', alloc);
while (++i < nd0);
s++; /* skip '.' */
} else
s += 10;
/* now do the fractional part */
for (; i < nd; i++) b = multadd(b, 10, *s++ - '0', alloc);
return b;
}
static int hi0bits(ULong x) {
int k = 0;
if (!(x & 0xffff0000)) {
k = 16;
x <<= 16;
}
if (!(x & 0xff000000)) {
k += 8;
x <<= 8;
}
if (!(x & 0xf0000000)) {
k += 4;
x <<= 4;
}
if (!(x & 0xc0000000)) {
k += 2;
x <<= 2;
}
if (!(x & 0x80000000)) {
k++;
if (!(x & 0x40000000)) return 32;
}
return k;
}
static int lo0bits(ULong *y) {
int k;
ULong x = *y;
if (x & 7) {
if (x & 1) return 0;
if (x & 2) {
*y = x >> 1;
return 1;
}
*y = x >> 2;
return 2;
}
k = 0;
if (!(x & 0xffff)) {
k = 16;
x >>= 16;
}
if (!(x & 0xff)) {
k += 8;
x >>= 8;
}
if (!(x & 0xf)) {
k += 4;
x >>= 4;
}
if (!(x & 0x3)) {
k += 2;
x >>= 2;
}
if (!(x & 1)) {
k++;
x >>= 1;
if (!x) return 32;
}
*y = x;
return k;
}
/* Convert integer to Bigint number */
static Bigint *i2b(int i, Stack_alloc *alloc) {
Bigint *b;
b = Balloc(1, alloc);
b->p.x[0] = i;
b->wds = 1;
return b;
}
/* Multiply two Bigint numbers */
static Bigint *mult(Bigint *a, Bigint *b, Stack_alloc *alloc) {
Bigint *c;
int k, wa, wb, wc;
ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0;
ULong y;
ULLong carry, z;
if (a->wds < b->wds) {
c = a;
a = b;
b = c;
}
k = a->k;
wa = a->wds;
wb = b->wds;
wc = wa + wb;
if (wc > a->maxwds) k++;
c = Balloc(k, alloc);
for (x = c->p.x, xa = x + wc; x < xa; x++) *x = 0;
xa = a->p.x;
xae = xa + wa;
xb = b->p.x;
xbe = xb + wb;
xc0 = c->p.x;
for (; xb < xbe; xc0++) {
if ((y = *xb++)) {
x = xa;
xc = xc0;
carry = 0;
do {
z = *x++ * (ULLong)y + *xc + carry;
carry = z >> 32;
*xc++ = (ULong)(z & FFFFFFFF);
} while (x < xae);
*xc = (ULong)carry;
}
}
for (xc0 = c->p.x, xc = xc0 + wc; wc > 0 && !*--xc; --wc)
;
c->wds = wc;
return c;
}
/*
Precalculated array of powers of 5: tested to be enough for
vasting majority of dtoa_r cases.
*/
static ULong powers5[] = {
625UL,
390625UL,
2264035265UL, 35UL,
2242703233UL, 762134875UL, 1262UL,
3211403009UL, 1849224548UL, 3668416493UL, 3913284084UL, 1593091UL,
781532673UL, 64985353UL, 253049085UL, 594863151UL, 3553621484UL,
3288652808UL, 3167596762UL, 2788392729UL, 3911132675UL, 590UL,
2553183233UL, 3201533787UL, 3638140786UL, 303378311UL, 1809731782UL,
3477761648UL, 3583367183UL, 649228654UL, 2915460784UL, 487929380UL,
1011012442UL, 1677677582UL, 3428152256UL, 1710878487UL, 1438394610UL,
2161952759UL, 4100910556UL, 1608314830UL, 349175UL};
static Bigint p5_a[] = {
/* { x } - k - maxwds - sign - wds */
{{powers5}, 1, 1, 0, 1}, {{powers5 + 1}, 1, 1, 0, 1},
{{powers5 + 2}, 1, 2, 0, 2}, {{powers5 + 4}, 2, 3, 0, 3},
{{powers5 + 7}, 3, 5, 0, 5}, {{powers5 + 12}, 4, 10, 0, 10},
{{powers5 + 22}, 5, 19, 0, 19}};
#define P5A_MAX (sizeof(p5_a) / sizeof(*p5_a) - 1)
static Bigint *pow5mult(Bigint *b, int k, Stack_alloc *alloc) {