Skip to content

gh-132108: Add Buffer Protocol support to int.from_bytes to improve performance #132109

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :meth:`int.from_bytes` when passed object supports :ref:`buffer
protocol <bufferobjects>`, like :class:`bytearray` by ~1.2x.
33 changes: 25 additions & 8 deletions Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -6439,6 +6439,7 @@ int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
{
int little_endian;
PyObject *long_obj, *bytes;
Py_buffer view;

if (byteorder == NULL)
little_endian = 0;
Expand All @@ -6452,14 +6453,30 @@ int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
return NULL;
}

bytes = PyObject_Bytes(bytes_obj);
if (bytes == NULL)
return NULL;

long_obj = _PyLong_FromByteArray(
(unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
little_endian, is_signed);
Py_DECREF(bytes);
/* Use buffer protocol to avoid copies. */
if (PyBytes_CheckExact(bytes_obj)) {
long_obj = _PyLong_FromByteArray(
(unsigned char *)PyBytes_AS_STRING(bytes_obj), Py_SIZE(bytes_obj),
little_endian, is_signed);
} else if (PyObject_CheckBuffer(bytes_obj)) {
if (PyObject_GetBuffer(bytes_obj, &view, PyBUF_SIMPLE) != 0) {
return NULL;
}
long_obj = _PyLong_FromByteArray(view.buf, view.len, little_endian,
is_signed);
PyBuffer_Release(&view);
}
else {
/* fallback: Construct a bytes then convert. */
bytes = PyObject_Bytes(bytes_obj);
if (bytes == NULL) {
return NULL;
}
long_obj = _PyLong_FromByteArray(
(unsigned char *)PyBytes_AS_STRING(bytes), Py_SIZE(bytes),
little_endian, is_signed);
Py_DECREF(bytes);
}

if (long_obj != NULL && type != &PyLong_Type) {
Py_SETREF(long_obj, PyObject_CallOneArg((PyObject *)type, long_obj));
Expand Down
Loading