Skip to content

Commit d63600c

Browse files
committed
fix: use _get_buffer_or_str in update() for consistent str error
update() now raises 'Strings must be encoded before hashing' for str input, matching hashlib exactly and consistent with one-shot functions and constructors.
1 parent 62b1b8f commit d63600c

2 files changed

Lines changed: 14 additions & 5 deletions

File tree

src/_xxhash.c

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -578,11 +578,13 @@ PyDoc_STRVAR(
578578
static PyObject *PYXXH32_update(PYXXH32Object *self, PyObject *arg)
579579
{
580580
Py_buffer buf;
581+
PyObject *buf_owner;
581582

582-
if (PyObject_GetBuffer(arg, &buf, PyBUF_SIMPLE) < 0)
583+
if (_get_buffer_or_str(arg, &buf, &buf_owner) < 0)
583584
return NULL;
584585

585586
PYXXH32_do_update(self, &buf);
587+
Py_XDECREF(buf_owner);
586588

587589
Py_RETURN_NONE;
588590
}
@@ -931,11 +933,13 @@ PyDoc_STRVAR(
931933
static PyObject *PYXXH64_update(PYXXH64Object *self, PyObject *arg)
932934
{
933935
Py_buffer buf;
936+
PyObject *buf_owner;
934937

935-
if (PyObject_GetBuffer(arg, &buf, PyBUF_SIMPLE) < 0)
938+
if (_get_buffer_or_str(arg, &buf, &buf_owner) < 0)
936939
return NULL;
937940

938941
PYXXH64_do_update(self, &buf);
942+
Py_XDECREF(buf_owner);
939943

940944
Py_RETURN_NONE;
941945
}
@@ -1283,11 +1287,13 @@ PyDoc_STRVAR(
12831287
static PyObject *PYXXH3_64_update(PYXXH3_64Object *self, PyObject *arg)
12841288
{
12851289
Py_buffer buf;
1290+
PyObject *buf_owner;
12861291

1287-
if (PyObject_GetBuffer(arg, &buf, PyBUF_SIMPLE) < 0)
1292+
if (_get_buffer_or_str(arg, &buf, &buf_owner) < 0)
12881293
return NULL;
12891294

12901295
PYXXH3_64_do_update(self, &buf);
1296+
Py_XDECREF(buf_owner);
12911297

12921298
Py_RETURN_NONE;
12931299
}
@@ -1644,11 +1650,13 @@ PyDoc_STRVAR(
16441650
static PyObject *PYXXH3_128_update(PYXXH3_128Object *self, PyObject *arg)
16451651
{
16461652
Py_buffer buf;
1653+
PyObject *buf_owner;
16471654

1648-
if (PyObject_GetBuffer(arg, &buf, PyBUF_SIMPLE) < 0)
1655+
if (_get_buffer_or_str(arg, &buf, &buf_owner) < 0)
16491656
return NULL;
16501657

16511658
PYXXH3_128_do_update(self, &buf);
1659+
Py_XDECREF(buf_owner);
16521660

16531661
Py_RETURN_NONE;
16541662
}

tests/test_hashlib_compat.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ def test_str_rejected_constructor(self):
3535
def test_str_rejected_update(self):
3636
for algo in ('xxh32', 'xxh64', 'xxh3_64', 'xxh3_128'):
3737
obj = getattr(xxhash, algo)()
38-
with self.assertRaises(TypeError):
38+
with self.assertRaisesRegex(TypeError,
39+
'Strings must be encoded before hashing'):
3940
obj.update('hello')
4041

4142
# ── data keyword ───────────────────────────────────────────────

0 commit comments

Comments
 (0)