pyany_serde/pyany_serde_impl/
bytes_serde.rs

1use pyo3::prelude::*;
2use pyo3::types::PyBytes;
3
4use crate::{
5    communication::{append_bytes, append_bytes_vec, retrieve_bytes},
6    PyAnySerde,
7};
8
9#[derive(Clone)]
10pub struct BytesSerde {}
11
12impl PyAnySerde for BytesSerde {
13    fn append<'py>(
14        &mut self,
15        buf: &mut [u8],
16        offset: usize,
17        obj: &Bound<'py, PyAny>,
18    ) -> PyResult<usize> {
19        Ok(append_bytes(
20            buf,
21            offset,
22            obj.downcast::<PyBytes>()?.as_bytes(),
23        ))
24    }
25
26    fn append_vec<'py>(
27        &mut self,
28        v: &mut Vec<u8>,
29        _start_addr: Option<usize>,
30        obj: &Bound<'py, PyAny>,
31    ) -> PyResult<()> {
32        append_bytes_vec(v, obj.downcast::<PyBytes>()?.as_bytes());
33        Ok(())
34    }
35
36    fn retrieve<'py>(
37        &mut self,
38        py: Python<'py>,
39        buf: &[u8],
40        offset: usize,
41    ) -> PyResult<(Bound<'py, PyAny>, usize)> {
42        let (obj_bytes, offset) = retrieve_bytes(buf, offset)?;
43        Ok((PyBytes::new(py, obj_bytes).into_any(), offset))
44    }
45}