From 8e29a024c6f48d3a15c679ee8d1b9555dcea8b4f Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Sun, 3 Dec 2023 12:05:08 +0100 Subject: [PATCH] Return 1 if NaN, 0 otherwise --- Doc/c-api/hash.rst | 8 ++++---- Lib/test/test_capi/test_hash.py | 7 +++++-- Python/pyhash.c | 8 ++++---- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/Doc/c-api/hash.rst b/Doc/c-api/hash.rst index 190a726958438d9..fd12d6204f0e057 100644 --- a/Doc/c-api/hash.rst +++ b/Doc/c-api/hash.rst @@ -52,16 +52,16 @@ Functions Hash a C double number. - * Set *\*result* to the hash and return ``1`` if *value* is finite or is + * Set *\*result* to the hash and return ``0`` if *value* is finite or is infinity. * Set *\*result* to :data:`sys.hash_info.nan ` (``0``) and - return ``0`` if *value* is not-a-number (NaN). + return ``1`` if *value* is not-a-number (NaN). *result* must not be ``NULL``. .. note:: - Only rely on the function return value to distinguish the "not-a-number" - case. *\*result* can be ``0`` if *value* is finite. For example, + Only rely on the function return value to distinguish the not-a-number + (NaN) case. *\*result* can be ``0`` if *value* is finite. For example, ``Py_HashDouble(0.0, &result)`` sets *\*result* to 0. .. versionadded:: 3.13 diff --git a/Lib/test/test_capi/test_hash.py b/Lib/test/test_capi/test_hash.py index 68bdcd8ccf0469e..7d2c6c437044312 100644 --- a/Lib/test/test_capi/test_hash.py +++ b/Lib/test/test_capi/test_hash.py @@ -35,10 +35,13 @@ def test_hash_getfuncdef(self): def test_hash_double(self): # Test Py_HashDouble() + # + # _Py_HashDouble() is tested indirectly by test_float in test_hash() + # and test_hash_nan(). hash_double = _testcapi.hash_double def check_number(value, expected): - self.assertEqual(hash_double(value), (1, expected)) + self.assertEqual(hash_double(value), (0, expected)) # test some integers integers = [ @@ -74,4 +77,4 @@ def check_number(value, expected): check_number(-x, hash(-x)) # test not-a-number (NaN) - self.assertEqual(hash_double(float('nan')), (0, sys.hash_info.nan)) + self.assertEqual(hash_double(float('nan')), (1, sys.hash_info.nan)) diff --git a/Python/pyhash.c b/Python/pyhash.c index 6fa79d08c288213..d43bb39985985dd 100644 --- a/Python/pyhash.c +++ b/Python/pyhash.c @@ -95,12 +95,12 @@ Py_HashDouble(double v, Py_hash_t *result) if (!Py_IS_FINITE(v)) { if (Py_IS_INFINITY(v)) { *result = (v > 0 ? _PyHASH_INF : -_PyHASH_INF); - return 1; + return 0; } else { assert(Py_IS_NAN(v)); *result = _PyHASH_NAN; - return 0; + return 1; } } @@ -134,7 +134,7 @@ Py_HashDouble(double v, Py_hash_t *result) if (x == (Py_uhash_t)-1) x = (Py_uhash_t)-2; *result = (Py_hash_t)x; - return 1; + return 0; } Py_hash_t @@ -143,7 +143,7 @@ _Py_HashDouble(PyObject *obj, double v) assert(obj != NULL); Py_hash_t hash; - if (Py_HashDouble(v, &hash) == 0) { + if (Py_HashDouble(v, &hash) == 1) { hash = _Py_HashPointer(obj); } return hash;