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

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

index ca7a8f38c0b4ec9b866a16c3f7ff0ecd23c7b1cb..f3bdbe29c4f2b56f49d8f5d823bb577d770c0a97 100644 (file)
@@ -116,6 +116,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 61ccad6f3450835ebc6c317805fd694cf37f2baa..e71be104e9f5785d044708de64f29f85b816099c 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,9 @@ What's New in Python 2.5.1c1?
 Core and builtins
 -----------------
 
+- Integer negation and absolute value were fixed to not rely
+  on undefined behaviour of the C compiler anymore.
+
 - Bug #1566800: make sure that EnvironmentError can be called with any
   number of arguments, as was the case in Python 2.4.
 
index b94e3e988707031b81b16de577d92346c2315ec8..28f760671078ee6699f3ee51e55f4a376cefdc26 100644 (file)
@@ -760,10 +760,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);
@@ -772,7 +771,7 @@ int_neg(PyIntObject *v)
                }
                return NULL;
        }
-       return PyInt_FromLong(x);
+       return PyInt_FromLong(-a);
 }
 
 static PyObject *