Skip to content

Commit

Permalink
pythongh-127740: For odd-length input to bytes.fromhex(...) change th…
Browse files Browse the repository at this point in the history
…e error message to ValueError: fromhex() arg must be of even length
  • Loading branch information
srinivasreddy committed Dec 9, 2024
1 parent 2041a95 commit b5b0da7
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 5 additions & 0 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,11 @@ def test_fromhex(self):
self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')

# For odd number of character(s)
with self.assertRaises(ValueError) as cm:
self.type2test.fromhex("a")
self.assertIn("fromhex() arg must be of even length", str(cm.exception))

for data, pos in (
# invalid first hexadecimal character
('12 x4 56', 3),
Expand Down
15 changes: 14 additions & 1 deletion Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2490,7 +2490,7 @@ PyObject*
_PyBytes_FromHex(PyObject *string, int use_bytearray)
{
char *buf;
Py_ssize_t hexlen, invalid_char;
Py_ssize_t hexlen, invalid_char,real_len=0;
unsigned int top, bot;
const Py_UCS1 *str, *end;
_PyBytesWriter writer;
Expand All @@ -2516,6 +2516,19 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
}

assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND);

const Py_UCS1 *s = PyUnicode_1BYTE_DATA(string);
for (Py_ssize_t i = 0; i < hexlen; i++) {
if (!Py_ISSPACE(s[i])) {
real_len++;
}
}
if (real_len % 2 != 0) {
PyErr_SetString(PyExc_ValueError,
"fromhex() arg must be of even length");
_PyBytesWriter_Dealloc(&writer);
return NULL;
}
str = PyUnicode_1BYTE_DATA(string);

/* This overestimates if there are spaces */
Expand Down

0 comments on commit b5b0da7

Please sign in to comment.