pyo3/conversions/
bytes.rs1#![cfg(feature = "bytes")]
2
3#![doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"bytes\"] }")]
24use bytes::Bytes;
66
67use crate::conversion::IntoPyObject;
68#[cfg(feature = "experimental-inspect")]
69use crate::inspect::PyStaticExpr;
70use crate::instance::Bound;
71use crate::pybacked::PyBackedBytes;
72use crate::types::PyBytes;
73#[cfg(feature = "experimental-inspect")]
74use crate::PyTypeInfo;
75use crate::{Borrowed, CastError, FromPyObject, PyAny, PyErr, Python};
76
77impl<'a, 'py> FromPyObject<'a, 'py> for Bytes {
78 type Error = CastError<'a, 'py>;
79
80 #[cfg(feature = "experimental-inspect")]
81 const INPUT_TYPE: PyStaticExpr = PyBackedBytes::INPUT_TYPE;
82
83 fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
84 Ok(Bytes::from_owner(obj.extract::<PyBackedBytes>()?))
85 }
86}
87
88impl<'py> IntoPyObject<'py> for Bytes {
89 type Target = PyBytes;
90 type Output = Bound<'py, Self::Target>;
91 type Error = PyErr;
92
93 #[cfg(feature = "experimental-inspect")]
94 const OUTPUT_TYPE: PyStaticExpr = PyBytes::TYPE_HINT;
95
96 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
97 Ok(PyBytes::new(py, &self))
98 }
99}
100
101impl<'py> IntoPyObject<'py> for &Bytes {
102 type Target = PyBytes;
103 type Output = Bound<'py, Self::Target>;
104 type Error = PyErr;
105
106 #[cfg(feature = "experimental-inspect")]
107 const OUTPUT_TYPE: PyStaticExpr = PyBytes::TYPE_HINT;
108
109 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
110 Ok(PyBytes::new(py, self))
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117 use crate::types::{PyAnyMethods, PyByteArray, PyByteArrayMethods, PyBytes};
118 use crate::Python;
119
120 #[test]
121 fn test_bytes() {
122 Python::attach(|py| {
123 let py_bytes = PyBytes::new(py, b"foobar");
124 let bytes: Bytes = py_bytes.extract().unwrap();
125 assert_eq!(&*bytes, b"foobar");
126
127 let bytes = Bytes::from_static(b"foobar").into_pyobject(py).unwrap();
128 assert!(bytes.is_instance_of::<PyBytes>());
129 });
130 }
131
132 #[test]
133 fn test_bytearray() {
134 Python::attach(|py| {
135 let py_bytearray = PyByteArray::new(py, b"foobar");
136 let bytes: Bytes = py_bytearray.extract().unwrap();
137 assert_eq!(&*bytes, b"foobar");
138
139 unsafe { py_bytearray.as_bytes_mut()[0] = b'x' };
141 assert_eq!(&bytes, "foobar");
142 assert_eq!(&py_bytearray.extract::<Vec<u8>>().unwrap(), b"xoobar");
143 });
144 }
145}