Skip to content

Commit f453221

Browse files
authored
bpo-40602: Add _Py_HashPointerRaw() function (GH-20056)
Add a new _Py_HashPointerRaw() function which avoids replacing -1 with -2 to micro-optimize hash table using pointer keys: using _Py_hashtable_hash_ptr() hash function.
1 parent 4c9ea09 commit f453221

File tree

3 files changed

+13
-5
lines changed

3 files changed

+13
-5
lines changed

Include/pyhash.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ extern "C" {
99
#ifndef Py_LIMITED_API
1010
PyAPI_FUNC(Py_hash_t) _Py_HashDouble(double);
1111
PyAPI_FUNC(Py_hash_t) _Py_HashPointer(const void*);
12+
// Similar to _Py_HashPointer(), but don't replace -1 with -2
13+
PyAPI_FUNC(Py_hash_t) _Py_HashPointerRaw(const void*);
1214
PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void*, Py_ssize_t);
1315
#endif
1416

Python/hashtable.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ _Py_hashtable_hash_ptr(struct _Py_hashtable_t *ht, const void *pkey)
109109
{
110110
void *key;
111111
_Py_HASHTABLE_READ_KEY(ht, pkey, key);
112-
return (Py_uhash_t)_Py_HashPointer(key);
112+
return (Py_uhash_t)_Py_HashPointerRaw(key);
113113
}
114114

115115

Python/pyhash.c

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,16 +129,22 @@ _Py_HashDouble(double v)
129129
}
130130

131131
Py_hash_t
132-
_Py_HashPointer(const void *p)
132+
_Py_HashPointerRaw(const void *p)
133133
{
134-
Py_hash_t x;
135134
size_t y = (size_t)p;
136135
/* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
137136
excessive hash collisions for dicts and sets */
138137
y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
139-
x = (Py_hash_t)y;
140-
if (x == -1)
138+
return (Py_hash_t)y;
139+
}
140+
141+
Py_hash_t
142+
_Py_HashPointer(const void *p)
143+
{
144+
Py_hash_t x = _Py_HashPointerRaw(p);
145+
if (x == -1) {
141146
x = -2;
147+
}
142148
return x;
143149
}
144150

0 commit comments

Comments
 (0)