Skip to content

Commit 1e0cb77

Browse files
committed
Implement hash function
1 parent 84a8506 commit 1e0cb77

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/cstring.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ static PyObject *cstring_str(PyObject *self) {
4242
return PyUnicode_FromString(CSTRING_VALUE(self));
4343
}
4444

45+
static Py_hash_t cstring_hash(PyObject *self) {
46+
return _Py_HashBytes(CSTRING_VALUE(self), Py_SIZE(self));
47+
}
48+
4549
static PyObject *cstring_richcompare(PyObject *self, PyObject *other, int op) {
4650
if(!_ensure_cstring(other))
4751
return NULL;
@@ -143,6 +147,7 @@ static PyTypeObject cstring_type = {
143147
.tp_dealloc = cstring_dealloc,
144148
.tp_richcompare = cstring_richcompare,
145149
.tp_str = cstring_str,
150+
.tp_hash = cstring_hash,
146151
.tp_as_sequence = &cstring_as_sequence,
147152
};
148153

test/test_cstring.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,13 @@ def test_str():
77
assert str(result) == 'hello, world'
88

99

10+
def test_hash():
11+
a = cstring('hello')
12+
b = cstring('hello')
13+
assert a is not b
14+
assert set((a, b)) == set((a,)) == set((b,))
15+
16+
1017
# Rich Compare
1118

1219

0 commit comments

Comments
 (0)