| 1 | # pyo3-bytes |
| 2 | |
| 3 | Integration between [`bytes`](https://docs.rs/bytes) and [`pyo3`](https://github.com/PyO3/pyo3). |
| 4 | |
| 5 | This provides [`PyBytes`], a wrapper around [`Bytes`][::bytes::Bytes] that supports the [Python buffer protocol](https://docs.python.org/3/c-api/buffer.html). |
| 6 | |
| 7 | This uses the new [`Bytes::from_owner` API](https://docs.rs/bytes/latest/bytes/struct.Bytes.html#method.from_owner) introduced in `bytes` 1.9. |
| 8 | |
| 9 | Since this integration uses the Python buffer protocol, any library that uses `pyo3-bytes` must set the feature flags for the `pyo3` dependency correctly. `pyo3` must either _not_ have an [`abi3` feature flag](https://pyo3.rs/v0.23.4/features.html#abi3) (in which case maturin will generate wheels per Python version), or have `abi3-py311` (which supports only Python 3.11+), since the buffer protocol became part of the Python stable ABI [as of Python 3.11](https://docs.python.org/3/c-api/buffer.html#c.Py_buffer). |
| 10 | |
| 11 | ## Importing buffers to Rust |
| 12 | |
| 13 | Just use `PyBytes` as a type in your functions or methods exposed to Python. |
| 14 | |
| 15 | ```rs |
| 16 | use pyo3_bytes::PyBytes; |
| 17 | use bytes::Bytes; |
| 18 | |
| 19 | #[pyfunction] |
| 20 | pub fn use_bytes(buffer: PyBytes) { |
| 21 | let buffer: Bytes = buffer.into_inner(); |
| 22 | } |
| 23 | ``` |
| 24 | |
| 25 | ## Exporting buffers to Python |
| 26 | |
| 27 | Return the `PyBytes` class from your function. |
| 28 | |
| 29 | ```rs |
| 30 | use pyo3_bytes::PyBytes; |
| 31 | use bytes::Bytes; |
| 32 | |
| 33 | #[pyfunction] |
| 34 | pub fn return_bytes() -> PyBytes { |
| 35 | let buffer = Bytes::from_static(b"hello"); |
| 36 | PyBytes::new(buffer) |
| 37 | } |
| 38 | ``` |
| 39 | |
| 40 | ## Safety |
| 41 | |
| 42 | Unfortunately, this interface cannot be 100% safe, as the Python buffer protocol does not enforce buffer immutability. |
| 43 | |
| 44 | The Python user must take care to not mutate the buffers that have been passed |
| 45 | to Rust. |
| 46 | |
| 47 | For more reading: |
| 48 | |
| 49 | - <https://alexgaynor.net/2022/oct/23/buffers-on-the-edge/> |
| 50 | - <https://github.com/PyO3/pyo3/issues/2824> |
| 51 | - <https://github.com/PyO3/pyo3/issues/4736> |
| 52 | |
| 53 | ## Python type hints |
| 54 | |
| 55 | On the Python side, the exported `Bytes` class implements many of the same |
| 56 | methods (with the same signature) as the Python `bytes` object. |
| 57 | |
| 58 | The Python type hints are available in the Github repo in the file `bytes.pyi`. |
| 59 | I don't know the best way to distribute this to downstream projects. If you have |
| 60 | an idea, create an issue to discuss. |
| 61 | |
| 62 | ## Version compatibility |
| 63 | |
| 64 | | pyo3-bytes | pyo3 | |
| 65 | | ---------- | ---- | |
| 66 | | 0.1.x | 0.23 | |
| 67 | | 0.2.x | 0.24 | |
| 68 | | 0.3.x | 0.25 | |
| 69 | | 0.4.x | 0.26 | |
| 70 | | 0.5.x | 0.27 | |
| 71 | | 0.6.x | 0.28 | |