8000 gh-129349: Accept bytes in bytes.fromhex()/bytearray.fromhex() by lordmauve · Pull Request #129844 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-129349: Accept bytes in bytes.fromhex()/bytearray.fromhex() #129844

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 12, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use buffer protocol to support all byte-like objects
  • Loading branch information
lordmauve committed Mar 12, 2025
commit b0e3eb557a1a7c68ae38c5017290ed024016fbe9
4 changes: 2 additions & 2 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2746,7 +2746,7 @@ data and are closely related to string objects in a variety of other ways.

.. versionchanged:: next
:meth:`bytes.fromhex` now accepts ASCII :class:`bytes` and
:class:`bytearray` objects as input.
:term:`bytes-like objects <bytes-like object>` as input.



Expand Down Expand Up @@ -2837,7 +2837,7 @@ objects.

.. versionchanged:: next
:meth:`bytearray.fromhex` now accepts ASCII :class:`bytes` and
:class:`bytearray` objects as input.
:term:`bytes-like objects <bytes-like object>` as input.

A reverse conversion function exists to transform a bytearray object into its
hexadecimal representation.
Expand Down
2 changes: 1 addition & 1 deletion Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ Other language changes
(Contrubuted by Sergey B Kirpichev in :gh:`87790`.)

* The :func:`bytes.fromhex` and :func:`bytearray.fromhex` methods now accept
ASCII :class:`bytes` and :class:`bytearray` objects.
ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: are bytes also bytes-like objects? if so, you can just link the term. Or more generally, isn't it objects that support the buffer protocol?

8000 Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but it seems less accessible to users to just link bytes-like object because that dives into a description of the buffer protocol which is lower level than the audience I was writing for in builtins docs.

Maybe the fault is with :term:\bytes-like object`` because it could just list types that duck-type like bytes.

So I hedged and did both.

Copy link
Member
@picnixz picnixz Mar 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could sa "that support the buffer protocol such as memoryviews" and add a link to whatever example of a type that supports the buffer protocol you used

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to say "bytes and bytes-like", it's more explicit.

(Contributed by Daniel Pope in :gh:`129349`.)

* ``\B`` in :mod:`regular expression <re>` now matches empty input string.
Expand Down
15 changes: 10 additions & 5 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,11 +457,16 @@ def test_fromhex(self):
self.assertRaises(ValueError, self.type2test.fromhex, c)

# Check that we can parse bytes and bytearray
self.assertEqual(self.type2test.fromhex(b' 012abc'), b'\x01\x2a\xbc')
self.assertEqual(
self.type2test.fromhex(bytearray(b' 012abc')),
b'\x01\x2a\xbc',
)
tests = [
("bytes", bytes),
("bytearray", bytearray),
("memoryview", memoryview),
("array.array", lambda bs: array.array('B', bs)),
]
for name, factory in tests:
with self.subTest(name=name):
self.assertEqual(self.type2test.fromhex(factory(b' 1A 2B 30 ')), b)

# Invalid bytes are rejected
for u8 in b"\0\x1C\x1D\x1E\x1F\x85\xa0":
b = bytes([30, 31, u8])
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
:meth:`bytes.fromhex` and :meth:`bytearray.fromhex` now accepts ASCII
:class:`bytes`/:class:`bytearray` objects.
:class:`bytes` and :term:`bytes-like objects <bytes-like object>`.
27 changes: 18 additions & 9 deletions Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2512,6 +2512,8 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
unsigned int t 6D40 op, bot;
const Py_UCS1 *str, *start, *end;
_PyBytesWriter writer;
Py_buffer view;
view.obj = NULL;

_PyBytesWriter_Init(&writer);
writer.use_bytearray = use_bytearray;
Expand All @@ -2534,15 +2536,13 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
}

assert(PyUnicode_KIND(string) == PyUnicode_1BYTE_KIND);
str = start = PyUnicode_1BYTE_DATA(string);
}
else if (PyBytes_Check(string)) {
hexlen = PyBytes_GET_SIZE(string);
str = start = (Py_UCS1 *)PyBytes_AS_STRING(string);
str = PyUnicode_1BYTE_DATA(string);
}
else if (PyByteArray_Check(string)) {
hexlen = PyByteArray_GET_SIZE(string);
str = start = (Py_UCS1 *)PyByteArray_AS_STRING(string);
else if (PyObject_CheckBuffer(string)) {
if (PyObject_GetBuffer(string, &view, PyBUF_SIMPLE) != 0)
return NULL;
hexlen = view.len;
str = view.buf;
}
else {
PyErr_Format(PyExc_TypeError,
Expand All @@ -2554,8 +2554,9 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
/* This overestimates if there are spaces */
buf = _PyBytesWriter_Alloc(&writer, hexlen / 2);
if (buf == NULL)
return NULL;
goto release_buffer;

start = str;
end = str + hexlen;
while (str < end) {
/* skip over spaces in the input */
Expand Down Expand Up @@ -2589,6 +2590,9 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
*buf++ = (unsigned char)((top << 4) + bot);
}

if (view.obj != NULL) {
PyBuffer_Release(&view);
}
return _PyBytesWriter_Finish(&writer, buf);

error:
Expand All @@ -2601,6 +2605,11 @@ _PyBytes_FromHex(PyObject *string, int use_bytearray)
"fromhex() arg at position %zd", invalid_char);
}
_PyBytesWriter_Dealloc(&writer);

release_buffer:
if (view.obj != NULL) {
PyBuffer_Release(&view);
}
return NULL;
}

Expand Down
0