Skip to content

Commit ea0c6ab

Browse files
committed
Cache hash code
1 parent 1e0cb77 commit ea0c6ab

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

src/cstring.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,16 @@
22

33
struct cstring {
44
PyObject_VAR_HEAD
5+
Py_hash_t hash;
56
char value[];
67
};
78

9+
#define CSTRING_HASH(self) (((struct cstring *)self)->hash)
810
#define CSTRING_VALUE(self) (((struct cstring *)self)->value)
911

1012
static PyObject *_cstring_new(PyTypeObject *type, const char *value, size_t len) {
1113
struct cstring *new = type->tp_alloc(type, len + 1);
14+
new->hash = -1;
1215
memcpy(new->value, value, len);
1316
new->value[len] = '\0';
1417
return (PyObject *)new;
@@ -43,7 +46,9 @@ static PyObject *cstring_str(PyObject *self) {
4346
}
4447

4548
static Py_hash_t cstring_hash(PyObject *self) {
46-
return _Py_HashBytes(CSTRING_VALUE(self), Py_SIZE(self));
49+
if(CSTRING_HASH(self) == -1)
50+
CSTRING_HASH(self) = _Py_HashBytes(CSTRING_VALUE(self), Py_SIZE(self));
51+
return CSTRING_HASH(self);
4752
}
4853

4954
static PyObject *cstring_richcompare(PyObject *self, PyObject *other, int op) {

0 commit comments

Comments
 (0)