Commit 5c7ade92 authored by Tim Peters's avatar Tim Peters

_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.
parent a833a35f
...@@ -308,26 +308,27 @@ unpack_double(const char *p, /* start of 8-byte string */ ...@@ -308,26 +308,27 @@ unpack_double(const char *p, /* start of 8-byte string */
static int static int
_range_error(const formatdef *f, int is_unsigned) _range_error(const formatdef *f, int is_unsigned)
{ {
if (is_unsigned == 0) { /* ulargest is the largest unsigned value with f->size bytes.
Py_ssize_t smallest, largest = 0; * Note that the simpler:
Py_ssize_t i = f->size * 8; * ((size_t)1 << (f->size * 8)) - 1
while (--i > 0) { * doesn't work when f->size == size_t because C doesn't define what
largest = (largest * 2) + 1; * happens when a left shift count is >= the number of bits in the
} * integer being shifted; e.g., on some boxes it doesn't shift at
smallest = -largest - 1; * all when they're equal.
*/
const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
if (is_unsigned)
PyErr_Format(StructError, PyErr_Format(StructError,
"'%c' format requires %zd <= number <= %zd", "'%c' format requires 0 <= number <= %zu",
f->format, f->format,
smallest, ulargest);
largest); else {
} else { const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
size_t largest = 0;
Py_ssize_t i = f->size * 8;
while (--i >= 0)
largest = (largest * 2) + 1;
PyErr_Format(StructError, PyErr_Format(StructError,
"'%c' format requires 0 <= number <= %zu", "'%c' format requires %zd <= number <= %zd",
f->format, f->format,
~ largest,
largest); largest);
} }
#ifdef PY_STRUCT_OVERFLOW_MASKING #ifdef PY_STRUCT_OVERFLOW_MASKING
...@@ -343,7 +344,8 @@ _range_error(const formatdef *f, int is_unsigned) ...@@ -343,7 +344,8 @@ _range_error(const formatdef *f, int is_unsigned)
Py_XDECREF(ptraceback); Py_XDECREF(ptraceback);
if (msg == NULL) if (msg == NULL)
return -1; return -1;
rval = PyErr_Warn(PyExc_DeprecationWarning, PyString_AS_STRING(msg)); rval = PyErr_Warn(PyExc_DeprecationWarning,
PyString_AS_STRING(msg));
Py_DECREF(msg); Py_DECREF(msg);
if (rval == 0) if (rval == 0)
return 0; return 0;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment