Skip to content

Commit

Permalink
Return 1 if NaN, 0 otherwise
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Dec 3, 2023
1 parent 2253114 commit 8e29a02
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
8 changes: 4 additions & 4 deletions Doc/c-api/hash.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sys.hash_info>` (``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
Expand Down
7 changes: 5 additions & 2 deletions Lib/test/test_capi/test_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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))
8 changes: 4 additions & 4 deletions Python/pyhash.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down

0 comments on commit 8e29a02

Please sign in to comment.