Module bytes

Module bytes 

Source
Expand description

Conversions to and from bytes’s [Bytes].

This is useful for efficiently converting Python’s bytes types efficiently. While bytes will be directly borrowed, converting from bytearray will result in a copy.

When converting Bytes back into Python, this will do a copy, just like &[u8] and Vec<u8>.

§When to use Bytes

Unless you specifically need [Bytes] for ref-counted ownership and sharing, you may find that using &[u8], Vec<u8>, Bound<PyBytes>, or PyBackedBytes is simpler for most use cases.

§Setup

To use this feature, add in your Cargo.toml:

[dependencies]
bytes = "1.10"
pyo3 = { version = "0.27.1", features = ["bytes"] }

Note that you must use compatible versions of bytes and PyO3.

§Example

Rust code to create functions which return Bytes or take Bytes as arguments:

use pyo3::prelude::*;
use bytes::Bytes;

#[pyfunction]
fn get_message_bytes() -> Bytes {
    Bytes::from_static(b"Hello Python!")
}

#[pyfunction]
fn num_bytes(bytes: Bytes) -> usize {
    bytes.len()
}

#[pymodule]
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(get_message_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(num_bytes, m)?)?;
    Ok(())
}

Python code that calls these functions:

from my_module import get_message_bytes, num_bytes

message = get_message_bytes()
assert message == b"Hello Python!"

size = num_bytes(message)
assert size == 13