]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-127740: For odd-length input to bytes.fromhex(...) change the error message to...
authorSrinivas Reddy Thatiparthy (తాటిపర్తి శ్రీనివాస్ రెడ్డి) <thatiparthysreenivas@gmail.com>
Wed, 11 Dec 2024 07:35:17 +0000 (13:05 +0530)
committerGitHub <noreply@github.com>
Wed, 11 Dec 2024 07:35:17 +0000 (08:35 +0100)
Lib/test/test_bytes.py
Misc/NEWS.d/next/Core_and_Builtins/2024-12-10-21-08-05.gh-issue-127740.0tWC9h.rst [new file with mode: 0644]
Objects/bytesobject.c

index 9e1985bb3a7639d5b641c4cada6064881358802a..32cd178fa3b445ab08cfc7713e802ef80130d88b 100644 (file)
@@ -459,6 +459,12 @@ class BaseBytesTest:
         self.assertRaises(ValueError, self.type2test.fromhex, '\x00')
         self.assertRaises(ValueError, self.type2test.fromhex, '12   \x00   34')
 
+        # For odd number of character(s)
+        for value in ("a", "aaa", "deadbee"):
+            with self.assertRaises(ValueError) as cm:
+                self.type2test.fromhex(value)
+            self.assertIn("fromhex() arg must contain an even number of hexadecimal digits", str(cm.exception))
+
         for data, pos in (
             # invalid first hexadecimal character
             ('12 x4 56', 3),
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-12-10-21-08-05.gh-issue-127740.0tWC9h.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-12-10-21-08-05.gh-issue-127740.0tWC9h.rst
new file mode 100644 (file)
index 0000000..f614dbb
--- /dev/null
@@ -0,0 +1,3 @@
+Fix error message in :func:`bytes.fromhex` when given an odd number of
+digits to properly indicate that an even number of hexadecimal digits is
+required.
index 8c7651f0f3aa4576b19f3bb64a1d5fef2516e78b..533089d25cd73a6b26968007ea886fef2eb72006 100644 (file)
@@ -2543,7 +2543,12 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
 
         bot = _PyLong_DigitValue[*str];
         if (bot >= 16) {
-            invalid_char = str - PyUnicode_1BYTE_DATA(string);
+            /* Check if we had a second digit */
+            if (str >= end){
+                invalid_char = -1;
+            } else {
+                invalid_char = str - PyUnicode_1BYTE_DATA(string);
+            }
             goto error;
         }
         str++;
@@ -2554,9 +2559,14 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
     return _PyBytesWriter_Finish(&writer, buf);
 
   error:
-    PyErr_Format(PyExc_ValueError,
-                 "non-hexadecimal number found in "
-                 "fromhex() arg at position %zd", invalid_char);
+    if (invalid_char == -1) {
+        PyErr_SetString(PyExc_ValueError,
+                        "fromhex() arg must contain an even number of hexadecimal digits");
+    } else {
+        PyErr_Format(PyExc_ValueError,
+                     "non-hexadecimal number found in "
+                     "fromhex() arg at position %zd", invalid_char);
+    }
     _PyBytesWriter_Dealloc(&writer);
     return NULL;
 }