Skip to content

bytes should translate to &[u8] #373

@pganssle

Description

@pganssle

Per a discussion in the gitter chat, it seems that currently the proper traits are not implemented to allow for Python's bytes objects to be automatically translated into &[u8] parameters. Right now, in order to write a function that takes bytes, you need to use &PyBytes:

#[pyfunction]
fn print_bytes(_py: Python, x: &PyBytes) {
    println!("{:?}", x.as_bytes())
}

If you instead use &[u8] directly, there's an error at compile time because the pyo3::PyTypeInfo trait is not implemented for [u8]. I think it should be possible to pass both a bytes and bytearray object into a Rust function that takes &[u8].

I am using version 0.6.0-alpha.4, and with this code:

#[pyfunction]
fn print_bytes(_py: Python, x: &[u8]) {
    println!("{:?}", x.as_bytes())
}

I get this error message:

error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
  --> src/lib.rs:36:1
   |
36 | #[pyfunction]
   | ^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `[u8]`
   = note: to learn more, visit <...>
   = note: required because of the requirements on the impl of
           `pyo3::FromPyObject<'_>` for `&[u8]`

error[E0277]: the trait bound `[u8]: pyo3::PyTypeInfo` is not satisfied
  --> src/lib.rs:36:1
   |
36 | #[pyfunction]
   | ^^^^^^^^^^^^^ the trait `pyo3::PyTypeInfo` is not implemented for `[u8]`
   |
   = note: required because of the requirements on the impl
           of `pyo3::PyTryFrom<'_>` for `[u8]`
   = note: required because of the requirements on the impl
           of `pyo3::FromPyObject<'_>` for `&[u8]`

error: aborting due to 2 previous errors

CC @thedrow

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions