Skip to content

Commit

Permalink
add PyBytes wrapper type to access bytes from python
Browse files Browse the repository at this point in the history
  • Loading branch information
somethingelseentirely committed Nov 28, 2024
1 parent 6ddc885 commit f4a6d35
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "anybytes"
version = "0.10.0"
version = "0.11.0-alpha.1"
edition = "2021"
license = "MIT"
repository = "https://github.com/triblespace/anybytes"
Expand Down
5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ mod owners;
#[cfg(feature = "zerocopy")]
pub mod packed;

#[cfg(feature = "pyo3")]
pub mod pybytes;

#[cfg(test)]
mod tests;

Expand All @@ -26,3 +29,5 @@ pub use crate::packed::Packed;
pub use crate::packed::PackedSlice;
#[cfg(feature = "zerocopy")]
pub use crate::packed::PackedStr;
#[cfg(feature = "pyo3")]
pub use crate::pybytes::PyBytes;
32 changes: 32 additions & 0 deletions src/pybytes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use pyo3::{prelude::*, ffi, PyResult};
use std::os::raw::c_int;

use crate::Bytes;

#[pyclass(name = "Bytes")]
pub struct PyBytes {
bytes: Bytes
}

#[pymethods]
impl PyBytes {
unsafe fn __getbuffer__(
slf: PyRefMut<Self>,
view: *mut ffi::Py_buffer,
flags: c_int,
) -> PyResult<()> {
let bytes = slf.bytes.as_slice();
let ret = ffi::PyBuffer_FillInfo(
view,
slf.as_ptr() as *mut _,
bytes.as_ptr() as *mut _,
bytes.len().try_into().unwrap(),
1, // read only
flags,
);
if ret == -1 {
return Err(PyErr::fetch(slf.py()));
}
Ok(())
}
}

0 comments on commit f4a6d35

Please sign in to comment.