#![cfg(feature = "bytes")]
#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"bytes\"] }")]
use bytes::Bytes;
use crate::conversion::IntoPyObject;
use crate::instance::Bound;
use crate::pybacked::PyBackedBytes;
use crate::types::PyBytes;
use crate::{Borrowed, CastError, FromPyObject, PyAny, PyErr, Python};
impl<'a, 'py> FromPyObject<'a, 'py> for Bytes {
type Error = CastError<'a, 'py>;
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
Ok(Bytes::from_owner(obj.extract::<PyBackedBytes>()?))
}
}
impl<'py> IntoPyObject<'py> for Bytes {
type Target = PyBytes;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyBytes::new(py, &self))
}
}
impl<'py> IntoPyObject<'py> for &Bytes {
type Target = PyBytes;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(PyBytes::new(py, self))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{PyAnyMethods, PyByteArray, PyByteArrayMethods, PyBytes};
use crate::Python;
#[test]
fn test_bytes() {
Python::attach(|py| {
let py_bytes = PyBytes::new(py, b"foobar");
let bytes: Bytes = py_bytes.extract().unwrap();
assert_eq!(&*bytes, b"foobar");
let bytes = Bytes::from_static(b"foobar").into_pyobject(py).unwrap();
assert!(bytes.is_instance_of::<PyBytes>());
});
}
#[test]
fn test_bytearray() {
Python::attach(|py| {
let py_bytearray = PyByteArray::new(py, b"foobar");
let bytes: Bytes = py_bytearray.extract().unwrap();
assert_eq!(&*bytes, b"foobar");
unsafe { py_bytearray.as_bytes_mut()[0] = b'x' };
assert_eq!(&bytes, "foobar");
assert_eq!(&py_bytearray.extract::<Vec<u8>>().unwrap(), b"xoobar");
});
}
}