3 * Copyright (c) 2001, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * "That only makes eleven (plus one mislaid) and not fourteen, unless
12 * wizards count differently to other people."
16 #define PERL_IN_NUMERIC_C
20 Perl_cast_ulong(pTHX_ NV f)
23 return f < I32_MIN ? (U32) I32_MIN : (U32)(I32) f;
26 if (f < U32_MAX_P1_HALF)
29 return ((U32) f) | (1 + U32_MAX >> 1);
34 return f > 0 ? U32_MAX : 0 /* NaN */;
38 Perl_cast_i32(pTHX_ NV f)
41 return f < I32_MIN ? I32_MIN : (I32) f;
44 if (f < U32_MAX_P1_HALF)
47 return (I32)(((U32) f) | (1 + U32_MAX >> 1));
52 return f > 0 ? (I32)U32_MAX : 0 /* NaN */;
56 Perl_cast_iv(pTHX_ NV f)
59 return f < IV_MIN ? IV_MIN : (IV) f;
62 /* For future flexibility allowing for sizeof(UV) >= sizeof(IV) */
63 if (f < UV_MAX_P1_HALF)
66 return (IV)(((UV) f) | (1 + UV_MAX >> 1));
71 return f > 0 ? (IV)UV_MAX : 0 /* NaN */;
75 Perl_cast_uv(pTHX_ NV f)
78 return f < IV_MIN ? (UV) IV_MIN : (UV)(IV) f;
81 if (f < UV_MAX_P1_HALF)
84 return ((UV) f) | (1 + UV_MAX >> 1);
89 return f > 0 ? UV_MAX : 0 /* NaN */;
92 #if defined(HUGE_VAL) || (defined(USE_LONG_DOUBLE) && defined(HUGE_VALL))
94 * This hack is to force load of "huge" support from libm.a
95 * So it is in perl for (say) POSIX to use.
96 * Needed for SunOS with Sun's 'acc' for example.
101 # if defined(USE_LONG_DOUBLE) && defined(HUGE_VALL)
111 converts a string representing a binary number to numeric form.
113 On entry I<start> and I<*len> give the string to scan, I<*flags> gives
114 conversion flags, and I<result> should be NULL or a pointer to an NV.
115 The scan stops at the end of the string, or the first invalid character.
116 On return I<*len> is set to the length scanned string, and I<*flags> gives
119 If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
120 and nothing is written to I<*result>. If the value is > UV_MAX C<grok_bin>
121 returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
122 and writes the value to I<*result> (or the value is discarded if I<result>
125 The hex number may optinally be prefixed with "0b" or "b" unless
126 C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
127 C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the binary
128 number may use '_' characters to separate digits.
134 Perl_grok_bin(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
135 const char *s = start;
140 const UV max_div_2 = UV_MAX / 2;
141 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
142 bool overflowed = FALSE;
144 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
145 /* strip off leading b or 0b.
146 for compatibility silently suffer "b" and "0b" as valid binary
153 else if (len >= 2 && s[0] == '0' && s[1] == 'b') {
160 for (; len-- && *s; s++) {
162 if (bit == '0' || bit == '1') {
163 /* Write it in this wonky order with a goto to attempt to get the
164 compiler to make the common case integer-only loop pretty tight.
165 With gcc seems to be much straighter code than old scan_bin. */
168 if (value <= max_div_2) {
169 value = (value << 1) | (bit - '0');
172 /* Bah. We're just overflowed. */
173 if (ckWARN_d(WARN_OVERFLOW))
174 Perl_warner(aTHX_ WARN_OVERFLOW,
175 "Integer overflow in binary number");
177 value_nv = (NV) value;
180 /* If an NV has not enough bits in its mantissa to
181 * represent an UV this summing of small low-order numbers
182 * is a waste of time (because the NV cannot preserve
183 * the low-order bits anyway): we could just remember when
184 * did we overflow and in the end just multiply value_nv by the
186 value_nv += (NV)(bit - '0');
189 if (bit == '_' && len && allow_underscores && (bit = s[1])
190 && (bit == '0' || bit == '1'))
196 if (ckWARN(WARN_DIGIT))
197 Perl_warner(aTHX_ WARN_DIGIT,
198 "Illegal binary digit '%c' ignored", *s);
202 if ( ( overflowed && value_nv > 4294967295.0)
204 || (!overflowed && value > 0xffffffff )
207 if (ckWARN(WARN_PORTABLE))
208 Perl_warner(aTHX_ WARN_PORTABLE,
209 "Binary number > 0b11111111111111111111111111111111 non-portable");
216 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
225 converts a string representing a hex number to numeric form.
227 On entry I<start> and I<*len> give the string to scan, I<*flags> gives
228 conversion flags, and I<result> should be NULL or a pointer to an NV.
229 The scan stops at the end of the string, or the first non-hex-digit character.
230 On return I<*len> is set to the length scanned string, and I<*flags> gives
233 If the value is <= UV_MAX it is returned as a UV, the output flags are clear,
234 and nothing is written to I<*result>. If the value is > UV_MAX C<grok_hex>
235 returns UV_MAX, sets C<PERL_SCAN_GREATER_THAN_UV_MAX> in the output flags,
236 and writes the value to I<*result> (or the value is discarded if I<result>
239 The hex number may optinally be prefixed with "0x" or "x" unless
240 C<PERL_SCAN_DISALLOW_PREFIX> is set in I<*flags> on entry. If
241 C<PERL_SCAN_ALLOW_UNDERSCORES> is set in I<*flags> then the hex
242 number may use '_' characters to separate digits.
248 Perl_grok_hex(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
249 const char *s = start;
254 const UV max_div_16 = UV_MAX / 16;
255 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
256 bool overflowed = FALSE;
257 const char *hexdigit;
259 if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) {
260 /* strip off leading x or 0x.
261 for compatibility silently suffer "x" and "0x" as valid hex numbers.
268 else if (len >= 2 && s[0] == '0' && s[1] == 'x') {
275 for (; len-- && *s; s++) {
276 hexdigit = strchr((char *) PL_hexdigit, *s);
278 /* Write it in this wonky order with a goto to attempt to get the
279 compiler to make the common case integer-only loop pretty tight.
280 With gcc seems to be much straighter code than old scan_hex. */
283 if (value <= max_div_16) {
284 value = (value << 4) | ((hexdigit - PL_hexdigit) & 15);
287 /* Bah. We're just overflowed. */
288 if (ckWARN_d(WARN_OVERFLOW))
289 Perl_warner(aTHX_ WARN_OVERFLOW,
290 "Integer overflow in hexadecimal number");
292 value_nv = (NV) value;
295 /* If an NV has not enough bits in its mantissa to
296 * represent an UV this summing of small low-order numbers
297 * is a waste of time (because the NV cannot preserve
298 * the low-order bits anyway): we could just remember when
299 * did we overflow and in the end just multiply value_nv by the
300 * right amount of 16-tuples. */
301 value_nv += (NV)((hexdigit - PL_hexdigit) & 15);
304 if (*s == '_' && len && allow_underscores && s[1]
305 && (hexdigit = strchr((char *) PL_hexdigit, s[1])))
311 if (ckWARN(WARN_DIGIT))
312 Perl_warner(aTHX_ WARN_DIGIT,
313 "Illegal hexadecimal digit '%c' ignored", *s);
317 if ( ( overflowed && value_nv > 4294967295.0)
319 || (!overflowed && value > 0xffffffff )
322 if (ckWARN(WARN_PORTABLE))
323 Perl_warner(aTHX_ WARN_PORTABLE,
324 "Hexadecimal number > 0xffffffff non-portable");
331 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
345 Perl_grok_oct(pTHX_ char *start, STRLEN *len_p, I32 *flags, NV *result) {
346 const char *s = start;
351 const UV max_div_8 = UV_MAX / 8;
352 bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES;
353 bool overflowed = FALSE;
355 for (; len-- && *s; s++) {
356 /* gcc 2.95 optimiser not smart enough to figure that this subtraction
357 out front allows slicker code. */
358 int digit = *s - '0';
359 if (digit >= 0 && digit <= 7) {
360 /* Write it in this wonky order with a goto to attempt to get the
361 compiler to make the common case integer-only loop pretty tight.
365 if (value <= max_div_8) {
366 value = (value << 3) | digit;
369 /* Bah. We're just overflowed. */
370 if (ckWARN_d(WARN_OVERFLOW))
371 Perl_warner(aTHX_ WARN_OVERFLOW,
372 "Integer overflow in octal number");
374 value_nv = (NV) value;
377 /* If an NV has not enough bits in its mantissa to
378 * represent an UV this summing of small low-order numbers
379 * is a waste of time (because the NV cannot preserve
380 * the low-order bits anyway): we could just remember when
381 * did we overflow and in the end just multiply value_nv by the
382 * right amount of 8-tuples. */
383 value_nv += (NV)digit;
386 if (digit == ('_' - '0') && len && allow_underscores
387 && (digit = s[1] - '0') && (digit >= 0 && digit <= 7))
393 /* Allow \octal to work the DWIM way (that is, stop scanning
394 * as soon as non-octal characters are seen, complain only iff
395 * someone seems to want to use the digits eight and nine). */
396 if (digit == 8 || digit == 9) {
397 if (ckWARN(WARN_DIGIT))
398 Perl_warner(aTHX_ WARN_DIGIT,
399 "Illegal octal digit '%c' ignored", *s);
404 if ( ( overflowed && value_nv > 4294967295.0)
406 || (!overflowed && value > 0xffffffff )
409 if (ckWARN(WARN_PORTABLE))
410 Perl_warner(aTHX_ WARN_PORTABLE,
411 "Octal number > 037777777777 non-portable");
418 *flags = PERL_SCAN_GREATER_THAN_UV_MAX;
427 For backwards compatibility. Use C<grok_bin> instead.
431 For backwards compatibility. Use C<grok_hex> instead.
435 For backwards compatibility. Use C<grok_oct> instead.
441 Perl_scan_bin(pTHX_ char *start, STRLEN len, STRLEN *retlen)
444 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
445 UV ruv = grok_bin (start, &len, &flags, &rnv);
448 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
452 Perl_scan_oct(pTHX_ char *start, STRLEN len, STRLEN *retlen)
455 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
456 UV ruv = grok_oct (start, &len, &flags, &rnv);
459 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
463 Perl_scan_hex(pTHX_ char *start, STRLEN len, STRLEN *retlen)
466 I32 flags = *retlen ? PERL_SCAN_ALLOW_UNDERSCORES : 0;
467 UV ruv = grok_hex (start, &len, &flags, &rnv);
470 return (flags & PERL_SCAN_GREATER_THAN_UV_MAX) ? rnv : (NV)ruv;
474 =for apidoc grok_numeric_radix
476 Scan and skip for a numeric decimal separator (radix).
481 Perl_grok_numeric_radix(pTHX_ const char **sp, const char *send)
483 #ifdef USE_LOCALE_NUMERIC
484 if (PL_numeric_radix_sv && IN_LOCALE) {
486 char* radix = SvPV(PL_numeric_radix_sv, len);
487 if (*sp + len <= send && memEQ(*sp, radix, len)) {
492 /* always try "." if numeric radix didn't match because
493 * we may have data from different locales mixed */
495 if (*sp < send && **sp == '.') {
503 =for apidoc grok_number
505 Recognise (or not) a number. The type of the number is returned
506 (0 if unrecognised), otherwise it is a bit-ORed combination of
507 IS_NUMBER_IN_UV, IS_NUMBER_GREATER_THAN_UV_MAX, IS_NUMBER_NOT_INT,
508 IS_NUMBER_NEG, IS_NUMBER_INFINITY, IS_NUMBER_NAN (defined in perl.h).
510 If the value of the number can fit an in UV, it is returned in the *valuep
511 IS_NUMBER_IN_UV will be set to indicate that *valuep is valid, IS_NUMBER_IN_UV
512 will never be set unless *valuep is valid, but *valuep may have been assigned
513 to during processing even though IS_NUMBER_IN_UV is not set on return.
514 If valuep is NULL, IS_NUMBER_IN_UV will be set for the same cases as when
515 valuep is non-NULL, but no actual assignment (or SEGV) will occur.
517 IS_NUMBER_NOT_INT will be set with IS_NUMBER_IN_UV if trailing decimals were
518 seen (in which case *valuep gives the true value truncated to an integer), and
519 IS_NUMBER_NEG if the number is negative (in which case *valuep holds the
520 absolute value). IS_NUMBER_IN_UV is not set if e notation was used or the
521 number is larger than a UV.
526 Perl_grok_number(pTHX_ const char *pv, STRLEN len, UV *valuep)
529 const char *send = pv + len;
530 const UV max_div_10 = UV_MAX / 10;
531 const char max_mod_10 = UV_MAX % 10;
536 while (s < send && isSPACE(*s))
540 } else if (*s == '-') {
542 numtype = IS_NUMBER_NEG;
550 /* next must be digit or the radix separator or beginning of infinity */
552 /* UVs are at least 32 bits, so the first 9 decimal digits cannot
555 /* This construction seems to be more optimiser friendly.
556 (without it gcc does the isDIGIT test and the *s - '0' separately)
557 With it gcc on arm is managing 6 instructions (6 cycles) per digit.
558 In theory the optimiser could deduce how far to unroll the loop
559 before checking for overflow. */
561 int digit = *s - '0';
562 if (digit >= 0 && digit <= 9) {
563 value = value * 10 + digit;
566 if (digit >= 0 && digit <= 9) {
567 value = value * 10 + digit;
570 if (digit >= 0 && digit <= 9) {
571 value = value * 10 + digit;
574 if (digit >= 0 && digit <= 9) {
575 value = value * 10 + digit;
578 if (digit >= 0 && digit <= 9) {
579 value = value * 10 + digit;
582 if (digit >= 0 && digit <= 9) {
583 value = value * 10 + digit;
586 if (digit >= 0 && digit <= 9) {
587 value = value * 10 + digit;
590 if (digit >= 0 && digit <= 9) {
591 value = value * 10 + digit;
593 /* Now got 9 digits, so need to check
594 each time for overflow. */
596 while (digit >= 0 && digit <= 9
597 && (value < max_div_10
598 || (value == max_div_10
599 && digit <= max_mod_10))) {
600 value = value * 10 + digit;
606 if (digit >= 0 && digit <= 9
609 skip the remaining digits, don't
610 worry about setting *valuep. */
613 } while (s < send && isDIGIT(*s));
615 IS_NUMBER_GREATER_THAN_UV_MAX;
635 numtype |= IS_NUMBER_IN_UV;
640 if (GROK_NUMERIC_RADIX(&s, send)) {
641 numtype |= IS_NUMBER_NOT_INT;
642 while (s < send && isDIGIT(*s)) /* optional digits after the radix */
646 else if (GROK_NUMERIC_RADIX(&s, send)) {
647 numtype |= IS_NUMBER_NOT_INT | IS_NUMBER_IN_UV; /* valuep assigned below */
648 /* no digits before the radix means we need digits after it */
649 if (s < send && isDIGIT(*s)) {
652 } while (s < send && isDIGIT(*s));
654 /* integer approximation is valid - it's 0. */
660 } else if (*s == 'I' || *s == 'i') {
661 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
662 s++; if (s == send || (*s != 'F' && *s != 'f')) return 0;
663 s++; if (s < send && (*s == 'I' || *s == 'i')) {
664 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
665 s++; if (s == send || (*s != 'I' && *s != 'i')) return 0;
666 s++; if (s == send || (*s != 'T' && *s != 't')) return 0;
667 s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0;
671 } else if (*s == 'N' || *s == 'n') {
672 /* XXX TODO: There are signaling NaNs and quiet NaNs. */
673 s++; if (s == send || (*s != 'A' && *s != 'a')) return 0;
674 s++; if (s == send || (*s != 'N' && *s != 'n')) return 0;
681 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
682 numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT;
684 numtype &= IS_NUMBER_NEG; /* Keep track of sign */
685 numtype |= IS_NUMBER_NAN | IS_NUMBER_NOT_INT;
686 } else if (s < send) {
687 /* we can have an optional exponent part */
688 if (*s == 'e' || *s == 'E') {
689 /* The only flag we keep is sign. Blow away any "it's UV" */
690 numtype &= IS_NUMBER_NEG;
691 numtype |= IS_NUMBER_NOT_INT;
693 if (s < send && (*s == '-' || *s == '+'))
695 if (s < send && isDIGIT(*s)) {
698 } while (s < send && isDIGIT(*s));
704 while (s < send && isSPACE(*s))
708 if (len == 10 && memEQ(pv, "0 but true", 10)) {
711 return IS_NUMBER_IN_UV;
717 S_mulexp10(NV value, I32 exponent)
726 else if (exponent < 0) {
728 exponent = -exponent;
731 /* On OpenVMS VAX we by default use the D_FLOAT double format,
732 * and that format does not have *easy* capabilities [1] for
733 * overflowing doubles 'silently' as IEEE fp does. We also need
734 * to support G_FLOAT on both VAX and Alpha, and though the exponent
735 * range is much larger than D_FLOAT it still doesn't do silent
736 * overflow. Therefore we need to detect early whether we would
737 * overflow (this is the behaviour of the native string-to-float
738 * conversion routines, and therefore of native applications, too).
740 * [1] Trying to establish a condition handler to trap floating point
741 * exceptions is not a good idea. */
742 #if defined(VMS) && !defined(__IEEE_FP) && defined(NV_MAX_10_EXP)
744 (log10(value) + exponent) >= (NV_MAX_10_EXP))
748 /* In UNICOS and in certain Cray models (such as T90) there is no
749 * IEEE fp, and no way at all from C to catch fp overflows gracefully.
750 * There is something you can do if you are willing to use some
751 * inline assembler: the instruction is called DFI-- but that will
752 * disable *all* floating point interrupts, a little bit too large
753 * a hammer. Therefore we need to catch potential overflows before
755 #if defined(_UNICOS) && defined(NV_MAX_10_EXP)
757 (log10(value) + exponent) >= NV_MAX_10_EXP)
761 for (bit = 1; exponent; bit <<= 1) {
762 if (exponent & bit) {
766 /* Floating point exceptions are supposed to be turned off. */
769 return negative ? value / result : value * result;
773 Perl_my_atof(pTHX_ const char* s)
776 #ifdef USE_LOCALE_NUMERIC
777 if (PL_numeric_local && IN_LOCALE) {
780 /* Scan the number twice; once using locale and once without;
781 * choose the larger result (in absolute value). */
782 Perl_atof2(aTHX_ s, &x);
783 SET_NUMERIC_STANDARD();
784 Perl_atof2(aTHX_ s, &y);
786 if ((y < 0.0 && y < x) || (y > 0.0 && y > x))
790 Perl_atof2(aTHX_ s, &x);
792 Perl_atof2(aTHX_ s, &x);
798 Perl_my_atof2(pTHX_ const char* orig, NV* value)
802 char* s = (char*)orig;
803 char* send = s + strlen(orig) - 1;
808 /* this is arbitrary */
810 /* we want the largest integers we can usefully use */
811 #if defined(HAS_QUAD) && defined(USE_64_BIT_INT)
812 # define PARTSIZE ((int)TYPE_DIGITS(U64)-1)
815 # define PARTSIZE ((int)TYPE_DIGITS(U32)-1)
818 I32 ipart = 0; /* index into part[] */
819 I32 offcount; /* number of digits in least significant part */
821 /* leading whitespace */
834 part[0] = offcount = 0;
836 seendigit = 1; /* get this over with */
838 /* skip leading zeros */
844 while (isDIGIT(*s)) {
845 if (++offcount > PARTSIZE) {
846 if (++ipart < PARTLIM) {
848 offcount = 1; /* ++0 */
851 /* limits of precision reached */
856 while (isDIGIT(*s)) {
860 /* warn of loss of precision? */
864 part[ipart] = part[ipart] * 10 + (*s++ - '0');
868 if (GROK_NUMERIC_RADIX((const char **)&s, send)) {
870 seendigit = 1; /* get this over with */
873 while (isDIGIT(*s)) {
874 if (++offcount > PARTSIZE) {
875 if (++ipart < PARTLIM) {
877 offcount = 1; /* ++0 */
880 /* limits of precision reached */
887 /* warn of loss of precision? */
892 part[ipart] = part[ipart] * 10 + (*s++ - '0');
896 /* combine components of mantissa */
897 for (i = 0; i <= ipart; ++i)
898 result += S_mulexp10((NV)part[ipart - i],
899 i ? offcount + (i - 1) * PARTSIZE : 0);
901 if (seendigit && (*s == 'e' || *s == 'E')) {
902 bool expnegative = 0;
913 exponent = exponent * 10 + (*s++ - '0');
915 exponent = -exponent;
918 /* now apply the exponent */
919 exponent += expextra;
920 result = S_mulexp10(result, exponent);
922 /* now apply the sign */