This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
sv.h: Document SVt_INVLIST fields
[perl5.git] / numeric.c
CommitLineData
98994639
HS
1/* numeric.c
2 *
663f364b 3 * Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
1129b882 4 * 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
98994639
HS
5 *
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8 *
9 */
10
11/*
4ac71550
TC
12 * "That only makes eleven (plus one mislaid) and not fourteen,
13 * unless wizards count differently to other people." --Beorn
14 *
15 * [p.115 of _The Hobbit_: "Queer Lodgings"]
98994639
HS
16 */
17
ccfc67b7
JH
18/*
19=head1 Numeric functions
166f8a29 20
7fefc6c1
KW
21=cut
22
166f8a29
DM
23This file contains all the stuff needed by perl for manipulating numeric
24values, including such things as replacements for the OS's atof() function
25
ccfc67b7
JH
26*/
27
98994639
HS
28#include "EXTERN.h"
29#define PERL_IN_NUMERIC_C
30#include "perl.h"
31
32U32
ddeaf645 33Perl_cast_ulong(NV f)
98994639
HS
34{
35 if (f < 0.0)
36 return f < I32_MIN ? (U32) I32_MIN : (U32)(I32) f;
37 if (f < U32_MAX_P1) {
38#if CASTFLAGS & 2
39 if (f < U32_MAX_P1_HALF)
40 return (U32) f;
41 f -= U32_MAX_P1_HALF;
42 return ((U32) f) | (1 + U32_MAX >> 1);
43#else
44 return (U32) f;
45#endif
46 }
47 return f > 0 ? U32_MAX : 0 /* NaN */;
48}
49
50I32
ddeaf645 51Perl_cast_i32(NV f)
98994639
HS
52{
53 if (f < I32_MAX_P1)
54 return f < I32_MIN ? I32_MIN : (I32) f;
55 if (f < U32_MAX_P1) {
56#if CASTFLAGS & 2
57 if (f < U32_MAX_P1_HALF)
58 return (I32)(U32) f;
59 f -= U32_MAX_P1_HALF;
60 return (I32)(((U32) f) | (1 + U32_MAX >> 1));
61#else
62 return (I32)(U32) f;
63#endif
64 }
65 return f > 0 ? (I32)U32_MAX : 0 /* NaN */;
66}
67
68IV
ddeaf645 69Perl_cast_iv(NV f)
98994639
HS
70{
71 if (f < IV_MAX_P1)
72 return f < IV_MIN ? IV_MIN : (IV) f;
73 if (f < UV_MAX_P1) {
74#if CASTFLAGS & 2
75 /* For future flexibility allowing for sizeof(UV) >= sizeof(IV) */
76 if (f < UV_MAX_P1_HALF)
77 return (IV)(UV) f;
78 f -= UV_MAX_P1_HALF;
79 return (IV)(((UV) f) | (1 + UV_MAX >> 1));
80#else
81 return (IV)(UV) f;
82#endif
83 }
84 return f > 0 ? (IV)UV_MAX : 0 /* NaN */;
85}
86
87UV
ddeaf645 88Perl_cast_uv(NV f)
98994639
HS
89{
90 if (f < 0.0)
91 return f < IV_MIN ? (UV) IV_MIN : (UV)(IV) f;
92 if (f < UV_MAX_P1) {
93#if CASTFLAGS & 2
94 if (f < UV_MAX_P1_HALF)
95 return (UV) f;
96 f -= UV_MAX_P1_HALF;
97 return ((UV) f) | (1 + UV_MAX >> 1);
98#else
99 return (UV) f;
100#endif
101 }
102 return f > 0 ? UV_MAX : 0 /* NaN */;
103}
104
53305cf1
NC
105/*
106=for apidoc grok_bin
98994639 107
53305cf1
NC
108converts a string representing a binary number to numeric form.
109
110On entry I<start> and I<*len> give the string to scan, I<*flags> gives
111conversion flags, and I<result> should be NULL or a pointer to an NV.
112The scan stops at the end of the string, or the first invalid character.
7b667b5f
MHM
113Unless C<PERL_SCAN_SILENT_ILLDIGIT> is set in I<*flags>, encountering an
114invalid character will also trigger a warning.
115On return I<*len> is set to the length of the scanned string,
116and I<*flags> gives output flags.
53305cf1 117
7fc63493 118If the value is <= C<UV_MAX> it is returned as a UV, the output flags are clear,
72d33970 119and nothing is written to I<*result>. If the value is > UV_MAX C<grok_bin>
53305cf1
NC
120returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
121and writes the value to I<*result> (or the value is discarded if I<result>
122is NULL).
123
7b667b5f 124The binary number may optionally be prefixed with "0b" or "b" unless
72d33970 125C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
a4c04bdc 126C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the binary
53305cf1
NC
127number may use '_' characters to separate digits.
128
129=cut
02470786
KW
130
131Not documented yet because experimental is C<PERL_SCAN_SILENT_NON_PORTABLE
132which suppresses any message for non-portable numbers that are still valid
133on this platform.
53305cf1
NC
134 */
135
136UV
7918f24d
NC
137Perl_grok_bin(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result)
138{
53305cf1
NC
139 const char *s = start;
140 STRLEN len = *len_p;
141 UV value = 0;
142 NV value_nv = 0;
143
144 const UV max_div_2 = UV_MAX / 2;
f2338a2e 145 const bool allow_underscores = cBOOL(*flags & PERL_SCAN_ALLOW_UNDERSCORES);
53305cf1 146 bool overflowed = FALSE;
7fc63493 147 char bit;
53305cf1 148
7918f24d
NC
149 PERL_ARGS_ASSERT_GROK_BIN;
150
a4c04bdc
NC
151 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
152 /* strip off leading b or 0b.
153 for compatibility silently suffer "b" and "0b" as valid binary
154 numbers. */
155 if (len >= 1) {
a674e8db 156 if (s[0] == 'b' || s[0] == 'B') {
a4c04bdc
NC
157 s++;
158 len--;
159 }
a674e8db 160 else if (len >= 2 && s[0] == '0' && (s[1] == 'b' || s[1] == 'B')) {
a4c04bdc
NC
161 s+=2;
162 len-=2;
163 }
164 }
53305cf1
NC
165 }
166
7fc63493 167 for (; len-- && (bit = *s); s++) {
53305cf1
NC
168 if (bit == '0' || bit == '1') {
169 /* Write it in this wonky order with a goto to attempt to get the
170 compiler to make the common case integer-only loop pretty tight.
171 With gcc seems to be much straighter code than old scan_bin. */
172 redo:
173 if (!overflowed) {
174 if (value <= max_div_2) {
175 value = (value << 1) | (bit - '0');
176 continue;
177 }
178 /* Bah. We're just overflowed. */
dcbac5bb 179 /* diag_listed_as: Integer overflow in %s number */
9b387841
NC
180 Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
181 "Integer overflow in binary number");
53305cf1
NC
182 overflowed = TRUE;
183 value_nv = (NV) value;
184 }
185 value_nv *= 2.0;
98994639 186 /* If an NV has not enough bits in its mantissa to
d1be9408 187 * represent a UV this summing of small low-order numbers
98994639
HS
188 * is a waste of time (because the NV cannot preserve
189 * the low-order bits anyway): we could just remember when
53305cf1 190 * did we overflow and in the end just multiply value_nv by the
98994639 191 * right amount. */
53305cf1
NC
192 value_nv += (NV)(bit - '0');
193 continue;
194 }
195 if (bit == '_' && len && allow_underscores && (bit = s[1])
196 && (bit == '0' || bit == '1'))
98994639
HS
197 {
198 --len;
199 ++s;
53305cf1 200 goto redo;
98994639 201 }
a2a5de95
NC
202 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT))
203 Perl_ck_warner(aTHX_ packWARN(WARN_DIGIT),
204 "Illegal binary digit '%c' ignored", *s);
53305cf1 205 break;
98994639 206 }
53305cf1
NC
207
208 if ( ( overflowed && value_nv > 4294967295.0)
98994639 209#if UVSIZE > 4
02470786
KW
210 || (!overflowed && value > 0xffffffff
211 && ! (*flags & PERL_SCAN_SILENT_NON_PORTABLE))
98994639
HS
212#endif
213 ) {
a2a5de95
NC
214 Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
215 "Binary number > 0b11111111111111111111111111111111 non-portable");
53305cf1
NC
216 }
217 *len_p = s - start;
218 if (!overflowed) {
219 *flags = 0;
220 return value;
98994639 221 }
53305cf1
NC
222 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
223 if (result)
224 *result = value_nv;
225 return UV_MAX;
98994639
HS
226}
227
53305cf1
NC
228/*
229=for apidoc grok_hex
230
231converts a string representing a hex number to numeric form.
232
c2da02fc 233On entry I<start> and I<*len_p> give the string to scan, I<*flags> gives
53305cf1 234conversion flags, and I<result> should be NULL or a pointer to an NV.
7b667b5f
MHM
235The scan stops at the end of the string, or the first invalid character.
236Unless C<PERL_SCAN_SILENT_ILLDIGIT> is set in I<*flags>, encountering an
237invalid character will also trigger a warning.
238On return I<*len> is set to the length of the scanned string,
239and I<*flags> gives output flags.
53305cf1
NC
240
241If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
72d33970 242and nothing is written to I<*result>. If the value is > UV_MAX C<grok_hex>
53305cf1
NC
243returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
244and writes the value to I<*result> (or the value is discarded if I<result>
245is NULL).
246
d1be9408 247The hex number may optionally be prefixed with "0x" or "x" unless
72d33970 248C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
a4c04bdc 249C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the hex
53305cf1
NC
250number may use '_' characters to separate digits.
251
252=cut
02470786
KW
253
254Not documented yet because experimental is C<PERL_SCAN_SILENT_NON_PORTABLE
255which suppresses any message for non-portable numbers that are still valid
256on this platform.
53305cf1
NC
257 */
258
259UV
7918f24d
NC
260Perl_grok_hex(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result)
261{
53305cf1
NC
262 const char *s = start;
263 STRLEN len = *len_p;
264 UV value = 0;
265 NV value_nv = 0;
53305cf1 266 const UV max_div_16 = UV_MAX / 16;
f2338a2e 267 const bool allow_underscores = cBOOL(*flags & PERL_SCAN_ALLOW_UNDERSCORES);
53305cf1 268 bool overflowed = FALSE;
98994639 269
7918f24d
NC
270 PERL_ARGS_ASSERT_GROK_HEX;
271
a4c04bdc
NC
272 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
273 /* strip off leading x or 0x.
274 for compatibility silently suffer "x" and "0x" as valid hex numbers.
275 */
276 if (len >= 1) {
a674e8db 277 if (s[0] == 'x' || s[0] == 'X') {
a4c04bdc
NC
278 s++;
279 len--;
280 }
a674e8db 281 else if (len >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
a4c04bdc
NC
282 s+=2;
283 len-=2;
284 }
285 }
98994639
HS
286 }
287
288 for (; len-- && *s; s++) {
626ef089 289 if (isXDIGIT(*s)) {
53305cf1
NC
290 /* Write it in this wonky order with a goto to attempt to get the
291 compiler to make the common case integer-only loop pretty tight.
292 With gcc seems to be much straighter code than old scan_hex. */
293 redo:
294 if (!overflowed) {
295 if (value <= max_div_16) {
626ef089 296 value = (value << 4) | XDIGIT_VALUE(*s);
53305cf1
NC
297 continue;
298 }
299 /* Bah. We're just overflowed. */
dcbac5bb 300 /* diag_listed_as: Integer overflow in %s number */
9b387841
NC
301 Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
302 "Integer overflow in hexadecimal number");
53305cf1
NC
303 overflowed = TRUE;
304 value_nv = (NV) value;
305 }
306 value_nv *= 16.0;
307 /* If an NV has not enough bits in its mantissa to
d1be9408 308 * represent a UV this summing of small low-order numbers
53305cf1
NC
309 * is a waste of time (because the NV cannot preserve
310 * the low-order bits anyway): we could just remember when
311 * did we overflow and in the end just multiply value_nv by the
312 * right amount of 16-tuples. */
626ef089 313 value_nv += (NV) XDIGIT_VALUE(*s);
53305cf1
NC
314 continue;
315 }
316 if (*s == '_' && len && allow_underscores && s[1]
626ef089 317 && isXDIGIT(s[1]))
98994639
HS
318 {
319 --len;
320 ++s;
53305cf1 321 goto redo;
98994639 322 }
a2a5de95
NC
323 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT))
324 Perl_ck_warner(aTHX_ packWARN(WARN_DIGIT),
53305cf1
NC
325 "Illegal hexadecimal digit '%c' ignored", *s);
326 break;
327 }
328
329 if ( ( overflowed && value_nv > 4294967295.0)
330#if UVSIZE > 4
02470786
KW
331 || (!overflowed && value > 0xffffffff
332 && ! (*flags & PERL_SCAN_SILENT_NON_PORTABLE))
53305cf1
NC
333#endif
334 ) {
a2a5de95
NC
335 Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
336 "Hexadecimal number > 0xffffffff non-portable");
53305cf1
NC
337 }
338 *len_p = s - start;
339 if (!overflowed) {
340 *flags = 0;
341 return value;
342 }
343 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
344 if (result)
345 *result = value_nv;
346 return UV_MAX;
347}
348
349/*
350=for apidoc grok_oct
351
7b667b5f
MHM
352converts a string representing an octal number to numeric form.
353
354On entry I<start> and I<*len> give the string to scan, I<*flags> gives
355conversion flags, and I<result> should be NULL or a pointer to an NV.
356The scan stops at the end of the string, or the first invalid character.
357Unless C<PERL_SCAN_SILENT_ILLDIGIT> is set in I<*flags>, encountering an
154bd527 3588 or 9 will also trigger a warning.
7b667b5f
MHM
359On return I<*len> is set to the length of the scanned string,
360and I<*flags> gives output flags.
361
362If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
72d33970 363and nothing is written to I<*result>. If the value is > UV_MAX C<grok_oct>
7b667b5f
MHM
364returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
365and writes the value to I<*result> (or the value is discarded if I<result>
366is NULL).
367
368If C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the octal
369number may use '_' characters to separate digits.
53305cf1
NC
370
371=cut
02470786 372
333ae27c
KW
373Not documented yet because experimental is C<PERL_SCAN_SILENT_NON_PORTABLE>
374which suppresses any message for non-portable numbers, but which are valid
02470786 375on this platform.
53305cf1
NC
376 */
377
378UV
7918f24d
NC
379Perl_grok_oct(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result)
380{
53305cf1
NC
381 const char *s = start;
382 STRLEN len = *len_p;
383 UV value = 0;
384 NV value_nv = 0;
53305cf1 385 const UV max_div_8 = UV_MAX / 8;
f2338a2e 386 const bool allow_underscores = cBOOL(*flags & PERL_SCAN_ALLOW_UNDERSCORES);
53305cf1
NC
387 bool overflowed = FALSE;
388
7918f24d
NC
389 PERL_ARGS_ASSERT_GROK_OCT;
390
53305cf1 391 for (; len-- && *s; s++) {
626ef089 392 if (isOCTAL(*s)) {
53305cf1
NC
393 /* Write it in this wonky order with a goto to attempt to get the
394 compiler to make the common case integer-only loop pretty tight.
395 */
396 redo:
397 if (!overflowed) {
398 if (value <= max_div_8) {
626ef089 399 value = (value << 3) | OCTAL_VALUE(*s);
53305cf1
NC
400 continue;
401 }
402 /* Bah. We're just overflowed. */
dcbac5bb 403 /* diag_listed_as: Integer overflow in %s number */
9b387841
NC
404 Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
405 "Integer overflow in octal number");
53305cf1
NC
406 overflowed = TRUE;
407 value_nv = (NV) value;
408 }
409 value_nv *= 8.0;
98994639 410 /* If an NV has not enough bits in its mantissa to
d1be9408 411 * represent a UV this summing of small low-order numbers
98994639
HS
412 * is a waste of time (because the NV cannot preserve
413 * the low-order bits anyway): we could just remember when
53305cf1
NC
414 * did we overflow and in the end just multiply value_nv by the
415 * right amount of 8-tuples. */
626ef089 416 value_nv += (NV) OCTAL_VALUE(*s);
53305cf1
NC
417 continue;
418 }
626ef089
KW
419 if (*s == '_' && len && allow_underscores && isOCTAL(s[1])) {
420 --len;
421 ++s;
422 goto redo;
423 }
53305cf1 424 /* Allow \octal to work the DWIM way (that is, stop scanning
7b667b5f 425 * as soon as non-octal characters are seen, complain only if
626ef089
KW
426 * someone seems to want to use the digits eight and nine. Since we
427 * know it is not octal, then if isDIGIT, must be an 8 or 9). */
428 if (isDIGIT(*s)) {
a2a5de95
NC
429 if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT))
430 Perl_ck_warner(aTHX_ packWARN(WARN_DIGIT),
431 "Illegal octal digit '%c' ignored", *s);
53305cf1
NC
432 }
433 break;
98994639 434 }
53305cf1
NC
435
436 if ( ( overflowed && value_nv > 4294967295.0)
98994639 437#if UVSIZE > 4
02470786
KW
438 || (!overflowed && value > 0xffffffff
439 && ! (*flags & PERL_SCAN_SILENT_NON_PORTABLE))
98994639
HS
440#endif
441 ) {
a2a5de95
NC
442 Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
443 "Octal number > 037777777777 non-portable");
53305cf1
NC
444 }
445 *len_p = s - start;
446 if (!overflowed) {
447 *flags = 0;
448 return value;
98994639 449 }
53305cf1
NC
450 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
451 if (result)
452 *result = value_nv;
453 return UV_MAX;
454}
455
456/*
457=for apidoc scan_bin
458
72d33970 459For backwards compatibility. Use C<grok_bin> instead.
53305cf1
NC
460
461=for apidoc scan_hex
462
72d33970 463For backwards compatibility. Use C<grok_hex> instead.
53305cf1
NC
464
465=for apidoc scan_oct
466
72d33970 467For backwards compatibility. Use C<grok_oct> instead.
53305cf1
NC
468
469=cut
470 */
471
472NV
73d840c0 473Perl_scan_bin(pTHX_ const char *start, STRLEN len, STRLEN *retlen)
53305cf1
NC
474{
475 NV rnv;
476 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
73d840c0 477 const UV ruv = grok_bin (start, &len, &flags, &rnv);
53305cf1 478
7918f24d
NC
479 PERL_ARGS_ASSERT_SCAN_BIN;
480
53305cf1
NC
481 *retlen = len;
482 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
483}
484
485NV
73d840c0 486Perl_scan_oct(pTHX_ const char *start, STRLEN len, STRLEN *retlen)
53305cf1
NC
487{
488 NV rnv;
489 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
73d840c0 490 const UV ruv = grok_oct (start, &len, &flags, &rnv);
53305cf1 491
7918f24d
NC
492 PERL_ARGS_ASSERT_SCAN_OCT;
493
53305cf1
NC
494 *retlen = len;
495 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
496}
497
498NV
73d840c0 499Perl_scan_hex(pTHX_ const char *start, STRLEN len, STRLEN *retlen)
53305cf1
NC
500{
501 NV rnv;
502 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
73d840c0 503 const UV ruv = grok_hex (start, &len, &flags, &rnv);
53305cf1 504
7918f24d
NC
505 PERL_ARGS_ASSERT_SCAN_HEX;
506
53305cf1
NC
507 *retlen = len;
508 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
98994639
HS
509}
510
511/*
512=for apidoc grok_numeric_radix
513
514Scan and skip for a numeric decimal separator (radix).
515
516=cut
517 */
518bool
519Perl_grok_numeric_radix(pTHX_ const char **sp, const char *send)
520{
521#ifdef USE_LOCALE_NUMERIC
7918f24d
NC
522 PERL_ARGS_ASSERT_GROK_NUMERIC_RADIX;
523
d6ded950 524 if (IN_LC(LC_NUMERIC)) {
21431899
KW
525 DECLARE_STORE_LC_NUMERIC_SET_TO_NEEDED();
526 if (PL_numeric_radix_sv) {
c5a7e38e
KW
527 STRLEN len;
528 const char * const radix = SvPV(PL_numeric_radix_sv, len);
529 if (*sp + len <= send && memEQ(*sp, radix, len)) {
530 *sp += len;
531 RESTORE_LC_NUMERIC();
532 return TRUE;
533 }
21431899
KW
534 }
535 RESTORE_LC_NUMERIC();
98994639
HS
536 }
537 /* always try "." if numeric radix didn't match because
538 * we may have data from different locales mixed */
539#endif
7918f24d
NC
540
541 PERL_ARGS_ASSERT_GROK_NUMERIC_RADIX;
542
98994639
HS
543 if (*sp < send && **sp == '.') {
544 ++*sp;
545 return TRUE;
546 }
547 return FALSE;
548}
549
550/*
3f7602fa 551=for apidoc grok_number_flags
98994639
HS
552
553Recognise (or not) a number. The type of the number is returned
554(0 if unrecognised), otherwise it is a bit-ORed combination of
555IS_NUMBER_IN_UV, IS_NUMBER_GREATER_THAN_UV_MAX, IS_NUMBER_NOT_INT,
aa8b85de 556IS_NUMBER_NEG, IS_NUMBER_INFINITY, IS_NUMBER_NAN (defined in perl.h).
60939fb8 557
cd164854 558If the value of the number can fit in a UV, it is returned in the *valuep
60939fb8
NC
559IS_NUMBER_IN_UV will be set to indicate that *valuep is valid, IS_NUMBER_IN_UV
560will never be set unless *valuep is valid, but *valuep may have been assigned
561to during processing even though IS_NUMBER_IN_UV is not set on return.
562If valuep is NULL, IS_NUMBER_IN_UV will be set for the same cases as when
563valuep is non-NULL, but no actual assignment (or SEGV) will occur.
564
565IS_NUMBER_NOT_INT will be set with IS_NUMBER_IN_UV if trailing decimals were
566seen (in which case *valuep gives the true value truncated to an integer), and
567IS_NUMBER_NEG if the number is negative (in which case *valuep holds the
568absolute value). IS_NUMBER_IN_UV is not set if e notation was used or the
569number is larger than a UV.
98994639 570
3f7602fa
TC
571C<flags> allows only C<PERL_SCAN_TRAILING>, which allows for trailing
572non-numeric text on an otherwise successful I<grok>, setting
573C<IS_NUMBER_TRAILING> on the result.
574
575=for apidoc grok_number
576
577Identical to grok_number_flags() with flags set to zero.
578
98994639
HS
579=cut
580 */
581int
582Perl_grok_number(pTHX_ const char *pv, STRLEN len, UV *valuep)
583{
3f7602fa
TC
584 PERL_ARGS_ASSERT_GROK_NUMBER;
585
586 return grok_number_flags(pv, len, valuep, 0);
587}
588
589int
590Perl_grok_number_flags(pTHX_ const char *pv, STRLEN len, UV *valuep, U32 flags)
591{
60939fb8 592 const char *s = pv;
c4420975 593 const char * const send = pv + len;
60939fb8
NC
594 const UV max_div_10 = UV_MAX / 10;
595 const char max_mod_10 = UV_MAX % 10;
596 int numtype = 0;
597 int sawinf = 0;
aa8b85de 598 int sawnan = 0;
60939fb8 599
3f7602fa 600 PERL_ARGS_ASSERT_GROK_NUMBER_FLAGS;
7918f24d 601
60939fb8
NC
602 while (s < send && isSPACE(*s))
603 s++;
604 if (s == send) {
605 return 0;
606 } else if (*s == '-') {
607 s++;
608 numtype = IS_NUMBER_NEG;
609 }
610 else if (*s == '+')
aa42a541 611 s++;
60939fb8
NC
612
613 if (s == send)
614 return 0;
615
616 /* next must be digit or the radix separator or beginning of infinity */
617 if (isDIGIT(*s)) {
618 /* UVs are at least 32 bits, so the first 9 decimal digits cannot
619 overflow. */
620 UV value = *s - '0';
621 /* This construction seems to be more optimiser friendly.
622 (without it gcc does the isDIGIT test and the *s - '0' separately)
623 With it gcc on arm is managing 6 instructions (6 cycles) per digit.
624 In theory the optimiser could deduce how far to unroll the loop
625 before checking for overflow. */
58bb9ec3
NC
626 if (++s < send) {
627 int digit = *s - '0';
60939fb8
NC
628 if (digit >= 0 && digit <= 9) {
629 value = value * 10 + digit;
58bb9ec3
NC
630 if (++s < send) {
631 digit = *s - '0';
60939fb8
NC
632 if (digit >= 0 && digit <= 9) {
633 value = value * 10 + digit;
58bb9ec3
NC
634 if (++s < send) {
635 digit = *s - '0';
60939fb8
NC
636 if (digit >= 0 && digit <= 9) {
637 value = value * 10 + digit;
58bb9ec3
NC
638 if (++s < send) {
639 digit = *s - '0';
60939fb8
NC
640 if (digit >= 0 && digit <= 9) {
641 value = value * 10 + digit;
58bb9ec3
NC
642 if (++s < send) {
643 digit = *s - '0';
60939fb8
NC
644 if (digit >= 0 && digit <= 9) {
645 value = value * 10 + digit;
58bb9ec3
NC
646 if (++s < send) {
647 digit = *s - '0';
60939fb8
NC
648 if (digit >= 0 && digit <= 9) {
649 value = value * 10 + digit;
58bb9ec3
NC
650 if (++s < send) {
651 digit = *s - '0';
60939fb8
NC
652 if (digit >= 0 && digit <= 9) {
653 value = value * 10 + digit;
58bb9ec3
NC
654 if (++s < send) {
655 digit = *s - '0';
60939fb8
NC
656 if (digit >= 0 && digit <= 9) {
657 value = value * 10 + digit;
58bb9ec3 658 if (++s < send) {
60939fb8
NC
659 /* Now got 9 digits, so need to check
660 each time for overflow. */
58bb9ec3 661 digit = *s - '0';
60939fb8
NC
662 while (digit >= 0 && digit <= 9
663 && (value < max_div_10
664 || (value == max_div_10
665 && digit <= max_mod_10))) {
666 value = value * 10 + digit;
58bb9ec3
NC
667 if (++s < send)
668 digit = *s - '0';
60939fb8
NC
669 else
670 break;
671 }
672 if (digit >= 0 && digit <= 9
51bd16da 673 && (s < send)) {
60939fb8
NC
674 /* value overflowed.
675 skip the remaining digits, don't
676 worry about setting *valuep. */
677 do {
678 s++;
679 } while (s < send && isDIGIT(*s));
680 numtype |=
681 IS_NUMBER_GREATER_THAN_UV_MAX;
682 goto skip_value;
683 }
684 }
685 }
98994639 686 }
60939fb8
NC
687 }
688 }
689 }
690 }
691 }
692 }
693 }
694 }
695 }
696 }
697 }
98994639 698 }
60939fb8 699 }
98994639 700 }
60939fb8
NC
701 numtype |= IS_NUMBER_IN_UV;
702 if (valuep)
703 *valuep = value;
704
705 skip_value:
706 if (GROK_NUMERIC_RADIX(&s, send)) {
707 numtype |= IS_NUMBER_NOT_INT;
708 while (s < send && isDIGIT(*s)) /* optional digits after the radix */
709 s++;
98994639 710 }
60939fb8
NC
711 }
712 else if (GROK_NUMERIC_RADIX(&s, send)) {
713 numtype |= IS_NUMBER_NOT_INT | IS_NUMBER_IN_UV; /* valuep assigned below */
714 /* no digits before the radix means we need digits after it */
715 if (s < send && isDIGIT(*s)) {
716 do {
717 s++;
718 } while (s < send && isDIGIT(*s));
719 if (valuep) {
720 /* integer approximation is valid - it's 0. */
721 *valuep = 0;
722 }
98994639 723 }
60939fb8
NC
724 else
725 return 0;
726 } else if (*s == 'I' || *s == 'i') {
727 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
728 s++; if (s == send || (*s != 'F' && *s != 'f')) return 0;
729 s++; if (s < send && (*s == 'I' || *s == 'i')) {
730 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
731 s++; if (s == send || (*s != 'I' && *s != 'i')) return 0;
732 s++; if (s == send || (*s != 'T' && *s != 't')) return 0;
733 s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0;
734 s++;
98994639 735 }
60939fb8 736 sawinf = 1;
aa8b85de
JH
737 } else if (*s == 'N' || *s == 'n') {
738 /* XXX TODO: There are signaling NaNs and quiet NaNs. */
739 s++; if (s == send || (*s != 'A' && *s != 'a')) return 0;
740 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
741 s++;
742 sawnan = 1;
743 } else
98994639 744 return 0;
60939fb8
NC
745
746 if (sawinf) {
747 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
748 numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT;
aa8b85de
JH
749 } else if (sawnan) {
750 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
751 numtype |= IS_NUMBER_NAN | IS_NUMBER_NOT_INT;
60939fb8
NC
752 } else if (s < send) {
753 /* we can have an optional exponent part */
754 if (*s == 'e' || *s == 'E') {
60939fb8
NC
755 s++;
756 if (s < send && (*s == '-' || *s == '+'))
757 s++;
758 if (s < send && isDIGIT(*s)) {
759 do {
760 s++;
761 } while (s < send && isDIGIT(*s));
762 }
3f7602fa
TC
763 else if (flags & PERL_SCAN_TRAILING)
764 return numtype | IS_NUMBER_TRAILING;
60939fb8 765 else
3f7602fa
TC
766 return 0;
767
768 /* The only flag we keep is sign. Blow away any "it's UV" */
769 numtype &= IS_NUMBER_NEG;
770 numtype |= IS_NUMBER_NOT_INT;
60939fb8
NC
771 }
772 }
773 while (s < send && isSPACE(*s))
774 s++;
775 if (s >= send)
aa8b85de 776 return numtype;
60939fb8
NC
777 if (len == 10 && memEQ(pv, "0 but true", 10)) {
778 if (valuep)
779 *valuep = 0;
780 return IS_NUMBER_IN_UV;
781 }
3f7602fa
TC
782 else if (flags & PERL_SCAN_TRAILING) {
783 return numtype | IS_NUMBER_TRAILING;
784 }
785
60939fb8 786 return 0;
98994639
HS
787}
788
4801ca72 789STATIC NV
98994639
HS
790S_mulexp10(NV value, I32 exponent)
791{
792 NV result = 1.0;
793 NV power = 10.0;
794 bool negative = 0;
795 I32 bit;
796
797 if (exponent == 0)
798 return value;
659c4b96
DM
799 if (value == 0)
800 return (NV)0;
87032ba1 801
24866caa 802 /* On OpenVMS VAX we by default use the D_FLOAT double format,
67597c89 803 * and that format does not have *easy* capabilities [1] for
24866caa
CB
804 * overflowing doubles 'silently' as IEEE fp does. We also need
805 * to support G_FLOAT on both VAX and Alpha, and though the exponent
806 * range is much larger than D_FLOAT it still doesn't do silent
807 * overflow. Therefore we need to detect early whether we would
808 * overflow (this is the behaviour of the native string-to-float
809 * conversion routines, and therefore of native applications, too).
67597c89 810 *
24866caa
CB
811 * [1] Trying to establish a condition handler to trap floating point
812 * exceptions is not a good idea. */
87032ba1
JH
813
814 /* In UNICOS and in certain Cray models (such as T90) there is no
815 * IEEE fp, and no way at all from C to catch fp overflows gracefully.
816 * There is something you can do if you are willing to use some
817 * inline assembler: the instruction is called DFI-- but that will
818 * disable *all* floating point interrupts, a little bit too large
819 * a hammer. Therefore we need to catch potential overflows before
820 * it's too late. */
353813d9 821
85bba25f 822#if ((defined(VMS) && !defined(_IEEE_FP)) || defined(_UNICOS)) && defined(NV_MAX_10_EXP)
353813d9 823 STMT_START {
c4420975 824 const NV exp_v = log10(value);
353813d9
HS
825 if (exponent >= NV_MAX_10_EXP || exponent + exp_v >= NV_MAX_10_EXP)
826 return NV_MAX;
827 if (exponent < 0) {
828 if (-(exponent + exp_v) >= NV_MAX_10_EXP)
829 return 0.0;
830 while (-exponent >= NV_MAX_10_EXP) {
831 /* combination does not overflow, but 10^(-exponent) does */
832 value /= 10;
833 ++exponent;
834 }
835 }
836 } STMT_END;
87032ba1
JH
837#endif
838
353813d9
HS
839 if (exponent < 0) {
840 negative = 1;
841 exponent = -exponent;
b27804d8
DM
842#ifdef NV_MAX_10_EXP
843 /* for something like 1234 x 10^-309, the action of calculating
844 * the intermediate value 10^309 then returning 1234 / (10^309)
845 * will fail, since 10^309 becomes infinity. In this case try to
846 * refactor it as 123 / (10^308) etc.
847 */
848 while (value && exponent > NV_MAX_10_EXP) {
849 exponent--;
850 value /= 10;
851 }
852#endif
353813d9 853 }
98994639
HS
854 for (bit = 1; exponent; bit <<= 1) {
855 if (exponent & bit) {
856 exponent ^= bit;
857 result *= power;
236f0012
CB
858 /* Floating point exceptions are supposed to be turned off,
859 * but if we're obviously done, don't risk another iteration.
860 */
861 if (exponent == 0) break;
98994639
HS
862 }
863 power *= power;
864 }
865 return negative ? value / result : value * result;
866}
867
868NV
869Perl_my_atof(pTHX_ const char* s)
870{
871 NV x = 0.0;
872#ifdef USE_LOCALE_NUMERIC
7918f24d
NC
873 PERL_ARGS_ASSERT_MY_ATOF;
874
a2287a13
KW
875 {
876 DECLARE_STORE_LC_NUMERIC_SET_TO_NEEDED();
d6ded950 877 if (PL_numeric_radix_sv && IN_LC(LC_NUMERIC)) {
e4850248
KW
878 const char *standard = NULL, *local = NULL;
879 bool use_standard_radix;
98994639 880
e4850248
KW
881 /* Look through the string for the first thing that looks like a
882 * decimal point: either the value in the current locale or the
883 * standard fallback of '.'. The one which appears earliest in the
884 * input string is the one that we should have atof look for. Note
885 * that we have to determine this beforehand because on some
886 * systems, Perl_atof2 is just a wrapper around the system's atof.
887 * */
888 standard = strchr(s, '.');
889 local = strstr(s, SvPV_nolen(PL_numeric_radix_sv));
78787052 890
e4850248 891 use_standard_radix = standard && (!local || standard < local);
78787052 892
e4850248
KW
893 if (use_standard_radix)
894 SET_NUMERIC_STANDARD();
78787052 895
e4850248 896 Perl_atof2(s, x);
78787052 897
e4850248
KW
898 if (use_standard_radix)
899 SET_NUMERIC_LOCAL();
900 }
901 else
902 Perl_atof2(s, x);
a2287a13
KW
903 RESTORE_LC_NUMERIC();
904 }
98994639 905#else
a36244b7 906 Perl_atof2(s, x);
98994639
HS
907#endif
908 return x;
909}
910
911char*
912Perl_my_atof2(pTHX_ const char* orig, NV* value)
913{
20f6aaab 914 NV result[3] = {0.0, 0.0, 0.0};
e1ec3a88 915 const char* s = orig;
a36244b7 916#ifdef USE_PERL_ATOF
20f6aaab 917 UV accumulator[2] = {0,0}; /* before/after dp */
a36244b7 918 bool negative = 0;
e1ec3a88 919 const char* send = s + strlen(orig) - 1;
8194bf88 920 bool seen_digit = 0;
20f6aaab
AS
921 I32 exp_adjust[2] = {0,0};
922 I32 exp_acc[2] = {-1, -1};
923 /* the current exponent adjust for the accumulators */
98994639 924 I32 exponent = 0;
8194bf88 925 I32 seen_dp = 0;
20f6aaab
AS
926 I32 digit = 0;
927 I32 old_digit = 0;
8194bf88
DM
928 I32 sig_digits = 0; /* noof significant digits seen so far */
929
7918f24d
NC
930 PERL_ARGS_ASSERT_MY_ATOF2;
931
8194bf88
DM
932/* There is no point in processing more significant digits
933 * than the NV can hold. Note that NV_DIG is a lower-bound value,
934 * while we need an upper-bound value. We add 2 to account for this;
935 * since it will have been conservative on both the first and last digit.
936 * For example a 32-bit mantissa with an exponent of 4 would have
937 * exact values in the set
938 * 4
939 * 8
940 * ..
941 * 17179869172
942 * 17179869176
943 * 17179869180
944 *
945 * where for the purposes of calculating NV_DIG we would have to discount
946 * both the first and last digit, since neither can hold all values from
947 * 0..9; but for calculating the value we must examine those two digits.
948 */
ffa277e5
AS
949#ifdef MAX_SIG_DIG_PLUS
950 /* It is not necessarily the case that adding 2 to NV_DIG gets all the
951 possible digits in a NV, especially if NVs are not IEEE compliant
952 (e.g., long doubles on IRIX) - Allen <allens@cpan.org> */
953# define MAX_SIG_DIGITS (NV_DIG+MAX_SIG_DIG_PLUS)
954#else
955# define MAX_SIG_DIGITS (NV_DIG+2)
956#endif
8194bf88
DM
957
958/* the max number we can accumulate in a UV, and still safely do 10*N+9 */
959#define MAX_ACCUMULATE ( (UV) ((UV_MAX - 9)/10))
98994639 960
96a05aee
HS
961 /* leading whitespace */
962 while (isSPACE(*s))
963 ++s;
964
98994639
HS
965 /* sign */
966 switch (*s) {
967 case '-':
968 negative = 1;
924ba076 969 /* FALLTHROUGH */
98994639
HS
970 case '+':
971 ++s;
972 }
973
2b54f59f
YST
974 /* punt to strtod for NaN/Inf; if no support for it there, tough luck */
975
976#ifdef HAS_STRTOD
977 if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I') {
c042ae3a 978 const char *p = negative ? s - 1 : s;
2b54f59f
YST
979 char *endp;
980 NV rslt;
981 rslt = strtod(p, &endp);
982 if (endp != p) {
983 *value = rslt;
984 return (char *)endp;
985 }
986 }
987#endif
988
8194bf88
DM
989 /* we accumulate digits into an integer; when this becomes too
990 * large, we add the total to NV and start again */
98994639 991
8194bf88
DM
992 while (1) {
993 if (isDIGIT(*s)) {
994 seen_digit = 1;
20f6aaab 995 old_digit = digit;
8194bf88 996 digit = *s++ - '0';
20f6aaab
AS
997 if (seen_dp)
998 exp_adjust[1]++;
98994639 999
8194bf88
DM
1000 /* don't start counting until we see the first significant
1001 * digit, eg the 5 in 0.00005... */
1002 if (!sig_digits && digit == 0)
1003 continue;
1004
1005 if (++sig_digits > MAX_SIG_DIGITS) {
98994639 1006 /* limits of precision reached */
20f6aaab
AS
1007 if (digit > 5) {
1008 ++accumulator[seen_dp];
1009 } else if (digit == 5) {
1010 if (old_digit % 2) { /* round to even - Allen */
1011 ++accumulator[seen_dp];
1012 }
1013 }
1014 if (seen_dp) {
1015 exp_adjust[1]--;
1016 } else {
1017 exp_adjust[0]++;
1018 }
8194bf88 1019 /* skip remaining digits */
98994639 1020 while (isDIGIT(*s)) {
98994639 1021 ++s;
20f6aaab
AS
1022 if (! seen_dp) {
1023 exp_adjust[0]++;
1024 }
98994639
HS
1025 }
1026 /* warn of loss of precision? */
98994639 1027 }
8194bf88 1028 else {
20f6aaab 1029 if (accumulator[seen_dp] > MAX_ACCUMULATE) {
8194bf88 1030 /* add accumulator to result and start again */
20f6aaab
AS
1031 result[seen_dp] = S_mulexp10(result[seen_dp],
1032 exp_acc[seen_dp])
1033 + (NV)accumulator[seen_dp];
1034 accumulator[seen_dp] = 0;
1035 exp_acc[seen_dp] = 0;
98994639 1036 }
20f6aaab
AS
1037 accumulator[seen_dp] = accumulator[seen_dp] * 10 + digit;
1038 ++exp_acc[seen_dp];
98994639 1039 }
8194bf88 1040 }
e1ec3a88 1041 else if (!seen_dp && GROK_NUMERIC_RADIX(&s, send)) {
8194bf88 1042 seen_dp = 1;
20f6aaab 1043 if (sig_digits > MAX_SIG_DIGITS) {
c86f7df5 1044 do {
20f6aaab 1045 ++s;
c86f7df5 1046 } while (isDIGIT(*s));
20f6aaab
AS
1047 break;
1048 }
8194bf88
DM
1049 }
1050 else {
1051 break;
98994639
HS
1052 }
1053 }
1054
20f6aaab
AS
1055 result[0] = S_mulexp10(result[0], exp_acc[0]) + (NV)accumulator[0];
1056 if (seen_dp) {
1057 result[1] = S_mulexp10(result[1], exp_acc[1]) + (NV)accumulator[1];
1058 }
98994639 1059
8194bf88 1060 if (seen_digit && (*s == 'e' || *s == 'E')) {
98994639
HS
1061 bool expnegative = 0;
1062
1063 ++s;
1064 switch (*s) {
1065 case '-':
1066 expnegative = 1;
924ba076 1067 /* FALLTHROUGH */
98994639
HS
1068 case '+':
1069 ++s;
1070 }
1071 while (isDIGIT(*s))
1072 exponent = exponent * 10 + (*s++ - '0');
1073 if (expnegative)
1074 exponent = -exponent;
1075 }
1076
20f6aaab
AS
1077
1078
98994639 1079 /* now apply the exponent */
20f6aaab
AS
1080
1081 if (seen_dp) {
1082 result[2] = S_mulexp10(result[0],exponent+exp_adjust[0])
1083 + S_mulexp10(result[1],exponent-exp_adjust[1]);
1084 } else {
1085 result[2] = S_mulexp10(result[0],exponent+exp_adjust[0]);
1086 }
98994639
HS
1087
1088 /* now apply the sign */
1089 if (negative)
20f6aaab 1090 result[2] = -result[2];
a36244b7 1091#endif /* USE_PERL_ATOF */
20f6aaab 1092 *value = result[2];
73d840c0 1093 return (char *)s;
98994639
HS
1094}
1095
55954f19
JH
1096#if ! defined(HAS_MODFL) && defined(HAS_AINTL) && defined(HAS_COPYSIGNL)
1097long double
1098Perl_my_modfl(long double x, long double *ip)
1099{
1100 *ip = aintl(x);
1101 return (x == *ip ? copysignl(0.0L, x) : x - *ip);
1102}
1103#endif
1104
1105#if ! defined(HAS_FREXPL) && defined(HAS_ILOGBL) && defined(HAS_SCALBNL)
1106long double
1107Perl_my_frexpl(long double x, int *e) {
1108 *e = x == 0.0L ? 0 : ilogbl(x) + 1;
1109 return (scalbnl(x, -*e));
1110}
1111#endif
66610fdd
RGS
1112
1113/*
ed140128
AD
1114=for apidoc Perl_signbit
1115
1116Return a non-zero integer if the sign bit on an NV is set, and 0 if
1117it is not.
1118
1119If Configure detects this system has a signbit() that will work with
1120our NVs, then we just use it via the #define in perl.h. Otherwise,
1121fall back on this implementation. As a first pass, this gets everything
1122right except -0.0. Alas, catching -0.0 is the main use for this function,
1123so this is not too helpful yet. Still, at least we have the scaffolding
1124in place to support other systems, should that prove useful.
1125
1126
1127Configure notes: This function is called 'Perl_signbit' instead of a
1128plain 'signbit' because it is easy to imagine a system having a signbit()
1129function or macro that doesn't happen to work with our particular choice
1130of NVs. We shouldn't just re-#define signbit as Perl_signbit and expect
1131the standard system headers to be happy. Also, this is a no-context
1132function (no pTHX_) because Perl_signbit() is usually re-#defined in
1133perl.h as a simple macro call to the system's signbit().
1134Users should just always call Perl_signbit().
1135
1136=cut
1137*/
1138#if !defined(HAS_SIGNBIT)
1139int
1140Perl_signbit(NV x) {
1141 return (x < 0.0) ? 1 : 0;
1142}
1143#endif
1144
1145/*
66610fdd
RGS
1146 * Local variables:
1147 * c-indentation-style: bsd
1148 * c-basic-offset: 4
14d04a33 1149 * indent-tabs-mode: nil
66610fdd
RGS
1150 * End:
1151 *
14d04a33 1152 * ex: set ts=8 sts=4 sw=4 et:
37442d52 1153 */