Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
cmaloney wants to merge4 commits intopython:main
base:main
Choose a base branch
Loading
fromcmaloney:int_from_byteslike
Open
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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.
35 changes: 27 additions & 8 deletionsObjects/longobject.c
View file
Open in desktop
Original file line numberDiff line numberDiff 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,32 @@ 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);
/* Fast-path exact bytes. */
if (PyBytes_CheckExact(bytes_obj)) {
long_obj = _PyLong_FromByteArray(
(unsigned char *)PyBytes_AS_STRING(bytes_obj), Py_SIZE(bytes_obj),
little_endian, is_signed);
}
/* Use buffer protocol to avoid copies. */
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

[8]ページ先頭

©2009-2025 Movatter.jp