Skip to content

Commit

Permalink
Add tests and update logic
Browse files Browse the repository at this point in the history
  • Loading branch information
srinivasreddy committed Dec 9, 2024
1 parent aa6684b commit bf3ace9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
2 changes: 1 addition & 1 deletion Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ def test_fromhex(self):
self.assertRaises(ValueError, self.type2test.fromhex, '12 \x00 34')

# For odd number of character(s)
for value in ("a", "a ", " a"," a ", "a a a", "a a a ", " a a a", " a a a "):
for value in ("a", "a ", " a"," a ", "a a a", "aa a ", " aa a", " aaa "):
with self.assertRaises(ValueError) as cm:
self.type2test.fromhex(value)
self.assertIn("fromhex() arg must be of even length", str(cm.exception))
Expand Down
20 changes: 11 additions & 9 deletions Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2541,6 +2541,14 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
}
str++;

/* Check if we have a second digit*/
if (str >= end) {
PyErr_SetString(PyExc_ValueError,
"fromhex() arg must be of even length");
_PyBytesWriter_Dealloc(&writer);
return NULL;
}

bot = _PyLong_DigitValue[*str];
if (bot >= 16) {
invalid_char = str - PyUnicode_1BYTE_DATA(string);
Expand All @@ -2554,15 +2562,9 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
return _PyBytesWriter_Finish(&writer, buf);

error:
if (str >= end) {
PyErr_SetString(PyExc_ValueError,
"fromhex() arg must be of even length");
}
else {
PyErr_Format(PyExc_ValueError,
"non-hexadecimal number found in "
"fromhex() arg at position %zd", invalid_char);
}
PyErr_Format(PyExc_ValueError,
"non-hexadecimal number found in "
"fromhex() arg at position %zd", invalid_char);
_PyBytesWriter_Dealloc(&writer);
return NULL;
}
Expand Down

0 comments on commit bf3ace9

Please sign in to comment.