Skip to content

optimize conversion from bytes for Vec<u8> and [u8; N] #5244

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

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

davidhewitt
Copy link
Member

This is a (successful!) experiment to try and close off some of the remaining questions in #4390

In particular, this addresses the challenge of optimized bytes extraction and whether we can make it work while changing the trait.
Only the last commit 449bd26 is actually relevant here, the rest is just current snapshot of #4390.

This solves the problem encountered in #4390 (comment), namely by avoiding any additional trait bounds and instead requiring the type adding a slice conversion to handle fully the pathways both to array and to vec.

// step 1 of slice extraction for specialized types like `Vec<u8>` and `[u8; N]`
// note that 's lifetime is deliberately different from 'a because the type may
// in general not have a meaningful relation to the lifetime 'a
#[doc(hidden)]
fn object_as_slice<'s>(
    _obj: Borrowed<'s, 'py, PyAny>,
    _: private::Token,
) -> Option<PyResult<&'s [Self]>> {
    None
}

// step 2 of the slice extraction into an array
#[doc(hidden)]
fn slice_into_array<const N: usize>(_slice: &[Self], _: private::Token) -> PyResult<[Self; N]> {
    unreachable!("types implementing as_slice must also implement slice_into_array");
}

// step 2 of the slice extraction into a vector
#[doc(hidden)]
fn slice_into_vec(_slice: &[Self], _: private::Token) -> PyResult<Vec<Self>>
where
    Self: Sized,
{
    unreachable!("types implementing as_slice must also implement slice_into_vec");
}

The nice thing about this design is that:

  • I think this can generalize to also supporting bytearray extraction, and maybe even via PyBuffer<T>
  • I think we could also apply this to main if we wanted without changing FromPyObject, but that's more churn so I'd rather move forward with add second lifetime to FromPyObject #4390. Hopefully we can unblock that in the near future.

@Icxolu
Copy link
Contributor

Icxolu commented Jul 18, 2025

Thanks for taking a look here! This looks very interesting, I'll try to take a more detailed look in the coming days.

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