]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Fix integer negation and absolute value to not rely
authorMartin v. Löwis <martin@v.loewis.de>
Wed, 4 Oct 2006 05:48:05 +0000 (05:48 +0000)
committerMartin v. Löwis <martin@v.loewis.de>
Wed, 4 Oct 2006 05:48:05 +0000 (05:48 +0000)
on undefined behaviour of the C compiler anymore.

Lib/test/test_builtin.py
Misc/NEWS
Objects/intobject.c

index 2389e1be52eab0db9c4f2c2d443a3cbef38fd8aa..f8a5047113b92f4c1b923fdb9e3a8a4848920cb8 100644 (file)
@@ -101,6 +101,7 @@ class BuiltinTest(unittest.TestCase):
         self.assertEqual(abs(0), 0)
         self.assertEqual(abs(1234), 1234)
         self.assertEqual(abs(-1234), 1234)
+        self.assertTrue(abs(-sys.maxint-1) > 0)
         # float
         self.assertEqual(abs(0.0), 0.0)
         self.assertEqual(abs(3.14), 3.14)
index 2a6145c72c0c6591f9897d5891008ba3ccbf1ef0..e505a3210969d338c3214f0bbec84c4e2e7ec63c 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,9 @@ What's New in Python 2.4.4c1?
 Core and builtins
 -----------------
 
+- Integer negation and absolute value were fixed to not rely
+  on undefined behaviour of the C compiler anymore.
+
 - Patch #1567691: super() and new.instancemethod() now don't accept
   keyword arguments any more (previously they accepted them, but didn't
   use them).
index 1a7e2f7c8610a9af5a8acf3ebb2482364736d42e..579fe7dcbfc118f3620eedac54262fc20a608775 100644 (file)
@@ -674,10 +674,9 @@ int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
 static PyObject *
 int_neg(PyIntObject *v)
 {
-       register long a, x;
+       register long a;
        a = v->ob_ival;
-       x = -a;
-       if (a < 0 && x < 0) {
+       if (a < 0 && (unsigned long)a == 0-(unsigned long)a) {
                PyObject *o = PyLong_FromLong(a);
                if (o != NULL) {
                        PyObject *result = PyNumber_Negative(o);
@@ -686,7 +685,7 @@ int_neg(PyIntObject *v)
                }
                return NULL;
        }
-       return PyInt_FromLong(x);
+       return PyInt_FromLong(-a);
 }
 
 static PyObject *