Skip to content

internal: Fix double copy creating PyBackedBytes from PyByteArray - #6357

Merged
davidhewitt merged 1 commit into
PyO3:mainfrom
PeterFaiman:peterfaiman/push-rkwzokwwmlly
Aug 28, 2026
Merged

internal: Fix double copy creating PyBackedBytes from PyByteArray#6357
davidhewitt merged 1 commit into
PyO3:mainfrom
PeterFaiman:peterfaiman/push-rkwzokwwmlly

Conversation

@PeterFaiman

@PeterFaiman PeterFaiman commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Arc::<[u8]>::from(py_bytearray.to_vec()) creates a Vec copy of the PyByteArray contents, then immediately copies that Vec into an Arc<[u8]>. It should copy the PyByteArray contents directly into the Arc<[u8]>. This PR inlines PyByteArrayMethods::to_vec into PyBackedBytes::from without the unnecessary copy.

pyo3/src/types/bytearray.rs

Lines 291 to 300 in 7550783

fn to_vec(&self) -> Vec<u8> {
with_critical_section(self, || {
// SAFETY:
// * `self` is a `Bound` object, which guarantees that the Python GIL is held.
// * For free-threaded Python, a critical section is used in lieu of the GIL.
// * We don't interact with the interpreter
// * We don't mutate the underlying slice
unsafe { self.as_bytes() }.to_vec()
})
}

`Arc::<[u8]>::from(py_bytearray.to_vec())` creates a `Vec` copy of the `PyByteArray` contents, then immediately copies that `Vec` into an `Arc<[u8]>`. It should copy the `PyByteArray` contents directly into the `Arc<[u8]>`. This PR inlines `PyByteArrayMethods::to_vec` into `PyBackedBytes::from` without the unnecessary copy.

See: <https://github.com/PyO3/pyo3/blob/75507833367e5267dd6fdd7e48de628e4b8e53e0/src/types/bytearray.rs#L291-L300>.

@davidhewitt davidhewitt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks, seems fine to me!

@davidhewitt
davidhewitt added this pull request to the merge queue Aug 28, 2026
Merged via the queue into PyO3:main with commit 491df5b Aug 28, 2026
55 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants