Skip to content

Commit

Permalink
Add value range check for seed
Browse files Browse the repository at this point in the history
  • Loading branch information
hajimes committed Sep 17, 2024
1 parent 1b3f19b commit 2ad4331
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/mmh3/mmh3module.c
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,18 @@ typedef unsigned __int64 uint64_t;
Py_TYPE(args[1])->tp_name); \
return NULL; \
} \
seed = (uint32_t)PyLong_AsUnsignedLong(args[1]); \
if (seed == (unsigned long)-1 && PyErr_Occurred()) { \
const unsigned long seed_tmp = PyLong_AsUnsignedLong(args[1]); \
if (seed_tmp == -1 && PyErr_Occurred()) { \
if (PyErr_ExceptionMatches(PyExc_OverflowError)) { \
PyErr_SetString(PyExc_ValueError, "seed is out of range"); \
return NULL; \
} \
} \
if (seed_tmp > 0xFFFFFFFF) { \
PyErr_SetString(PyExc_ValueError, "seed is out of range"); \
return NULL; \
} \
seed = (uint32_t)seed_tmp; \
}

//-----------------------------------------------------------------------------
Expand Down
24 changes: 24 additions & 0 deletions tests/test_invalid_inputs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# pylint: disable=missing-module-docstring, missing-function-docstring
# pylint: disable=no-value-for-parameter, too-many-function-args
import mmh3
import pytest


def test_mmh3_32_digest_raises_typeerror() -> None:
with pytest.raises(TypeError):
mmh3.mmh3_32_digest()
with pytest.raises(TypeError):
mmh3.mmh3_32_digest(b"hello, world", 42, 1234)
with pytest.raises(TypeError):
mmh3.mmh3_32_digest("hello, world")
with pytest.raises(TypeError):
mmh3.mmh3_32_digest(b"hello, world", "42")
with pytest.raises(TypeError):
mmh3.mmh3_32_digest([1, 2, 3], 42)


def test_mmh3_32_digest_raises_valueerror() -> None:
with pytest.raises(ValueError):
mmh3.mmh3_32_digest(b"hello, world", -1)
with pytest.raises(ValueError):
mmh3.mmh3_32_digest(b"hello, world", 2**32)
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ description = run unit tests
commands_pre =
pip install ".[test]"
commands =
pytest
pytest {posargs}

[testenv:lint]
description = run linters with formatting
Expand Down

0 comments on commit 2ad4331

Please sign in to comment.