cpython/Python/pystrtod.c

1305 lines
40 KiB
C
Raw Normal View History

/* -*- Mode: C; c-file-style: "python" -*- */
#include <Python.h>
#include <locale.h>
/* Case-insensitive string match used for nan and inf detection; t should be
lower-case. Returns 1 for a successful match, 0 otherwise. */
static int
case_insensitive_match(const char *s, const char *t)
{
while(*t && Py_TOLOWER(*s) == *t) {
s++;
t++;
}
return *t ? 0 : 1;
}
/* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or
"infinity", with an optional leading sign of "+" or "-". On success,
return the NaN or Infinity as a double and set *endptr to point just beyond
the successfully parsed portion of the string. On failure, return -1.0 and
set *endptr to point to the start of the string. */
#ifndef PY_NO_SHORT_FLOAT_REPR
double
_Py_parse_inf_or_nan(const char *p, char **endptr)
{
double retval;
const char *s;
int negate = 0;
s = p;
if (*s == '-') {
negate = 1;
s++;
}
else if (*s == '+') {
s++;
}
if (case_insensitive_match(s, "inf")) {
s += 3;
if (case_insensitive_match(s, "inity"))
s += 5;
retval = _Py_dg_infinity(negate);
}
else if (case_insensitive_match(s, "nan")) {
s += 3;
retval = _Py_dg_stdnan(negate);
}
else {
s = p;
retval = -1.0;
}
*endptr = (char *)s;
return retval;
}
#else
double
_Py_parse_inf_or_nan(const char *p, char **endptr)
{
double retval;
const char *s;
int negate = 0;
s = p;
if (*s == '-') {
negate = 1;
s++;
}
else if (*s == '+') {
s++;
}
if (case_insensitive_match(s, "inf")) {
s += 3;
if (case_insensitive_match(s, "inity"))
s += 5;
retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL;
}
#ifdef Py_NAN
else if (case_insensitive_match(s, "nan")) {
s += 3;
retval = negate ? -Py_NAN : Py_NAN;
}
#endif
else {
s = p;
retval = -1.0;
}
*endptr = (char *)s;
return retval;
}
#endif
/**
* _PyOS_ascii_strtod:
* @nptr: the string to convert to a numeric value.
* @endptr: if non-%NULL, it returns the character after
* the last character used in the conversion.
*
* Converts a string to a #gdouble value.
* This function behaves like the standard strtod() function
* does in the C locale. It does this without actually
* changing the current locale, since that would not be
* thread-safe.
*
* This function is typically used when reading configuration
* files or other non-user input that should be locale independent.
* To handle input from the user you should normally use the
* locale-sensitive system strtod() function.
*
* If the correct value would cause overflow, plus or minus %HUGE_VAL
* is returned (according to the sign of the value), and %ERANGE is
* stored in %errno. If the correct value would cause underflow,
* zero is returned and %ERANGE is stored in %errno.
Partially merge trunk into p3yk. The removal of Mac/Tools is confusing svn merge in bad ways, so I'll have to merge that extra-carefully (probably manually.) Merged revisions 46495-46605 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r46495 | tim.peters | 2006-05-28 03:52:38 +0200 (Sun, 28 May 2006) | 2 lines Added missing svn:eol-style property to text files. ........ r46497 | tim.peters | 2006-05-28 12:41:29 +0200 (Sun, 28 May 2006) | 3 lines PyErr_Display(), PyErr_WriteUnraisable(): Coverity found a cut-and-paste bug in both: `className` was referenced before being checked for NULL. ........ r46499 | fredrik.lundh | 2006-05-28 14:06:46 +0200 (Sun, 28 May 2006) | 5 lines needforspeed: added Py_MEMCPY macro (currently tuned for Visual C only), and use it for string copy operations. this gives a 20% speedup on some string benchmarks. ........ r46501 | michael.hudson | 2006-05-28 17:51:40 +0200 (Sun, 28 May 2006) | 26 lines Quality control, meet exceptions.c. Fix a number of problems with the need for speed code: One is doing this sort of thing: Py_DECREF(self->field); self->field = newval; Py_INCREF(self->field); without being very sure that self->field doesn't start with a value that has a __del__, because that almost certainly can lead to segfaults. As self->args is constrained to be an exact tuple we may as well exploit this fact consistently. This leads to quite a lot of simplification (and, hey, probably better performance). Add some error checking in places lacking it. Fix some rather strange indentation in the Unicode code. Delete some trailing whitespace. More to come, I haven't fixed all the reference leaks yet... ........ r46502 | george.yoshida | 2006-05-28 18:39:09 +0200 (Sun, 28 May 2006) | 3 lines Patch #1080727: add "encoding" parameter to doctest.DocFileSuite Contributed by Bjorn Tillenius. ........ r46503 | martin.v.loewis | 2006-05-28 18:57:38 +0200 (Sun, 28 May 2006) | 4 lines Rest of patch #1490384: Commit icon source, remove claim that Erik von Blokland is the author of the installer picture. ........ r46504 | michael.hudson | 2006-05-28 19:40:29 +0200 (Sun, 28 May 2006) | 16 lines Quality control, meet exceptions.c, round two. Make some functions that should have been static static. Fix a bunch of refleaks by fixing the definition of MiddlingExtendsException. Remove all the __new__ implementations apart from BaseException_new. Rewrite most code that needs it to cope with NULL fields (such code could get excercised anyway, the __new__-removal just makes it more likely). This involved editing the code for WindowsError, which I can't test. This fixes all the refleaks in at least the start of a regrtest -R :: run. ........ r46505 | marc-andre.lemburg | 2006-05-28 19:46:58 +0200 (Sun, 28 May 2006) | 10 lines Initial version of systimes - a module to provide platform dependent performance measurements. The module is currently just a proof-of-concept implementation, but will integrated into pybench once it is stable enough. License: pybench license. Author: Marc-Andre Lemburg. ........ r46507 | armin.rigo | 2006-05-28 21:13:17 +0200 (Sun, 28 May 2006) | 15 lines ("Forward-port" of r46506) Remove various dependencies on dictionary order in the standard library tests, and one (clearly an oversight, potentially critical) in the standard library itself - base64.py. Remaining open issues: * test_extcall is an output test, messy to make robust * tarfile.py has a potential bug here, but I'm not familiar enough with this code. Filed in as SF bug #1496501. * urllib2.HTTPPasswordMgr() returns a random result if there is more than one matching root path. I'm asking python-dev for clarification... ........ r46508 | georg.brandl | 2006-05-28 22:11:45 +0200 (Sun, 28 May 2006) | 4 lines The empty string is a valid import path. (fixes #1496539) ........ r46509 | georg.brandl | 2006-05-28 22:23:12 +0200 (Sun, 28 May 2006) | 3 lines Patch #1496206: urllib2 PasswordMgr ./. default ports ........ r46510 | georg.brandl | 2006-05-28 22:57:09 +0200 (Sun, 28 May 2006) | 3 lines Fix refleaks in UnicodeError get and set methods. ........ r46511 | michael.hudson | 2006-05-28 23:19:03 +0200 (Sun, 28 May 2006) | 3 lines use the UnicodeError traversal and clearing functions in UnicodeError subclasses. ........ r46512 | thomas.wouters | 2006-05-28 23:32:12 +0200 (Sun, 28 May 2006) | 4 lines Make last patch valid C89 so Windows compilers can deal with it. ........ r46513 | georg.brandl | 2006-05-28 23:42:54 +0200 (Sun, 28 May 2006) | 3 lines Fix ref-antileak in _struct.c which eventually lead to deallocating None. ........ r46514 | georg.brandl | 2006-05-28 23:57:35 +0200 (Sun, 28 May 2006) | 4 lines Correct None refcount issue in Mac modules. (Are they still used?) ........ r46515 | armin.rigo | 2006-05-29 00:07:08 +0200 (Mon, 29 May 2006) | 3 lines A clearer error message when passing -R to regrtest.py with release builds of Python. ........ r46516 | georg.brandl | 2006-05-29 00:14:04 +0200 (Mon, 29 May 2006) | 3 lines Fix C function calling conventions in _sre module. ........ r46517 | georg.brandl | 2006-05-29 00:34:51 +0200 (Mon, 29 May 2006) | 3 lines Convert audioop over to METH_VARARGS. ........ r46518 | georg.brandl | 2006-05-29 00:38:57 +0200 (Mon, 29 May 2006) | 3 lines METH_NOARGS functions do get called with two args. ........ r46519 | georg.brandl | 2006-05-29 11:46:51 +0200 (Mon, 29 May 2006) | 4 lines Fix refleak in socketmodule. Replace bogus Py_BuildValue calls. Fix refleak in exceptions. ........ r46520 | nick.coghlan | 2006-05-29 14:43:05 +0200 (Mon, 29 May 2006) | 7 lines Apply modified version of Collin Winter's patch #1478788 Renames functional extension module to _functools and adds a Python functools module so that utility functions like update_wrapper can be added easily. ........ r46522 | georg.brandl | 2006-05-29 15:53:16 +0200 (Mon, 29 May 2006) | 3 lines Convert fmmodule to METH_VARARGS. ........ r46523 | georg.brandl | 2006-05-29 16:13:21 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494605. ........ r46524 | georg.brandl | 2006-05-29 16:28:05 +0200 (Mon, 29 May 2006) | 3 lines Handle PyMem_Malloc failure in pystrtod.c. Closes #1494671. ........ r46525 | georg.brandl | 2006-05-29 16:33:55 +0200 (Mon, 29 May 2006) | 3 lines Fix compiler warning. ........ r46526 | georg.brandl | 2006-05-29 16:39:00 +0200 (Mon, 29 May 2006) | 3 lines Fix #1494787 (pyclbr counts whitespace as superclass name) ........ r46527 | bob.ippolito | 2006-05-29 17:47:29 +0200 (Mon, 29 May 2006) | 1 line simplify the struct code a bit (no functional changes) ........ r46528 | armin.rigo | 2006-05-29 19:59:47 +0200 (Mon, 29 May 2006) | 2 lines Silence a warning. ........ r46529 | georg.brandl | 2006-05-29 21:39:45 +0200 (Mon, 29 May 2006) | 3 lines Correct some value converting strangenesses. ........ r46530 | nick.coghlan | 2006-05-29 22:27:44 +0200 (Mon, 29 May 2006) | 1 line When adding a module like functools, it helps to let SVN know about the file. ........ r46531 | georg.brandl | 2006-05-29 22:52:54 +0200 (Mon, 29 May 2006) | 4 lines Patches #1497027 and #972322: try HTTP digest auth first, and watch out for handler name collisions. ........ r46532 | georg.brandl | 2006-05-29 22:57:01 +0200 (Mon, 29 May 2006) | 3 lines Add News entry for last commit. ........ r46533 | georg.brandl | 2006-05-29 23:04:52 +0200 (Mon, 29 May 2006) | 4 lines Make use of METH_O and METH_NOARGS where possible. Use Py_UnpackTuple instead of PyArg_ParseTuple where possible. ........ r46534 | georg.brandl | 2006-05-29 23:58:42 +0200 (Mon, 29 May 2006) | 3 lines Convert more modules to METH_VARARGS. ........ r46535 | georg.brandl | 2006-05-30 00:00:30 +0200 (Tue, 30 May 2006) | 3 lines Whoops. ........ r46536 | fredrik.lundh | 2006-05-30 00:42:07 +0200 (Tue, 30 May 2006) | 4 lines fixed "abc".count("", 100) == -96 error (hopefully, nobody's relying on the current behaviour ;-) ........ r46537 | bob.ippolito | 2006-05-30 00:55:48 +0200 (Tue, 30 May 2006) | 1 line struct: modulo math plus warning on all endian-explicit formats for compatibility with older struct usage (ugly) ........ r46539 | bob.ippolito | 2006-05-30 02:26:01 +0200 (Tue, 30 May 2006) | 1 line Add a length check to aifc to ensure it doesn't write a bogus file ........ r46540 | tim.peters | 2006-05-30 04:25:25 +0200 (Tue, 30 May 2006) | 10 lines deprecated_err(): Stop bizarre warning messages when the tests are run in the order: test_genexps (or any other doctest-based test) test_struct test_doctest The `warnings` module needs an advertised way to save/restore its internal filter list. ........ r46541 | tim.peters | 2006-05-30 04:26:46 +0200 (Tue, 30 May 2006) | 2 lines Whitespace normalization. ........ r46542 | tim.peters | 2006-05-30 04:30:30 +0200 (Tue, 30 May 2006) | 2 lines Set a binary svn:mime-type property on this UTF-8 encoded file. ........ r46543 | neal.norwitz | 2006-05-30 05:18:50 +0200 (Tue, 30 May 2006) | 1 line Simplify further by using AddStringConstant ........ r46544 | tim.peters | 2006-05-30 06:16:25 +0200 (Tue, 30 May 2006) | 6 lines Convert relevant dict internals to Py_ssize_t. I don't have a box with nearly enough RAM, or an OS, that could get close to tickling this, though (requires a dict w/ at least 2**31 entries). ........ r46545 | neal.norwitz | 2006-05-30 06:19:21 +0200 (Tue, 30 May 2006) | 1 line Remove stray | in comment ........ r46546 | neal.norwitz | 2006-05-30 06:25:05 +0200 (Tue, 30 May 2006) | 1 line Use Py_SAFE_DOWNCAST for safety. Fix format strings. Remove 2 more stray | in comment ........ r46547 | neal.norwitz | 2006-05-30 06:43:23 +0200 (Tue, 30 May 2006) | 1 line No DOWNCAST is required since sizeof(Py_ssize_t) >= sizeof(int) and Py_ReprEntr returns an int ........ r46548 | tim.peters | 2006-05-30 07:04:59 +0200 (Tue, 30 May 2006) | 3 lines dict_print(): Explicitly narrow the return value from a (possibly) wider variable. ........ r46549 | tim.peters | 2006-05-30 07:23:59 +0200 (Tue, 30 May 2006) | 5 lines dict_print(): So that Neal & I don't spend the rest of our lives taking turns rewriting code that works ;-), get rid of casting illusions by declaring a new variable with the obvious type. ........ r46550 | georg.brandl | 2006-05-30 09:04:55 +0200 (Tue, 30 May 2006) | 3 lines Restore exception pickle support. #1497319. ........ r46551 | georg.brandl | 2006-05-30 09:13:29 +0200 (Tue, 30 May 2006) | 3 lines Add a test case for exception pickling. args is never NULL. ........ r46552 | neal.norwitz | 2006-05-30 09:21:10 +0200 (Tue, 30 May 2006) | 1 line Don't fail if the (sub)pkgname already exist. ........ r46553 | georg.brandl | 2006-05-30 09:34:45 +0200 (Tue, 30 May 2006) | 3 lines Disallow keyword args for exceptions. ........ r46554 | neal.norwitz | 2006-05-30 09:36:54 +0200 (Tue, 30 May 2006) | 5 lines I'm impatient. I think this will fix a few more problems with the buildbots. I'm not sure this is the best approach, but I can't think of anything better. If this creates problems, feel free to revert, but I think it's safe and should make things a little better. ........ r46555 | georg.brandl | 2006-05-30 10:17:00 +0200 (Tue, 30 May 2006) | 4 lines Do the check for no keyword arguments in __init__ so that subclasses of Exception can be supplied keyword args ........ r46556 | georg.brandl | 2006-05-30 10:47:19 +0200 (Tue, 30 May 2006) | 3 lines Convert test_exceptions to unittest. ........ r46557 | andrew.kuchling | 2006-05-30 14:52:01 +0200 (Tue, 30 May 2006) | 1 line Add SoC name, and reorganize this section a bit ........ r46559 | tim.peters | 2006-05-30 17:53:34 +0200 (Tue, 30 May 2006) | 11 lines PyLong_FromString(): Continued fraction analysis (explained in a new comment) suggests there are almost certainly large input integers in all non-binary input bases for which one Python digit too few is initally allocated to hold the final result. Instead of assert-failing when that happens, allocate more space. Alas, I estimate it would take a few days to find a specific such case, so this isn't backed up by a new test (not to mention that such a case may take hours to run, since conversion time is quadratic in the number of digits, and preliminary attempts suggested that the smallest such inputs contain at least a million digits). ........ r46560 | fredrik.lundh | 2006-05-30 19:11:48 +0200 (Tue, 30 May 2006) | 3 lines changed find/rfind to return -1 for matches outside the source string ........ r46561 | bob.ippolito | 2006-05-30 19:37:54 +0200 (Tue, 30 May 2006) | 1 line Change wrapping terminology to overflow masking ........ r46562 | fredrik.lundh | 2006-05-30 19:39:58 +0200 (Tue, 30 May 2006) | 3 lines changed count to return 0 for slices outside the source string ........ r46568 | tim.peters | 2006-05-31 01:28:02 +0200 (Wed, 31 May 2006) | 2 lines Whitespace normalization. ........ r46569 | brett.cannon | 2006-05-31 04:19:54 +0200 (Wed, 31 May 2006) | 5 lines Clarify wording on default values for strptime(); defaults are used when better values cannot be inferred. Closes bug #1496315. ........ r46572 | neal.norwitz | 2006-05-31 09:43:27 +0200 (Wed, 31 May 2006) | 1 line Calculate smallest properly (it was off by one) and use proper ssize_t types for Win64 ........ r46573 | neal.norwitz | 2006-05-31 10:01:08 +0200 (Wed, 31 May 2006) | 1 line Revert last checkin, it is better to do make distclean ........ r46574 | neal.norwitz | 2006-05-31 11:02:44 +0200 (Wed, 31 May 2006) | 3 lines On 64-bit platforms running test_struct after test_tarfile would fail since the deprecation warning wouldn't be raised. ........ r46575 | thomas.heller | 2006-05-31 13:37:58 +0200 (Wed, 31 May 2006) | 3 lines PyTuple_Pack is not available in Python 2.3, but ctypes must stay compatible with that. ........ r46576 | andrew.kuchling | 2006-05-31 15:18:56 +0200 (Wed, 31 May 2006) | 1 line 'functional' module was renamed to 'functools' ........ r46577 | kristjan.jonsson | 2006-05-31 15:35:41 +0200 (Wed, 31 May 2006) | 1 line Fixup the PCBuild8 project directory. exceptions.c have moved to Objects, and the functionalmodule.c has been replaced with _functoolsmodule.c. Other minor changes to .vcproj files and .sln to fix compilation ........ r46578 | andrew.kuchling | 2006-05-31 16:08:48 +0200 (Wed, 31 May 2006) | 15 lines [Bug #1473048] SimpleXMLRPCServer and DocXMLRPCServer don't look at the path of the HTTP request at all; you can POST or GET from / or /RPC2 or /blahblahblah with the same results. Security scanners that look for /cgi-bin/phf will therefore report lots of vulnerabilities. Fix: add a .rpc_paths attribute to the SimpleXMLRPCServer class, and report a 404 error if the path isn't on the allowed list. Possibly-controversial aspect of this change: the default makes only '/' and '/RPC2' legal. Maybe this will break people's applications (though I doubt it). We could just set the default to an empty tuple, which would exactly match the current behaviour. ........ r46579 | andrew.kuchling | 2006-05-31 16:12:47 +0200 (Wed, 31 May 2006) | 1 line Mention SimpleXMLRPCServer change ........ r46580 | tim.peters | 2006-05-31 16:28:07 +0200 (Wed, 31 May 2006) | 2 lines Trimmed trailing whitespace. ........ r46581 | tim.peters | 2006-05-31 17:33:22 +0200 (Wed, 31 May 2006) | 4 lines _range_error(): Speed and simplify (there's no real need for loops here). Assert that size_t is actually big enough, and that f->size is at least one. Wrap a long line. ........ r46582 | tim.peters | 2006-05-31 17:34:37 +0200 (Wed, 31 May 2006) | 2 lines Repaired error in new comment. ........ r46584 | neal.norwitz | 2006-06-01 07:32:49 +0200 (Thu, 01 Jun 2006) | 4 lines Remove ; at end of macro. There was a compiler recently that warned about extra semi-colons. It may have been the HP C compiler. This file will trigger a bunch of those warnings now. ........ r46585 | georg.brandl | 2006-06-01 08:39:19 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly unpickle 2.4 exceptions via __setstate__ (patch #1498571) ........ r46586 | georg.brandl | 2006-06-01 10:27:32 +0200 (Thu, 01 Jun 2006) | 3 lines Correctly allocate complex types with tp_alloc. (bug #1498638) ........ r46587 | georg.brandl | 2006-06-01 14:30:46 +0200 (Thu, 01 Jun 2006) | 2 lines Correctly dispatch Faults in loads (patch #1498627) ........ r46588 | georg.brandl | 2006-06-01 15:00:49 +0200 (Thu, 01 Jun 2006) | 3 lines Some code style tweaks, and remove apply. ........ r46589 | armin.rigo | 2006-06-01 15:19:12 +0200 (Thu, 01 Jun 2006) | 5 lines [ 1497053 ] Let dicts propagate the exceptions in user __eq__(). [ 1456209 ] dictresize() vulnerability ( <- backport candidate ). ........ r46590 | tim.peters | 2006-06-01 15:41:46 +0200 (Thu, 01 Jun 2006) | 2 lines Whitespace normalization. ........ r46591 | tim.peters | 2006-06-01 15:49:23 +0200 (Thu, 01 Jun 2006) | 2 lines Record bugs 1275608 and 1456209 as being fixed. ........ r46592 | tim.peters | 2006-06-01 15:56:26 +0200 (Thu, 01 Jun 2006) | 5 lines Re-enable a new empty-string test added during the NFS sprint, but disabled then because str and unicode strings gave different results. The implementations were repaired later during the sprint, but the new test remained disabled. ........ r46594 | tim.peters | 2006-06-01 17:50:44 +0200 (Thu, 01 Jun 2006) | 7 lines Armin committed his patch while I was reviewing it (I'm sure he didn't know this), so merged in some changes I made during review. Nothing material apart from changing a new `mask` local from int to Py_ssize_t. Mostly this is repairing comments that were made incorrect, and adding new comments. Also a few minor code rewrites for clarity or helpful succinctness. ........ r46599 | neal.norwitz | 2006-06-02 06:45:53 +0200 (Fri, 02 Jun 2006) | 1 line Convert docstrings to comments so regrtest -v prints method names ........ r46600 | neal.norwitz | 2006-06-02 06:50:49 +0200 (Fri, 02 Jun 2006) | 2 lines Fix memory leak found by valgrind. ........ r46601 | neal.norwitz | 2006-06-02 06:54:52 +0200 (Fri, 02 Jun 2006) | 1 line More memory leaks from valgrind ........ r46602 | neal.norwitz | 2006-06-02 08:23:00 +0200 (Fri, 02 Jun 2006) | 11 lines Patch #1357836: Prevent an invalid memory read from test_coding in case the done flag is set. In that case, the loop isn't entered. I wonder if rather than setting the done flag in the cases before the loop, if they should just exit early. This code looks like it should be refactored. Backport candidate (also the early break above if decoding_fgets fails) ........ r46603 | martin.blais | 2006-06-02 15:03:43 +0200 (Fri, 02 Jun 2006) | 1 line Fixed struct test to not use unittest. ........ r46605 | tim.peters | 2006-06-03 01:22:51 +0200 (Sat, 03 Jun 2006) | 10 lines pprint functions used to sort a dict (by key) if and only if the output required more than one line. "Small" dicts got displayed in seemingly random order (the hash-induced order produced by dict.__repr__). None of this was documented. Now pprint functions always sort dicts by key, and the docs promise it. This was proposed and agreed to during the PyCon 2006 core sprint -- I just didn't have time for it before now. ........
2006-06-08 11:42:34 -03:00
* If memory allocation fails, %ENOMEM is stored in %errno.
*
* This function resets %errno before calling strtod() so that
* you can reliably detect overflow and underflow.
*
* Return value: the #gdouble value.
**/
#ifndef PY_NO_SHORT_FLOAT_REPR
static double
_PyOS_ascii_strtod(const char *nptr, char **endptr)
{
double result;
_Py_SET_53BIT_PRECISION_HEADER;
assert(nptr != NULL);
/* Set errno to zero, so that we can distinguish zero results
and underflows */
errno = 0;
_Py_SET_53BIT_PRECISION_START;
result = _Py_dg_strtod(nptr, endptr);
_Py_SET_53BIT_PRECISION_END;
if (*endptr == nptr)
/* string might represent an inf or nan */
result = _Py_parse_inf_or_nan(nptr, endptr);
return result;
}
#else
/*
Use system strtod; since strtod is locale aware, we may
have to first fix the decimal separator.
Note that unlike _Py_dg_strtod, the system strtod may not always give
correctly rounded results.
*/
static double
_PyOS_ascii_strtod(const char *nptr, char **endptr)
{
char *fail_pos;
double val;
struct lconv *locale_data;
const char *decimal_point;
size_t decimal_point_len;
const char *p, *decimal_point_pos;
const char *end = NULL; /* Silence gcc */
const char *digits_pos = NULL;
int negate = 0;
assert(nptr != NULL);
fail_pos = NULL;
locale_data = localeconv();
decimal_point = locale_data->decimal_point;
decimal_point_len = strlen(decimal_point);
assert(decimal_point_len != 0);
decimal_point_pos = NULL;
/* Parse infinities and nans */
val = _Py_parse_inf_or_nan(nptr, endptr);
if (*endptr != nptr)
return val;
/* Set errno to zero, so that we can distinguish zero results
and underflows */
errno = 0;
/* We process the optional sign manually, then pass the remainder to
the system strtod. This ensures that the result of an underflow
has the correct sign. (bug #1725) */
p = nptr;
/* Process leading sign, if present */
if (*p == '-') {
negate = 1;
p++;
}
else if (*p == '+') {
p++;
}
/* Some platform strtods accept hex floats; Python shouldn't (at the
moment), so we check explicitly for strings starting with '0x'. */
if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X'))
goto invalid_string;
/* Check that what's left begins with a digit or decimal point */
if (!Py_ISDIGIT(*p) && *p != '.')
goto invalid_string;
digits_pos = p;
if (decimal_point[0] != '.' ||
decimal_point[1] != 0)
{
/* Look for a '.' in the input; if present, it'll need to be
swapped for the current locale's decimal point before we
call strtod. On the other hand, if we find the current
locale's decimal point then the input is invalid. */
while (Py_ISDIGIT(*p))
p++;
if (*p == '.')
{
decimal_point_pos = p++;
/* locate end of number */
while (Py_ISDIGIT(*p))
p++;
if (*p == 'e' || *p == 'E')
p++;
if (*p == '+' || *p == '-')
p++;
while (Py_ISDIGIT(*p))
p++;
end = p;
}
else if (strncmp(p, decimal_point, decimal_point_len) == 0)
/* Python bug #1417699 */
goto invalid_string;
/* For the other cases, we need not convert the decimal
point */
}
if (decimal_point_pos) {
char *copy, *c;
/* Create a copy of the input, with the '.' converted to the
locale-specific decimal point */
copy = (char *)PyMem_MALLOC(end - digits_pos +
1 + decimal_point_len);
if (copy == NULL) {
*endptr = (char *)nptr;
errno = ENOMEM;
return val;
}
c = copy;
memcpy(c, digits_pos, decimal_point_pos - digits_pos);
c += decimal_point_pos - digits_pos;
memcpy(c, decimal_point, decimal_point_len);
c += decimal_point_len;
memcpy(c, decimal_point_pos + 1,
end - (decimal_point_pos + 1));
c += end - (decimal_point_pos + 1);
*c = 0;
val = strtod(copy, &fail_pos);
if (fail_pos)
{
if (fail_pos > decimal_point_pos)
fail_pos = (char *)digits_pos +
(fail_pos - copy) -
(decimal_point_len - 1);
else
fail_pos = (char *)digits_pos +
(fail_pos - copy);
}
PyMem_FREE(copy);
}
else {
val = strtod(digits_pos, &fail_pos);
}
if (fail_pos == digits_pos)
goto invalid_string;
if (negate && fail_pos != nptr)
val = -val;
*endptr = fail_pos;
return val;
invalid_string:
*endptr = (char*)nptr;
errno = EINVAL;
return -1.0;
}
#endif
/* PyOS_string_to_double converts a null-terminated byte string s (interpreted
as a string of ASCII characters) to a float. The string should not have
leading or trailing whitespace. The conversion is independent of the
current locale.
If endptr is NULL, try to convert the whole string. Raise ValueError and
return -1.0 if the string is not a valid representation of a floating-point
number.
If endptr is non-NULL, try to convert as much of the string as possible.
If no initial segment of the string is the valid representation of a
floating-point number then *endptr is set to point to the beginning of the
string, -1.0 is returned and again ValueError is raised.
On overflow (e.g., when trying to convert '1e500' on an IEEE 754 machine),
if overflow_exception is NULL then +-Py_HUGE_VAL is returned, and no Python
exception is raised. Otherwise, overflow_exception should point to
a Python exception, this exception will be raised, -1.0 will be returned,
and *endptr will point just past the end of the converted value.
If any other failure occurs (for example lack of memory), -1.0 is returned
and the appropriate Python exception will have been set.
*/
double
PyOS_string_to_double(const char *s,
char **endptr,
PyObject *overflow_exception)
{
double x, result=-1.0;
char *fail_pos;
errno = 0;
PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0)
x = _PyOS_ascii_strtod(s, &fail_pos);
PyFPE_END_PROTECT(x)
if (errno == ENOMEM) {
PyErr_NoMemory();
fail_pos = (char *)s;
}
else if (!endptr && (fail_pos == s || *fail_pos != '\0'))
PyErr_Format(PyExc_ValueError,
"could not convert string to float: "
"%.200s", s);
else if (fail_pos == s)
PyErr_Format(PyExc_ValueError,
"could not convert string to float: "
"%.200s", s);
else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception)
PyErr_Format(overflow_exception,
"value too large to convert to float: "
"%.200s", s);
else
result = x;
if (endptr != NULL)
*endptr = fail_pos;
return result;
}
/* Remove underscores that follow the underscore placement rule from
the string and then call the `innerfunc` function on the result.
It should return a new object or NULL on exception.
`what` is used for the error message emitted when underscores are detected
that don't follow the rule. `arg` is an opaque pointer passed to the inner
function.
This is used to implement underscore-agnostic conversion for floats
and complex numbers.
*/
PyObject *
_Py_string_to_number_with_underscores(
const char *s, Py_ssize_t orig_len, const char *what, PyObject *obj, void *arg,
PyObject *(*innerfunc)(const char *, Py_ssize_t, void *))
{
char prev;
const char *p, *last;
char *dup, *end;
PyObject *result;
if (strchr(s, '_') == NULL) {
return innerfunc(s, orig_len, arg);
}
dup = PyMem_Malloc(orig_len + 1);
end = dup;
prev = '\0';
last = s + orig_len;
for (p = s; *p; p++) {
if (*p == '_') {
/* Underscores are only allowed after digits. */
if (!(prev >= '0' && prev <= '9')) {
goto error;
}
}
else {
*end++ = *p;
/* Underscores are only allowed before digits. */
if (prev == '_' && !(*p >= '0' && *p <= '9')) {
goto error;
}
}
prev = *p;
}
/* Underscores are not allowed at the end. */
if (prev == '_') {
goto error;
}
/* No embedded NULs allowed. */
if (p != last) {
goto error;
}
*end = '\0';
result = innerfunc(dup, end - dup, arg);
PyMem_Free(dup);
return result;
error:
PyMem_Free(dup);
PyErr_Format(PyExc_ValueError,
"could not convert string to %s: "
"%R", what, obj);
return NULL;
}
#ifdef PY_NO_SHORT_FLOAT_REPR
/* Given a string that may have a decimal point in the current
locale, change it back to a dot. Since the string cannot get
longer, no need for a maximum buffer size parameter. */
Py_LOCAL_INLINE(void)
change_decimal_from_locale_to_dot(char* buffer)
{
struct lconv *locale_data = localeconv();
const char *decimal_point = locale_data->decimal_point;
if (decimal_point[0] != '.' || decimal_point[1] != 0) {
size_t decimal_point_len = strlen(decimal_point);
if (*buffer == '+' || *buffer == '-')
buffer++;
while (Py_ISDIGIT(*buffer))
buffer++;
if (strncmp(buffer, decimal_point, decimal_point_len) == 0) {
*buffer = '.';
buffer++;
if (decimal_point_len > 1) {
/* buffer needs to get smaller */
size_t rest_len = strlen(buffer +
(decimal_point_len - 1));
memmove(buffer,
buffer + (decimal_point_len - 1),
rest_len);
buffer[rest_len] = 0;
}
}
}
}
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900-60931,60933-60958 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r60901 | eric.smith | 2008-02-19 14:21:56 +0100 (Tue, 19 Feb 2008) | 1 line Added PEP 3101. ........ r60907 | georg.brandl | 2008-02-20 20:12:36 +0100 (Wed, 20 Feb 2008) | 2 lines Fixes contributed by Ori Avtalion. ........ r60909 | eric.smith | 2008-02-21 00:34:22 +0100 (Thu, 21 Feb 2008) | 1 line Trim leading zeros from a floating point exponent, per C99. See issue 1600. As far as I know, this only affects Windows. Add float type 'n' to PyOS_ascii_formatd (see PEP 3101 for 'n' description). ........ r60910 | eric.smith | 2008-02-21 00:39:28 +0100 (Thu, 21 Feb 2008) | 1 line Now that PyOS_ascii_formatd supports the 'n' format, simplify the float formatting code to just call it. ........ r60918 | andrew.kuchling | 2008-02-21 15:23:38 +0100 (Thu, 21 Feb 2008) | 2 lines Close manifest file. This change doesn't make any difference to CPython, but is a necessary fix for Jython. ........ r60921 | guido.van.rossum | 2008-02-21 18:46:16 +0100 (Thu, 21 Feb 2008) | 2 lines Remove news about float repr() -- issue 1580 is still in limbo. ........ r60923 | guido.van.rossum | 2008-02-21 19:18:37 +0100 (Thu, 21 Feb 2008) | 5 lines Removed uses of dict.has_key() from distutils, and uses of callable() from copy_reg.py, so the interpreter now starts up without warnings when '-3' is given. More work like this needs to be done in the rest of the stdlib. ........ r60924 | thomas.heller | 2008-02-21 19:28:48 +0100 (Thu, 21 Feb 2008) | 4 lines configure.ac: Remove the configure check for _Bool, it is already done in the top-level Python configure script. configure, fficonfig.h.in: regenerated. ........ r60925 | thomas.heller | 2008-02-21 19:52:20 +0100 (Thu, 21 Feb 2008) | 3 lines Replace 'has_key()' with 'in'. Replace 'raise Error, stuff' with 'raise Error(stuff)'. ........ r60927 | raymond.hettinger | 2008-02-21 20:24:53 +0100 (Thu, 21 Feb 2008) | 1 line Update more instances of has_key(). ........ r60928 | guido.van.rossum | 2008-02-21 20:46:35 +0100 (Thu, 21 Feb 2008) | 3 lines Fix a few typos and layout glitches (more work is needed). Move 2.5 news to Misc/HISTORY. ........ r60936 | georg.brandl | 2008-02-21 21:33:38 +0100 (Thu, 21 Feb 2008) | 2 lines #2079: typo in userdict docs. ........ r60938 | georg.brandl | 2008-02-21 21:38:13 +0100 (Thu, 21 Feb 2008) | 2 lines Part of #2154: minimal syntax fixes in doc example snippets. ........ r60942 | raymond.hettinger | 2008-02-22 04:16:42 +0100 (Fri, 22 Feb 2008) | 1 line First draft for itertools.product(). Docs and other updates forthcoming. ........ r60955 | nick.coghlan | 2008-02-22 11:54:06 +0100 (Fri, 22 Feb 2008) | 1 line Try to make command line error messages from runpy easier to understand (and suppress traceback cruft from the implicitly invoked runpy machinery) ........ r60956 | georg.brandl | 2008-02-22 13:31:45 +0100 (Fri, 22 Feb 2008) | 2 lines A lot more typo fixes by Ori Avtalion. ........ r60957 | georg.brandl | 2008-02-22 13:56:34 +0100 (Fri, 22 Feb 2008) | 2 lines Don't reference pyshell. ........ r60958 | georg.brandl | 2008-02-22 13:57:05 +0100 (Fri, 22 Feb 2008) | 2 lines Another fix. ........
2008-02-22 12:37:40 -04:00
/* From the C99 standard, section 7.19.6:
The exponent always contains at least two digits, and only as many more digits
as necessary to represent the exponent.
*/
#define MIN_EXPONENT_DIGITS 2
/* Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS
in length. */
Py_LOCAL_INLINE(void)
ensure_minimum_exponent_length(char* buffer, size_t buf_size)
{
char *p = strpbrk(buffer, "eE");
if (p && (*(p + 1) == '-' || *(p + 1) == '+')) {
char *start = p + 2;
int exponent_digit_cnt = 0;
int leading_zero_cnt = 0;
int in_leading_zeros = 1;
int significant_digit_cnt;
/* Skip over the exponent and the sign. */
p += 2;
/* Find the end of the exponent, keeping track of leading
zeros. */
while (*p && Py_ISDIGIT(*p)) {
if (in_leading_zeros && *p == '0')
++leading_zero_cnt;
if (*p != '0')
in_leading_zeros = 0;
++p;
++exponent_digit_cnt;
}
significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt;
if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) {
/* If there are 2 exactly digits, we're done,
regardless of what they contain */
}
else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) {
int extra_zeros_cnt;
/* There are more than 2 digits in the exponent. See
if we can delete some of the leading zeros */
if (significant_digit_cnt < MIN_EXPONENT_DIGITS)
significant_digit_cnt = MIN_EXPONENT_DIGITS;
extra_zeros_cnt = exponent_digit_cnt -
significant_digit_cnt;
/* Delete extra_zeros_cnt worth of characters from the
front of the exponent */
assert(extra_zeros_cnt >= 0);
/* Add one to significant_digit_cnt to copy the
trailing 0 byte, thus setting the length */
memmove(start,
start + extra_zeros_cnt,
significant_digit_cnt + 1);
}
else {
/* If there are fewer than 2 digits, add zeros
until there are 2, if there's enough room */
int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt;
if (start + zeros + exponent_digit_cnt + 1
< buffer + buf_size) {
memmove(start + zeros, start,
exponent_digit_cnt + 1);
memset(start, '0', zeros);
}
}
}
}
/* Remove trailing zeros after the decimal point from a numeric string; also
remove the decimal point if all digits following it are zero. The numeric
string must end in '\0', and should not have any leading or trailing
whitespace. Assumes that the decimal point is '.'. */
Py_LOCAL_INLINE(void)
remove_trailing_zeros(char *buffer)
{
char *old_fraction_end, *new_fraction_end, *end, *p;
p = buffer;
if (*p == '-' || *p == '+')
/* Skip leading sign, if present */
++p;
while (Py_ISDIGIT(*p))
++p;
/* if there's no decimal point there's nothing to do */
if (*p++ != '.')
return;
/* scan any digits after the point */
while (Py_ISDIGIT(*p))
++p;
old_fraction_end = p;
/* scan up to ending '\0' */
while (*p != '\0')
p++;
/* +1 to make sure that we move the null byte as well */
end = p+1;
/* scan back from fraction_end, looking for removable zeros */
p = old_fraction_end;
while (*(p-1) == '0')
--p;
/* and remove point if we've got that far */
if (*(p-1) == '.')
--p;
new_fraction_end = p;
memmove(new_fraction_end, old_fraction_end, end-old_fraction_end);
}
/* Ensure that buffer has a decimal point in it. The decimal point will not
be in the current locale, it will always be '.'. Don't add a decimal point
if an exponent is present. Also, convert to exponential notation where
adding a '.0' would produce too many significant digits (see issue 5864).
Returns a pointer to the fixed buffer, or NULL on failure.
*/
Py_LOCAL_INLINE(char *)
ensure_decimal_point(char* buffer, size_t buf_size, int precision)
{
int digit_count, insert_count = 0, convert_to_exp = 0;
char *chars_to_insert, *digits_start;
/* search for the first non-digit character */
char *p = buffer;
if (*p == '-' || *p == '+')
/* Skip leading sign, if present. I think this could only
ever be '-', but it can't hurt to check for both. */
++p;
digits_start = p;
while (*p && Py_ISDIGIT(*p))
++p;
digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int);
if (*p == '.') {
if (Py_ISDIGIT(*(p+1))) {
/* Nothing to do, we already have a decimal
point and a digit after it */
}
else {
/* We have a decimal point, but no following
digit. Insert a zero after the decimal. */
/* can't ever get here via PyOS_double_to_string */
assert(precision == -1);
++p;
chars_to_insert = "0";
insert_count = 1;
}
}
else if (!(*p == 'e' || *p == 'E')) {
/* Don't add ".0" if we have an exponent. */
if (digit_count == precision) {
/* issue 5864: don't add a trailing .0 in the case
where the '%g'-formatted result already has as many
significant digits as were requested. Switch to
exponential notation instead. */
convert_to_exp = 1;
/* no exponent, no point, and we shouldn't land here
for infs and nans, so we must be at the end of the
string. */
assert(*p == '\0');
}
else {
assert(precision == -1 || digit_count < precision);
chars_to_insert = ".0";
insert_count = 2;
}
}
if (insert_count) {
size_t buf_len = strlen(buffer);
if (buf_len + insert_count + 1 >= buf_size) {
/* If there is not enough room in the buffer
for the additional text, just skip it. It's
not worth generating an error over. */
}
else {
memmove(p + insert_count, p,
buffer + strlen(buffer) - p + 1);
memcpy(p, chars_to_insert, insert_count);
}
}
if (convert_to_exp) {
int written;
size_t buf_avail;
p = digits_start;
/* insert decimal point */
assert(digit_count >= 1);
memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */
p[1] = '.';
p += digit_count+1;
assert(p <= buf_size+buffer);
buf_avail = buf_size+buffer-p;
if (buf_avail == 0)
return NULL;
/* Add exponent. It's okay to use lower case 'e': we only
arrive here as a result of using the empty format code or
repr/str builtins and those never want an upper case 'E' */
written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1);
if (!(0 <= written &&
written < Py_SAFE_DOWNCAST(buf_avail, size_t, int)))
/* output truncated, or something else bad happened */
return NULL;
remove_trailing_zeros(buffer);
}
return buffer;
}
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900-60931,60933-60958 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r60901 | eric.smith | 2008-02-19 14:21:56 +0100 (Tue, 19 Feb 2008) | 1 line Added PEP 3101. ........ r60907 | georg.brandl | 2008-02-20 20:12:36 +0100 (Wed, 20 Feb 2008) | 2 lines Fixes contributed by Ori Avtalion. ........ r60909 | eric.smith | 2008-02-21 00:34:22 +0100 (Thu, 21 Feb 2008) | 1 line Trim leading zeros from a floating point exponent, per C99. See issue 1600. As far as I know, this only affects Windows. Add float type 'n' to PyOS_ascii_formatd (see PEP 3101 for 'n' description). ........ r60910 | eric.smith | 2008-02-21 00:39:28 +0100 (Thu, 21 Feb 2008) | 1 line Now that PyOS_ascii_formatd supports the 'n' format, simplify the float formatting code to just call it. ........ r60918 | andrew.kuchling | 2008-02-21 15:23:38 +0100 (Thu, 21 Feb 2008) | 2 lines Close manifest file. This change doesn't make any difference to CPython, but is a necessary fix for Jython. ........ r60921 | guido.van.rossum | 2008-02-21 18:46:16 +0100 (Thu, 21 Feb 2008) | 2 lines Remove news about float repr() -- issue 1580 is still in limbo. ........ r60923 | guido.van.rossum | 2008-02-21 19:18:37 +0100 (Thu, 21 Feb 2008) | 5 lines Removed uses of dict.has_key() from distutils, and uses of callable() from copy_reg.py, so the interpreter now starts up without warnings when '-3' is given. More work like this needs to be done in the rest of the stdlib. ........ r60924 | thomas.heller | 2008-02-21 19:28:48 +0100 (Thu, 21 Feb 2008) | 4 lines configure.ac: Remove the configure check for _Bool, it is already done in the top-level Python configure script. configure, fficonfig.h.in: regenerated. ........ r60925 | thomas.heller | 2008-02-21 19:52:20 +0100 (Thu, 21 Feb 2008) | 3 lines Replace 'has_key()' with 'in'. Replace 'raise Error, stuff' with 'raise Error(stuff)'. ........ r60927 | raymond.hettinger | 2008-02-21 20:24:53 +0100 (Thu, 21 Feb 2008) | 1 line Update more instances of has_key(). ........ r60928 | guido.van.rossum | 2008-02-21 20:46:35 +0100 (Thu, 21 Feb 2008) | 3 lines Fix a few typos and layout glitches (more work is needed). Move 2.5 news to Misc/HISTORY. ........ r60936 | georg.brandl | 2008-02-21 21:33:38 +0100 (Thu, 21 Feb 2008) | 2 lines #2079: typo in userdict docs. ........ r60938 | georg.brandl | 2008-02-21 21:38:13 +0100 (Thu, 21 Feb 2008) | 2 lines Part of #2154: minimal syntax fixes in doc example snippets. ........ r60942 | raymond.hettinger | 2008-02-22 04:16:42 +0100 (Fri, 22 Feb 2008) | 1 line First draft for itertools.product(). Docs and other updates forthcoming. ........ r60955 | nick.coghlan | 2008-02-22 11:54:06 +0100 (Fri, 22 Feb 2008) | 1 line Try to make command line error messages from runpy easier to understand (and suppress traceback cruft from the implicitly invoked runpy machinery) ........ r60956 | georg.brandl | 2008-02-22 13:31:45 +0100 (Fri, 22 Feb 2008) | 2 lines A lot more typo fixes by Ori Avtalion. ........ r60957 | georg.brandl | 2008-02-22 13:56:34 +0100 (Fri, 22 Feb 2008) | 2 lines Don't reference pyshell. ........ r60958 | georg.brandl | 2008-02-22 13:57:05 +0100 (Fri, 22 Feb 2008) | 2 lines Another fix. ........
2008-02-22 12:37:40 -04:00
/* see FORMATBUFLEN in unicodeobject.c */
#define FLOAT_FORMATBUFLEN 120
/**
* _PyOS_ascii_formatd:
* @buffer: A buffer to place the resulting string in
Merged revisions 61431,61433-61436,61439,61444,61449-61450,61453,61458,61465,61468,61471-61474,61480,61483-61484,61488,61495-61496,61498,61503-61504,61507,61509-61510,61515-61518 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r61431 | vinay.sajip | 2008-03-16 22:35:58 +0100 (So, 16 Mär 2008) | 1 line Clarified documentation on use of shutdown(). ........ r61433 | mark.summerfield | 2008-03-17 09:28:15 +0100 (Mo, 17 Mär 2008) | 5 lines Added a footnote to each pointing out that for XML output if an encoding string is given it should conform to the appropriate XML standards---for example, "UTF-8" is okay, but "UTF8" is not. ........ r61434 | eric.smith | 2008-03-17 12:01:01 +0100 (Mo, 17 Mär 2008) | 7 lines Issue 2264: empty float presentation type needs to have at least one digit past the decimal point. Added "Z" format_char to PyOS_ascii_formatd to support empty float presentation type. Renamed buf_size in PyOS_ascii_formatd to more accurately reflect it's meaning. Modified format.__float__ to use the new "Z" format as the default. Added test cases. ........ r61435 | eric.smith | 2008-03-17 13:14:29 +0100 (Mo, 17 Mär 2008) | 2 lines Reformated lines > 79 chars. Deleted unused macro ISXDIGIT. ........ r61436 | jeffrey.yasskin | 2008-03-17 15:40:53 +0100 (Mo, 17 Mär 2008) | 13 lines Allow Gnu gcc's to build python on OSX by removing -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd from configure. * r22183 added -no-cpp-precomp, which http://gcc.gnu.org/ml/gcc/2005-12/msg00368.html claims hasn't been needed since gcc-3.1. * r25607 added -Wno-long-double to avoid a warning in Include/objimpl.h (issue 525481). The long double is still there, but OSX 10.4's gcc no longer warns about it. * r33666 fixed issue 775892 on OSX 10.3 by adding -mno-fused-madd, which changed the sign of some float 0s. Tim Peters said it wasn't a real issue anyway, and it no longer causes test failures. Fixes issue #1779871. ........ r61439 | martin.v.loewis | 2008-03-17 17:31:57 +0100 (Mo, 17 Mär 2008) | 2 lines Add Trent Nelson. ........ r61444 | travis.oliphant | 2008-03-17 18:36:12 +0100 (Mo, 17 Mär 2008) | 1 line Add necessary headers to back-port new buffer protocol to Python 2.6 ........ r61449 | gregory.p.smith | 2008-03-17 19:48:05 +0100 (Mo, 17 Mär 2008) | 8 lines Force zlib.crc32 and zlib.adler32 to return a signed integer on all platforms regardless of the native sizeof(long) used in the integer object. This somewhat odd behavior of returning a signed is maintained in 2.x for compatibility reasons of always returning an integer rather than a long object. Fixes Issue1202 for Python 2.6 ........ r61450 | neal.norwitz | 2008-03-17 20:02:45 +0100 (Mo, 17 Mär 2008) | 3 lines Use a buffer large enough to ensure we don't overrun, even if the value is outside the range we expect. ........ r61453 | steven.bethard | 2008-03-17 20:33:11 +0100 (Mo, 17 Mär 2008) | 1 line Document unicode.isnumeric() and unicode.isdecimal() (issue2326) ........ r61458 | neal.norwitz | 2008-03-17 21:22:43 +0100 (Mo, 17 Mär 2008) | 5 lines Issue 2321: reduce memory usage (increase the memory that is returned to the system) by using pymalloc for the data of unicode objects. Will backport. ........ r61465 | martin.v.loewis | 2008-03-17 22:55:30 +0100 (Mo, 17 Mär 2008) | 2 lines Add David Wolever. ........ r61468 | gregory.p.smith | 2008-03-18 01:20:01 +0100 (Di, 18 Mär 2008) | 3 lines Fix the IOError message text when opening a file with an invalid filename. Error reported by Ilan Schnell. ........ r61471 | brett.cannon | 2008-03-18 02:00:07 +0100 (Di, 18 Mär 2008) | 2 lines Convert test_strftime, test_getargs, and test_pep247 to use unittest. ........ r61472 | jeffrey.yasskin | 2008-03-18 02:09:59 +0100 (Di, 18 Mär 2008) | 2 lines Fix build on platforms that don't have intptr_t. Patch by Joseph Armbruster. ........ r61473 | brett.cannon | 2008-03-18 02:50:25 +0100 (Di, 18 Mär 2008) | 2 lines Convert test_dummy_threading and test_dbm to unittest. ........ r61474 | brett.cannon | 2008-03-18 02:58:56 +0100 (Di, 18 Mär 2008) | 2 lines Move test_extcall to doctest. ........ r61480 | brett.cannon | 2008-03-18 04:46:22 +0100 (Di, 18 Mär 2008) | 2 lines test_errno was a no-op test; now it actually tests things and uses unittest. ........ r61483 | brett.cannon | 2008-03-18 05:09:00 +0100 (Di, 18 Mär 2008) | 3 lines Remove our implementation of memmove() and strerror(); both are in the C89 standard library. ........ r61484 | brett.cannon | 2008-03-18 05:16:06 +0100 (Di, 18 Mär 2008) | 2 lines The output directory for tests that compare against stdout is now gone! ........ r61488 | jeffrey.yasskin | 2008-03-18 05:29:35 +0100 (Di, 18 Mär 2008) | 2 lines Block the "socket.ssl() is deprecated" warning from test_socket_ssl. ........ r61495 | jeffrey.yasskin | 2008-03-18 05:56:06 +0100 (Di, 18 Mär 2008) | 4 lines Speed test_thread up from 51.328s to 0.081s by reducing its sleep times. We still sleep at all to make it likely that all threads are active at the same time. ........ r61496 | jeffrey.yasskin | 2008-03-18 06:12:41 +0100 (Di, 18 Mär 2008) | 4 lines Speed up test_dict by about 10x by only checking selected dict literal sizes, instead of every integer from 0 to 400. Exhaustive testing wastes time without providing enough more assurance that the code is correct. ........ r61498 | neal.norwitz | 2008-03-18 06:20:29 +0100 (Di, 18 Mär 2008) | 1 line Try increasing the timeout to reduce the flakiness of this test. ........ r61503 | brett.cannon | 2008-03-18 06:43:04 +0100 (Di, 18 Mär 2008) | 2 lines Improve the error message for a test that failed on the S-390 Debian buildbot. ........ r61504 | jeffrey.yasskin | 2008-03-18 06:45:40 +0100 (Di, 18 Mär 2008) | 3 lines Add a -S/--slow flag to regrtest to have it print the 10 slowest tests with their times. ........ r61507 | neal.norwitz | 2008-03-18 07:03:46 +0100 (Di, 18 Mär 2008) | 1 line Add some info to the failure messages ........ r61509 | trent.nelson | 2008-03-18 08:02:12 +0100 (Di, 18 Mär 2008) | 1 line Issue 2286: bump up the stack size of the 64-bit debug python_d.exe to 2100000. The default value of 200000 causes a stack overflow at 1965 iterations of r_object() in marshal.c, 35 iterations before the 2000 limit enforced by MAX_MARSHAL_STACK_DEPTH. ........ r61510 | trent.nelson | 2008-03-18 08:32:47 +0100 (Di, 18 Mär 2008) | 5 lines The behaviour of winsound.Beep() seems to differ between different versions of Windows when there's either: a) no sound card entirely b) legacy beep driver has been disabled c) the legacy beep driver has been uninstalled Sometimes RuntimeErrors are raised, sometimes they're not. If _have_soundcard() returns False, don't expect winsound.Beep() to raise a RuntimeError, as this clearly isn't the case, as demonstrated by the various Win32 XP buildbots. ........ r61515 | martin.v.loewis | 2008-03-18 13:20:15 +0100 (Di, 18 Mär 2008) | 2 lines norwitz-amd64 (gentoo) has EREMOTEIO. ........ r61516 | martin.v.loewis | 2008-03-18 13:45:37 +0100 (Di, 18 Mär 2008) | 2 lines Add more Linux error codes. ........ r61517 | martin.v.loewis | 2008-03-18 14:05:03 +0100 (Di, 18 Mär 2008) | 2 lines Add WSA errors. ........ r61518 | martin.v.loewis | 2008-03-18 14:16:05 +0100 (Di, 18 Mär 2008) | 2 lines Note that the stderr output of the test is intentional. ........
2008-03-18 12:15:01 -03:00
* @buf_size: The length of the buffer.
* @format: The printf()-style format to use for the
* code to use for converting.
* @d: The #gdouble to convert
* @precision: The precision to use when formatting.
*
* Converts a #gdouble to a string, using the '.' as
* decimal point. To format the number you pass in
* a printf()-style format string. Allowed conversion
* specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'.
*
Merged revisions 61431,61433-61436,61439,61444,61449-61450,61453,61458,61465,61468,61471-61474,61480,61483-61484,61488,61495-61496,61498,61503-61504,61507,61509-61510,61515-61518 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r61431 | vinay.sajip | 2008-03-16 22:35:58 +0100 (So, 16 Mär 2008) | 1 line Clarified documentation on use of shutdown(). ........ r61433 | mark.summerfield | 2008-03-17 09:28:15 +0100 (Mo, 17 Mär 2008) | 5 lines Added a footnote to each pointing out that for XML output if an encoding string is given it should conform to the appropriate XML standards---for example, "UTF-8" is okay, but "UTF8" is not. ........ r61434 | eric.smith | 2008-03-17 12:01:01 +0100 (Mo, 17 Mär 2008) | 7 lines Issue 2264: empty float presentation type needs to have at least one digit past the decimal point. Added "Z" format_char to PyOS_ascii_formatd to support empty float presentation type. Renamed buf_size in PyOS_ascii_formatd to more accurately reflect it's meaning. Modified format.__float__ to use the new "Z" format as the default. Added test cases. ........ r61435 | eric.smith | 2008-03-17 13:14:29 +0100 (Mo, 17 Mär 2008) | 2 lines Reformated lines > 79 chars. Deleted unused macro ISXDIGIT. ........ r61436 | jeffrey.yasskin | 2008-03-17 15:40:53 +0100 (Mo, 17 Mär 2008) | 13 lines Allow Gnu gcc's to build python on OSX by removing -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd from configure. * r22183 added -no-cpp-precomp, which http://gcc.gnu.org/ml/gcc/2005-12/msg00368.html claims hasn't been needed since gcc-3.1. * r25607 added -Wno-long-double to avoid a warning in Include/objimpl.h (issue 525481). The long double is still there, but OSX 10.4's gcc no longer warns about it. * r33666 fixed issue 775892 on OSX 10.3 by adding -mno-fused-madd, which changed the sign of some float 0s. Tim Peters said it wasn't a real issue anyway, and it no longer causes test failures. Fixes issue #1779871. ........ r61439 | martin.v.loewis | 2008-03-17 17:31:57 +0100 (Mo, 17 Mär 2008) | 2 lines Add Trent Nelson. ........ r61444 | travis.oliphant | 2008-03-17 18:36:12 +0100 (Mo, 17 Mär 2008) | 1 line Add necessary headers to back-port new buffer protocol to Python 2.6 ........ r61449 | gregory.p.smith | 2008-03-17 19:48:05 +0100 (Mo, 17 Mär 2008) | 8 lines Force zlib.crc32 and zlib.adler32 to return a signed integer on all platforms regardless of the native sizeof(long) used in the integer object. This somewhat odd behavior of returning a signed is maintained in 2.x for compatibility reasons of always returning an integer rather than a long object. Fixes Issue1202 for Python 2.6 ........ r61450 | neal.norwitz | 2008-03-17 20:02:45 +0100 (Mo, 17 Mär 2008) | 3 lines Use a buffer large enough to ensure we don't overrun, even if the value is outside the range we expect. ........ r61453 | steven.bethard | 2008-03-17 20:33:11 +0100 (Mo, 17 Mär 2008) | 1 line Document unicode.isnumeric() and unicode.isdecimal() (issue2326) ........ r61458 | neal.norwitz | 2008-03-17 21:22:43 +0100 (Mo, 17 Mär 2008) | 5 lines Issue 2321: reduce memory usage (increase the memory that is returned to the system) by using pymalloc for the data of unicode objects. Will backport. ........ r61465 | martin.v.loewis | 2008-03-17 22:55:30 +0100 (Mo, 17 Mär 2008) | 2 lines Add David Wolever. ........ r61468 | gregory.p.smith | 2008-03-18 01:20:01 +0100 (Di, 18 Mär 2008) | 3 lines Fix the IOError message text when opening a file with an invalid filename. Error reported by Ilan Schnell. ........ r61471 | brett.cannon | 2008-03-18 02:00:07 +0100 (Di, 18 Mär 2008) | 2 lines Convert test_strftime, test_getargs, and test_pep247 to use unittest. ........ r61472 | jeffrey.yasskin | 2008-03-18 02:09:59 +0100 (Di, 18 Mär 2008) | 2 lines Fix build on platforms that don't have intptr_t. Patch by Joseph Armbruster. ........ r61473 | brett.cannon | 2008-03-18 02:50:25 +0100 (Di, 18 Mär 2008) | 2 lines Convert test_dummy_threading and test_dbm to unittest. ........ r61474 | brett.cannon | 2008-03-18 02:58:56 +0100 (Di, 18 Mär 2008) | 2 lines Move test_extcall to doctest. ........ r61480 | brett.cannon | 2008-03-18 04:46:22 +0100 (Di, 18 Mär 2008) | 2 lines test_errno was a no-op test; now it actually tests things and uses unittest. ........ r61483 | brett.cannon | 2008-03-18 05:09:00 +0100 (Di, 18 Mär 2008) | 3 lines Remove our implementation of memmove() and strerror(); both are in the C89 standard library. ........ r61484 | brett.cannon | 2008-03-18 05:16:06 +0100 (Di, 18 Mär 2008) | 2 lines The output directory for tests that compare against stdout is now gone! ........ r61488 | jeffrey.yasskin | 2008-03-18 05:29:35 +0100 (Di, 18 Mär 2008) | 2 lines Block the "socket.ssl() is deprecated" warning from test_socket_ssl. ........ r61495 | jeffrey.yasskin | 2008-03-18 05:56:06 +0100 (Di, 18 Mär 2008) | 4 lines Speed test_thread up from 51.328s to 0.081s by reducing its sleep times. We still sleep at all to make it likely that all threads are active at the same time. ........ r61496 | jeffrey.yasskin | 2008-03-18 06:12:41 +0100 (Di, 18 Mär 2008) | 4 lines Speed up test_dict by about 10x by only checking selected dict literal sizes, instead of every integer from 0 to 400. Exhaustive testing wastes time without providing enough more assurance that the code is correct. ........ r61498 | neal.norwitz | 2008-03-18 06:20:29 +0100 (Di, 18 Mär 2008) | 1 line Try increasing the timeout to reduce the flakiness of this test. ........ r61503 | brett.cannon | 2008-03-18 06:43:04 +0100 (Di, 18 Mär 2008) | 2 lines Improve the error message for a test that failed on the S-390 Debian buildbot. ........ r61504 | jeffrey.yasskin | 2008-03-18 06:45:40 +0100 (Di, 18 Mär 2008) | 3 lines Add a -S/--slow flag to regrtest to have it print the 10 slowest tests with their times. ........ r61507 | neal.norwitz | 2008-03-18 07:03:46 +0100 (Di, 18 Mär 2008) | 1 line Add some info to the failure messages ........ r61509 | trent.nelson | 2008-03-18 08:02:12 +0100 (Di, 18 Mär 2008) | 1 line Issue 2286: bump up the stack size of the 64-bit debug python_d.exe to 2100000. The default value of 200000 causes a stack overflow at 1965 iterations of r_object() in marshal.c, 35 iterations before the 2000 limit enforced by MAX_MARSHAL_STACK_DEPTH. ........ r61510 | trent.nelson | 2008-03-18 08:32:47 +0100 (Di, 18 Mär 2008) | 5 lines The behaviour of winsound.Beep() seems to differ between different versions of Windows when there's either: a) no sound card entirely b) legacy beep driver has been disabled c) the legacy beep driver has been uninstalled Sometimes RuntimeErrors are raised, sometimes they're not. If _have_soundcard() returns False, don't expect winsound.Beep() to raise a RuntimeError, as this clearly isn't the case, as demonstrated by the various Win32 XP buildbots. ........ r61515 | martin.v.loewis | 2008-03-18 13:20:15 +0100 (Di, 18 Mär 2008) | 2 lines norwitz-amd64 (gentoo) has EREMOTEIO. ........ r61516 | martin.v.loewis | 2008-03-18 13:45:37 +0100 (Di, 18 Mär 2008) | 2 lines Add more Linux error codes. ........ r61517 | martin.v.loewis | 2008-03-18 14:05:03 +0100 (Di, 18 Mär 2008) | 2 lines Add WSA errors. ........ r61518 | martin.v.loewis | 2008-03-18 14:16:05 +0100 (Di, 18 Mär 2008) | 2 lines Note that the stderr output of the test is intentional. ........
2008-03-18 12:15:01 -03:00
* 'Z' is the same as 'g', except it always has a decimal and
* at least one digit after the decimal.
Merged revisions 60481,60485,60489-60492,60494-60496,60498-60499,60501-60503,60505-60506,60508-60509,60523-60524,60532,60543,60545,60547-60548,60552,60554,60556-60559,60561-60562,60569,60571-60572,60574,60576-60583,60585-60586,60589,60591,60594-60595,60597-60598,60600-60601,60606-60612,60615,60617,60619-60621,60623-60625,60627-60629,60631,60633,60635,60647,60650,60652,60654,60656,60658-60659,60664-60666,60668-60670,60672,60676,60678,60680-60683,60685-60686,60688,60690,60692-60694,60697-60700,60705-60706,60708,60711,60714,60720,60724-60730,60732,60736,60742,60744,60746,60748,60750-60751,60753,60756-60757,60759-60761,60763-60764,60766,60769-60770,60774-60784,60787-60789,60793,60796,60799-60809,60812-60813,60815-60821,60823-60826,60828-60829,60831-60834,60836,60838-60839,60846-60849,60852-60854,60856-60859,60861-60870,60874-60875,60880-60881,60886,60888-60890,60892,60894-60898,60900-60931,60933-60958 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r60901 | eric.smith | 2008-02-19 14:21:56 +0100 (Tue, 19 Feb 2008) | 1 line Added PEP 3101. ........ r60907 | georg.brandl | 2008-02-20 20:12:36 +0100 (Wed, 20 Feb 2008) | 2 lines Fixes contributed by Ori Avtalion. ........ r60909 | eric.smith | 2008-02-21 00:34:22 +0100 (Thu, 21 Feb 2008) | 1 line Trim leading zeros from a floating point exponent, per C99. See issue 1600. As far as I know, this only affects Windows. Add float type 'n' to PyOS_ascii_formatd (see PEP 3101 for 'n' description). ........ r60910 | eric.smith | 2008-02-21 00:39:28 +0100 (Thu, 21 Feb 2008) | 1 line Now that PyOS_ascii_formatd supports the 'n' format, simplify the float formatting code to just call it. ........ r60918 | andrew.kuchling | 2008-02-21 15:23:38 +0100 (Thu, 21 Feb 2008) | 2 lines Close manifest file. This change doesn't make any difference to CPython, but is a necessary fix for Jython. ........ r60921 | guido.van.rossum | 2008-02-21 18:46:16 +0100 (Thu, 21 Feb 2008) | 2 lines Remove news about float repr() -- issue 1580 is still in limbo. ........ r60923 | guido.van.rossum | 2008-02-21 19:18:37 +0100 (Thu, 21 Feb 2008) | 5 lines Removed uses of dict.has_key() from distutils, and uses of callable() from copy_reg.py, so the interpreter now starts up without warnings when '-3' is given. More work like this needs to be done in the rest of the stdlib. ........ r60924 | thomas.heller | 2008-02-21 19:28:48 +0100 (Thu, 21 Feb 2008) | 4 lines configure.ac: Remove the configure check for _Bool, it is already done in the top-level Python configure script. configure, fficonfig.h.in: regenerated. ........ r60925 | thomas.heller | 2008-02-21 19:52:20 +0100 (Thu, 21 Feb 2008) | 3 lines Replace 'has_key()' with 'in'. Replace 'raise Error, stuff' with 'raise Error(stuff)'. ........ r60927 | raymond.hettinger | 2008-02-21 20:24:53 +0100 (Thu, 21 Feb 2008) | 1 line Update more instances of has_key(). ........ r60928 | guido.van.rossum | 2008-02-21 20:46:35 +0100 (Thu, 21 Feb 2008) | 3 lines Fix a few typos and layout glitches (more work is needed). Move 2.5 news to Misc/HISTORY. ........ r60936 | georg.brandl | 2008-02-21 21:33:38 +0100 (Thu, 21 Feb 2008) | 2 lines #2079: typo in userdict docs. ........ r60938 | georg.brandl | 2008-02-21 21:38:13 +0100 (Thu, 21 Feb 2008) | 2 lines Part of #2154: minimal syntax fixes in doc example snippets. ........ r60942 | raymond.hettinger | 2008-02-22 04:16:42 +0100 (Fri, 22 Feb 2008) | 1 line First draft for itertools.product(). Docs and other updates forthcoming. ........ r60955 | nick.coghlan | 2008-02-22 11:54:06 +0100 (Fri, 22 Feb 2008) | 1 line Try to make command line error messages from runpy easier to understand (and suppress traceback cruft from the implicitly invoked runpy machinery) ........ r60956 | georg.brandl | 2008-02-22 13:31:45 +0100 (Fri, 22 Feb 2008) | 2 lines A lot more typo fixes by Ori Avtalion. ........ r60957 | georg.brandl | 2008-02-22 13:56:34 +0100 (Fri, 22 Feb 2008) | 2 lines Don't reference pyshell. ........ r60958 | georg.brandl | 2008-02-22 13:57:05 +0100 (Fri, 22 Feb 2008) | 2 lines Another fix. ........
2008-02-22 12:37:40 -04:00
*
* Return value: The pointer to the buffer with the converted string.
* On failure returns NULL but does not set any Python exception.
**/
static char *
_PyOS_ascii_formatd(char *buffer,
size_t buf_size,
const char *format,
double d,
int precision)
{
char format_char;
size_t format_len = strlen(format);
/* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but
also with at least one character past the decimal. */
char tmp_format[FLOAT_FORMATBUFLEN];
/* The last character in the format string must be the format char */
format_char = format[format_len - 1];
if (format[0] != '%')
return NULL;
/* I'm not sure why this test is here. It's ensuring that the format
string after the first character doesn't have a single quote, a
lowercase l, or a percent. This is the reverse of the commented-out
test about 10 lines ago. */
if (strpbrk(format + 1, "'l%"))
return NULL;
/* Also curious about this function is that it accepts format strings
like "%xg", which are invalid for floats. In general, the
interface to this function is not very good, but changing it is
difficult because it's a public API. */
if (!(format_char == 'e' || format_char == 'E' ||
format_char == 'f' || format_char == 'F' ||
format_char == 'g' || format_char == 'G' ||
format_char == 'Z'))
return NULL;
/* Map 'Z' format_char to 'g', by copying the format string and
replacing the final char with a 'g' */
if (format_char == 'Z') {
if (format_len + 1 >= sizeof(tmp_format)) {
/* The format won't fit in our copy. Error out. In
practice, this will never happen and will be
detected by returning NULL */
return NULL;
}
strcpy(tmp_format, format);
tmp_format[format_len - 1] = 'g';
format = tmp_format;
}
/* Have PyOS_snprintf do the hard work */
PyOS_snprintf(buffer, buf_size, format, d);
/* Do various fixups on the return string */
/* Get the current locale, and find the decimal point string.
Convert that string back to a dot. */
change_decimal_from_locale_to_dot(buffer);
/* If an exponent exists, ensure that the exponent is at least
MIN_EXPONENT_DIGITS digits, providing the buffer is large enough
for the extra zeros. Also, if there are more than
MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get
back to MIN_EXPONENT_DIGITS */
ensure_minimum_exponent_length(buffer, buf_size);
/* If format_char is 'Z', make sure we have at least one character
after the decimal point (and make sure we have a decimal point);
also switch to exponential notation in some edge cases where the
extra character would produce more significant digits that we
really want. */
if (format_char == 'Z')
buffer = ensure_decimal_point(buffer, buf_size, precision);
return buffer;
}
/* The fallback code to use if _Py_dg_dtoa is not available. */
PyAPI_FUNC(char *) PyOS_double_to_string(double val,
char format_code,
int precision,
int flags,
int *type)
{
char format[32];
Py_ssize_t bufsize;
char *buf;
int t, exp;
int upper = 0;
/* Validate format_code, and map upper and lower case */
switch (format_code) {
case 'e': /* exponent */
case 'f': /* fixed */
case 'g': /* general */
break;
case 'E':
upper = 1;
format_code = 'e';
break;
case 'F':
upper = 1;
format_code = 'f';
break;
case 'G':
upper = 1;
format_code = 'g';
break;
case 'r': /* repr format */
/* Supplied precision is unused, must be 0. */
if (precision != 0) {
PyErr_BadInternalCall();
return NULL;
}
/* The repr() precision (17 significant decimal digits) is the
minimal number that is guaranteed to have enough precision
so that if the number is read back in the exact same binary
value is recreated. This is true for IEEE floating point
by design, and also happens to work for all other modern
hardware. */
precision = 17;
format_code = 'g';
break;
default:
PyErr_BadInternalCall();
return NULL;
}
/* Here's a quick-and-dirty calculation to figure out how big a buffer
we need. In general, for a finite float we need:
1 byte for each digit of the decimal significand, and
1 for a possible sign
1 for a possible decimal point
2 for a possible [eE][+-]
1 for each digit of the exponent; if we allow 19 digits
total then we're safe up to exponents of 2**63.
1 for the trailing nul byte
This gives a total of 24 + the number of digits in the significand,
and the number of digits in the significand is:
for 'g' format: at most precision, except possibly
when precision == 0, when it's 1.
for 'e' format: precision+1
for 'f' format: precision digits after the point, at least 1
before. To figure out how many digits appear before the point
we have to examine the size of the number. If fabs(val) < 1.0
then there will be only one digit before the point. If
fabs(val) >= 1.0, then there are at most
1+floor(log10(ceiling(fabs(val))))
digits before the point (where the 'ceiling' allows for the
possibility that the rounding rounds the integer part of val
up). A safe upper bound for the above quantity is
1+floor(exp/3), where exp is the unique integer such that 0.5
<= fabs(val)/2**exp < 1.0. This exp can be obtained from
frexp.
So we allow room for precision+1 digits for all formats, plus an
extra floor(exp/3) digits for 'f' format.
*/
if (Py_IS_NAN(val) || Py_IS_INFINITY(val))
/* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */
bufsize = 5;
else {
bufsize = 25 + precision;
if (format_code == 'f' && fabs(val) >= 1.0) {
frexp(val, &exp);
bufsize += exp/3;
}
}
buf = PyMem_Malloc(bufsize);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
/* Handle nan and inf. */
if (Py_IS_NAN(val)) {
strcpy(buf, "nan");
t = Py_DTST_NAN;
} else if (Py_IS_INFINITY(val)) {
if (copysign(1., val) == 1.)
strcpy(buf, "inf");
else
strcpy(buf, "-inf");
t = Py_DTST_INFINITE;
} else {
t = Py_DTST_FINITE;
if (flags & Py_DTSF_ADD_DOT_0)
format_code = 'Z';
PyOS_snprintf(format, sizeof(format), "%%%s.%i%c",
(flags & Py_DTSF_ALT ? "#" : ""), precision,
format_code);
_PyOS_ascii_formatd(buf, bufsize, format, val, precision);
}
/* Add sign when requested. It's convenient (esp. when formatting
complex numbers) to include a sign even for inf and nan. */
if (flags & Py_DTSF_SIGN && buf[0] != '-') {
size_t len = strlen(buf);
/* the bufsize calculations above should ensure that we've got
space to add a sign */
assert((size_t)bufsize >= len+2);
memmove(buf+1, buf, len+1);
buf[0] = '+';
}
if (upper) {
/* Convert to upper case. */
char *p1;
for (p1 = buf; *p1; p1++)
*p1 = Py_TOUPPER(*p1);
}
if (type)
*type = t;
return buf;
}
#else
/* _Py_dg_dtoa is available. */
/* I'm using a lookup table here so that I don't have to invent a non-locale
specific way to convert to uppercase */
#define OFS_INF 0
#define OFS_NAN 1
#define OFS_E 2
/* The lengths of these are known to the code below, so don't change them */
static const char * const lc_float_strings[] = {
"inf",
"nan",
"e",
};
static const char * const uc_float_strings[] = {
"INF",
"NAN",
"E",
};
/* Convert a double d to a string, and return a PyMem_Malloc'd block of
memory contain the resulting string.
Arguments:
d is the double to be converted
format_code is one of 'e', 'f', 'g', 'r'. 'e', 'f' and 'g'
correspond to '%e', '%f' and '%g'; 'r' corresponds to repr.
mode is one of '0', '2' or '3', and is completely determined by
format_code: 'e' and 'g' use mode 2; 'f' mode 3, 'r' mode 0.
precision is the desired precision
always_add_sign is nonzero if a '+' sign should be included for positive
numbers
add_dot_0_if_integer is nonzero if integers in non-exponential form
should have ".0" added. Only applies to format codes 'r' and 'g'.
use_alt_formatting is nonzero if alternative formatting should be
used. Only applies to format codes 'e', 'f' and 'g'. For code 'g',
at most one of use_alt_formatting and add_dot_0_if_integer should
be nonzero.
type, if non-NULL, will be set to one of these constants to identify
the type of the 'd' argument:
Py_DTST_FINITE
Py_DTST_INFINITE
Py_DTST_NAN
Returns a PyMem_Malloc'd block of memory containing the resulting string,
or NULL on error. If NULL is returned, the Python error has been set.
*/
static char *
format_float_short(double d, char format_code,
int mode, int precision,
int always_add_sign, int add_dot_0_if_integer,
int use_alt_formatting, const char * const *float_strings,
int *type)
{
char *buf = NULL;
char *p = NULL;
Py_ssize_t bufsize = 0;
char *digits, *digits_end;
int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0;
Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end;
_Py_SET_53BIT_PRECISION_HEADER;
/* _Py_dg_dtoa returns a digit string (no decimal point or exponent).
Must be matched by a call to _Py_dg_freedtoa. */
_Py_SET_53BIT_PRECISION_START;
digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign,
&digits_end);
_Py_SET_53BIT_PRECISION_END;
decpt = (Py_ssize_t)decpt_as_int;
if (digits == NULL) {
/* The only failure mode is no memory. */
PyErr_NoMemory();
goto exit;
}
assert(digits_end != NULL && digits_end >= digits);
digits_len = digits_end - digits;
if (digits_len && !Py_ISDIGIT(digits[0])) {
/* Infinities and nans here; adapt Gay's output,
so convert Infinity to inf and NaN to nan, and
ignore sign of nan. Then return. */
/* ignore the actual sign of a nan */
if (digits[0] == 'n' || digits[0] == 'N')
sign = 0;
/* We only need 5 bytes to hold the result "+inf\0" . */
bufsize = 5; /* Used later in an assert. */
buf = (char *)PyMem_Malloc(bufsize);
if (buf == NULL) {
PyErr_NoMemory();
goto exit;
}
p = buf;
if (sign == 1) {
*p++ = '-';
}
else if (always_add_sign) {
*p++ = '+';
}
if (digits[0] == 'i' || digits[0] == 'I') {
strncpy(p, float_strings[OFS_INF], 3);
p += 3;
if (type)
*type = Py_DTST_INFINITE;
}
else if (digits[0] == 'n' || digits[0] == 'N') {
strncpy(p, float_strings[OFS_NAN], 3);
p += 3;
if (type)
*type = Py_DTST_NAN;
}
else {
/* shouldn't get here: Gay's code should always return
something starting with a digit, an 'I', or 'N' */
strncpy(p, "ERR", 3);
/* p += 3; */
Py_UNREACHABLE();
}
goto exit;
}
/* The result must be finite (not inf or nan). */
if (type)
*type = Py_DTST_FINITE;
/* We got digits back, format them. We may need to pad 'digits'
either on the left or right (or both) with extra zeros, so in
general the resulting string has the form
[<sign>]<zeros><digits><zeros>[<exponent>]
where either of the <zeros> pieces could be empty, and there's a
decimal point that could appear either in <digits> or in the
leading or trailing <zeros>.
Imagine an infinite 'virtual' string vdigits, consisting of the
string 'digits' (starting at index 0) padded on both the left and
right with infinite strings of zeros. We want to output a slice
vdigits[vdigits_start : vdigits_end]
of this virtual string. Thus if vdigits_start < 0 then we'll end
up producing some leading zeros; if vdigits_end > digits_len there
will be trailing zeros in the output. The next section of code
determines whether to use an exponent or not, figures out the
position 'decpt' of the decimal point, and computes 'vdigits_start'
and 'vdigits_end'. */
vdigits_end = digits_len;
switch (format_code) {
case 'e':
use_exp = 1;
vdigits_end = precision;
break;
case 'f':
vdigits_end = decpt + precision;
break;
case 'g':
if (decpt <= -4 || decpt >
(add_dot_0_if_integer ? precision-1 : precision))
use_exp = 1;
if (use_alt_formatting)
vdigits_end = precision;
break;
case 'r':
/* convert to exponential format at 1e16. We used to convert
at 1e17, but that gives odd-looking results for some values
when a 16-digit 'shortest' repr is padded with bogus zeros.
For example, repr(2e16+8) would give 20000000000000010.0;
the true value is 20000000000000008.0. */
if (decpt <= -4 || decpt > 16)
use_exp = 1;
break;
default:
PyErr_BadInternalCall();
goto exit;
}
/* if using an exponent, reset decimal point position to 1 and adjust
exponent accordingly.*/
if (use_exp) {
exp = (int)decpt - 1;
decpt = 1;
}
/* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start <
decpt < vdigits_end if add_dot_0_if_integer and no exponent */
vdigits_start = decpt <= 0 ? decpt-1 : 0;
if (!use_exp && add_dot_0_if_integer)
vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1;
else
vdigits_end = vdigits_end > decpt ? vdigits_end : decpt;
/* double check inequalities */
assert(vdigits_start <= 0 &&
0 <= digits_len &&
digits_len <= vdigits_end);
/* decimal point should be in (vdigits_start, vdigits_end] */
assert(vdigits_start < decpt && decpt <= vdigits_end);
/* Compute an upper bound how much memory we need. This might be a few
chars too long, but no big deal. */
bufsize =
/* sign, decimal point and trailing 0 byte */
3 +
/* total digit count (including zero padding on both sides) */
(vdigits_end - vdigits_start) +
/* exponent "e+100", max 3 numerical digits */
(use_exp ? 5 : 0);
/* Now allocate the memory and initialize p to point to the start of
it. */
buf = (char *)PyMem_Malloc(bufsize);
if (buf == NULL) {
PyErr_NoMemory();
goto exit;
}
p = buf;
/* Add a negative sign if negative, and a plus sign if non-negative
and always_add_sign is true. */
if (sign == 1)
*p++ = '-';
else if (always_add_sign)
*p++ = '+';
/* note that exactly one of the three 'if' conditions is true,
so we include exactly one decimal point */
/* Zero padding on left of digit string */
if (decpt <= 0) {
memset(p, '0', decpt-vdigits_start);
p += decpt - vdigits_start;
*p++ = '.';
memset(p, '0', 0-decpt);
p += 0-decpt;
}
else {
memset(p, '0', 0-vdigits_start);
p += 0 - vdigits_start;
}
/* Digits, with included decimal point */
if (0 < decpt && decpt <= digits_len) {
strncpy(p, digits, decpt-0);
p += decpt-0;
*p++ = '.';
strncpy(p, digits+decpt, digits_len-decpt);
p += digits_len-decpt;
}
else {
strncpy(p, digits, digits_len);
p += digits_len;
}
/* And zeros on the right */
if (digits_len < decpt) {
memset(p, '0', decpt-digits_len);
p += decpt-digits_len;
*p++ = '.';
memset(p, '0', vdigits_end-decpt);
p += vdigits_end-decpt;
}
else {
memset(p, '0', vdigits_end-digits_len);
p += vdigits_end-digits_len;
}
/* Delete a trailing decimal pt unless using alternative formatting. */
if (p[-1] == '.' && !use_alt_formatting)
p--;
/* Now that we've done zero padding, add an exponent if needed. */
if (use_exp) {
*p++ = float_strings[OFS_E][0];
exp_len = sprintf(p, "%+.02d", exp);
p += exp_len;
}
exit:
if (buf) {
*p = '\0';
/* It's too late if this fails, as we've already stepped on
memory that isn't ours. But it's an okay debugging test. */
assert(p-buf < bufsize);
}
if (digits)
_Py_dg_freedtoa(digits);
return buf;
}
PyAPI_FUNC(char *) PyOS_double_to_string(double val,
char format_code,
int precision,
int flags,
int *type)
{
const char * const *float_strings = lc_float_strings;
int mode;
/* Validate format_code, and map upper and lower case. Compute the
mode and make any adjustments as needed. */
switch (format_code) {
/* exponent */
case 'E':
float_strings = uc_float_strings;
format_code = 'e';
/* Fall through. */
case 'e':
mode = 2;
precision++;
break;
/* fixed */
case 'F':
float_strings = uc_float_strings;
format_code = 'f';
/* Fall through. */
case 'f':
mode = 3;
break;
/* general */
case 'G':
float_strings = uc_float_strings;
format_code = 'g';
/* Fall through. */
case 'g':
mode = 2;
/* precision 0 makes no sense for 'g' format; interpret as 1 */
if (precision == 0)
precision = 1;
break;
/* repr format */
case 'r':
mode = 0;
/* Supplied precision is unused, must be 0. */
if (precision != 0) {
PyErr_BadInternalCall();
return NULL;
}
break;
default:
PyErr_BadInternalCall();
return NULL;
}
return format_float_short(val, format_code, mode, precision,
flags & Py_DTSF_SIGN,
flags & Py_DTSF_ADD_DOT_0,
flags & Py_DTSF_ALT,
float_strings, type);
}
#endif /* ifdef PY_NO_SHORT_FLOAT_REPR */