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