1#[cfg(feature = "experimental-inspect")]
2use crate::inspect::types::TypeInfo;
3use crate::{types::PyBytes, FromPyObject, IntoPy, PyAny, PyObject, PyResult, Python, ToPyObject};
4
5impl<'a> IntoPy<PyObject> for &'a [u8] {
6 fn into_py(self, py: Python<'_>) -> PyObject {
7 PyBytes::new(py, self).to_object(py)
8 }
9
10 #[cfg(feature = "experimental-inspect")]
11 fn type_output() -> TypeInfo {
12 TypeInfo::builtin("bytes")
13 }
14}
15
16impl<'a> FromPyObject<'a> for &'a [u8] {
17 fn extract(obj: &'a PyAny) -> PyResult<Self> {
18 Ok(obj.downcast::<PyBytes>()?.as_bytes())
19 }
20
21 #[cfg(feature = "experimental-inspect")]
22 fn type_input() -> TypeInfo {
23 Self::type_output()
24 }
25}
26
27#[cfg(test)]
28mod tests {
29 use crate::FromPyObject;
30 use crate::Python;
31
32 #[test]
33 fn test_extract_bytes() {
34 Python::with_gil(|py| {
35 let py_bytes = py.eval("b'Hello Python'", None, None).unwrap();
36 let bytes: &[u8] = FromPyObject::extract(py_bytes).unwrap();
37 assert_eq!(bytes, b"Hello Python");
38 });
39 }
40}
41