summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorTim Peters <tim.peters@gmail.com>2003-01-28 20:37:45 (GMT)
committerTim Peters <tim.peters@gmail.com>2003-01-28 20:37:45 (GMT)
commitbaefd9e552723c6489c69cf5df93f82b473550a2 (patch)
tree25300bbc824f4b60c7c7ac1a352d9246ab0e2169 /Objects
parent3d8c01b31c1a58d2181f78c5df2b0e79131046c0 (diff)
downloadcpython-baefd9e552723c6489c69cf5df93f82b473550a2.zip
cpython-baefd9e552723c6489c69cf5df93f82b473550a2.tar.gz
cpython-baefd9e552723c6489c69cf5df93f82b473550a2.tar.bz2
Added new private API function _PyLong_NumBits. This will be used at the
start for the C implemention of new pickle LONG1 and LONG4 opcodes (the linear-time way to pickle a long is to call _PyLong_AsByteArray, but the caller has no idea how big an array to allocate, and correct calculation is a bit subtle).
Diffstat (limited to 'Objects')
-rw-r--r--Objects/longobject.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/Objects/longobject.c b/Objects/longobject.c
index cb27e79..1180ec2 100644
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -260,6 +260,41 @@ PyLong_AsUnsignedLong(PyObject *vv)
return x;
}
+size_t
+_PyLong_NumBits(PyObject *vv)
+{
+ PyLongObject *v = (PyLongObject *)vv;
+ size_t result = 1; /* for the sign bit */
+ size_t ndigits = ABS(v->ob_size);
+
+ assert(v != NULL);
+ assert(PyLong_Check(v));
+ assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
+ if (ndigits > 0) {
+ size_t product;
+ digit msd = v->ob_digit[ndigits - 1];
+
+ product = (ndigits - 1) * SHIFT;
+ if (product / SHIFT != ndigits - 1)
+ goto Overflow;
+ result += product;
+ if (result < product)
+ goto Overflow;
+ do {
+ ++result;
+ if (result == 0)
+ goto Overflow;
+ msd >>= 1;
+ } while (msd);
+ }
+ return result;
+
+Overflow:
+ PyErr_SetString(PyExc_OverflowError, "long has too many bits "
+ "to express in a platform size_t");
+ return (size_t)-1;
+}
+
PyObject *
_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
int little_endian, int is_signed)