pyany_serde/pyany_serde_impl/
complex_serde.rs1use pyo3::prelude::*;
2use pyo3::types::PyComplex;
3
4use crate::{
5 communication::{append_c_double, append_c_double_vec, retrieve_c_double},
6 PyAnySerde,
7};
8
9#[derive(Clone)]
10pub struct ComplexSerde {}
11
12impl PyAnySerde for ComplexSerde {
13 fn append<'py>(
14 &mut self,
15 buf: &mut [u8],
16 offset: usize,
17 obj: &Bound<'py, PyAny>,
18 ) -> PyResult<usize> {
19 let complex = obj.downcast::<PyComplex>()?;
20 let mut offset = append_c_double(buf, offset, complex.real());
21 offset = append_c_double(buf, offset, complex.imag());
22 Ok(offset)
23 }
24
25 fn append_vec<'py>(
26 &mut self,
27 v: &mut Vec<u8>,
28 _start_addr: Option<usize>,
29 obj: &Bound<'py, PyAny>,
30 ) -> PyResult<()> {
31 let complex = obj.downcast::<PyComplex>()?;
32 append_c_double_vec(v, complex.real());
33 append_c_double_vec(v, complex.imag());
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 (real, mut offset) = retrieve_c_double(buf, offset)?;
44 let imag;
45 (imag, offset) = retrieve_c_double(buf, offset)?;
46 Ok((PyComplex::from_doubles(py, real, imag).into_any(), offset))
47 }
48}