diff --git a/src/types/string.rs b/src/types/string.rs index 11965bbd..4b964861 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -215,6 +215,18 @@ impl<'source> FromPyObject<'source> for String { } } +impl<'a> FromPy<&'a [u8]> for PyObject { + fn from_py(other: &'a [u8], py: Python) -> Self { + PyBytes::new(py, other).to_object(py) + } +} + +impl<'a> FromPyObject<'a> for &'a [u8] { + fn extract(obj: &'a PyAny) -> PyResult { + Ok(::try_from(obj)?.as_bytes()) + } +} + #[cfg(test)] mod test { use super::{PyBytes, PyString}; @@ -244,6 +256,16 @@ mod test { assert_eq!(s, s2); } + #[test] + fn test_extract_bytes() { + let gil = Python::acquire_gil(); + let py = gil.python(); + + let py_bytes = py.eval("b'Hello Python'", None, None).unwrap(); + let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap(); + assert_eq!(bytes, b"Hello Python"); + } + #[test] fn test_as_bytes() { let gil = Python::acquire_gil(); diff --git a/tests/test_bytes.rs b/tests/test_bytes.rs new file mode 100644 index 00000000..cffd6053 --- /dev/null +++ b/tests/test_bytes.rs @@ -0,0 +1,22 @@ +use pyo3::prelude::*; +use pyo3::wrap_pyfunction; + +mod common; + +#[pyfunction] +fn bytes_pybytes_conversion(bytes: &[u8]) -> &[u8] { + bytes +} + +#[test] +fn test_pybytes_bytes_conversion() { + let gil = Python::acquire_gil(); + let py = gil.python(); + + let bytes_pybytes_conversion = wrap_pyfunction!(bytes_pybytes_conversion)(py); + py_assert!( + py, + bytes_pybytes_conversion, + "bytes_pybytes_conversion(b'Hello World') == b'Hello World'" + ); +}