| 1 | use std::marker::PhantomData; |
| 2 | |
| 3 | #[cfg(feature = "arbitrary_precision")] |
| 4 | use pyo3::types::{PyAnyMethods, PyFloat, PyInt}; |
| 5 | use pyo3::types::{ |
| 6 | PyDict, PyDictMethods, PyList, PyListMethods, PyMapping, PySequence, PyString, PyTuple, |
| 7 | PyTupleMethods, |
| 8 | }; |
| 9 | use pyo3::{Bound, BoundObject, IntoPyObject, PyAny, PyResult, Python}; |
| 10 | use serde::{ser, Serialize}; |
| 11 | |
| 12 | use crate::error::{PythonizeError, Result}; |
| 13 | |
| 14 | /// Trait for types which can represent a Python mapping |
| 15 | pub trait PythonizeMappingType { |
| 16 | /// Builder type for Python mappings |
| 17 | type Builder<'py>: 'py; |
| 18 | |
| 19 | /// Create a builder for a Python mapping |
| 20 | fn builder<'py>(py: Python<'py>, len: Option<usize>) -> PyResult<Self::Builder<'py>>; |
| 21 | |
| 22 | /// Adds the key-value item to the mapping being built |
| 23 | fn push_item<'py>( |
| 24 | builder: &mut Self::Builder<'py>, |
| 25 | key: Bound<'py, PyAny>, |
| 26 | value: Bound<'py, PyAny>, |
| 27 | ) -> PyResult<()>; |
| 28 | |
| 29 | /// Build the Python mapping |
| 30 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>>; |
| 31 | } |
| 32 | |
| 33 | /// Trait for types which can represent a Python mapping and have a name |
| 34 | pub trait PythonizeNamedMappingType { |
| 35 | /// Builder type for Python mappings with a name |
| 36 | type Builder<'py>: 'py; |
| 37 | |
| 38 | /// Create a builder for a Python mapping with a name |
| 39 | fn builder<'py>( |
| 40 | py: Python<'py>, |
| 41 | len: usize, |
| 42 | name: &'static str, |
| 43 | ) -> PyResult<Self::Builder<'py>>; |
| 44 | |
| 45 | /// Adds the field to the named mapping being built |
| 46 | fn push_field<'py>( |
| 47 | builder: &mut Self::Builder<'py>, |
| 48 | name: Bound<'py, PyString>, |
| 49 | value: Bound<'py, PyAny>, |
| 50 | ) -> PyResult<()>; |
| 51 | |
| 52 | /// Build the Python mapping |
| 53 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>>; |
| 54 | } |
| 55 | |
| 56 | /// Trait for types which can represent a Python sequence |
| 57 | pub trait PythonizeListType: Sized { |
| 58 | /// Constructor |
| 59 | fn create_sequence<'py, T, U>( |
| 60 | py: Python<'py>, |
| 61 | elements: impl IntoIterator<Item = T, IntoIter = U>, |
| 62 | ) -> PyResult<Bound<'py, PySequence>> |
| 63 | where |
| 64 | T: IntoPyObject<'py>, |
| 65 | U: ExactSizeIterator<Item = T>; |
| 66 | } |
| 67 | |
| 68 | /// Custom types for serialization |
| 69 | pub trait PythonizeTypes { |
| 70 | /// Python map type (should be representable as python mapping) |
| 71 | type Map: PythonizeMappingType; |
| 72 | /// Python (struct-like) named map type (should be representable as python mapping) |
| 73 | type NamedMap: PythonizeNamedMappingType; |
| 74 | /// Python sequence type (should be representable as python sequence) |
| 75 | type List: PythonizeListType; |
| 76 | } |
| 77 | |
| 78 | impl PythonizeMappingType for PyDict { |
| 79 | type Builder<'py> = Bound<'py, Self>; |
| 80 | |
| 81 | fn builder<'py>(py: Python<'py>, _len: Option<usize>) -> PyResult<Self::Builder<'py>> { |
| 82 | Ok(Self::new(py)) |
| 83 | } |
| 84 | |
| 85 | fn push_item<'py>( |
| 86 | builder: &mut Self::Builder<'py>, |
| 87 | key: Bound<'py, PyAny>, |
| 88 | value: Bound<'py, PyAny>, |
| 89 | ) -> PyResult<()> { |
| 90 | builder.set_item(key, value) |
| 91 | } |
| 92 | |
| 93 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>> { |
| 94 | Ok(builder.into_mapping()) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Adapter type to use an unnamed mapping type, i.e. one that implements |
| 99 | /// [`PythonizeMappingType`], as a named mapping type, i.e. one that implements |
| 100 | /// [`PythonizeNamedMappingType`]. The adapter simply drops the provided name. |
| 101 | /// |
| 102 | /// This adapter is commonly applied to use the same unnamed mapping type for |
| 103 | /// both [`PythonizeTypes::Map`] and [`PythonizeTypes::NamedMap`] while only |
| 104 | /// implementing [`PythonizeMappingType`]. |
| 105 | pub struct PythonizeUnnamedMappingAdapter<T: PythonizeMappingType> { |
| 106 | _unnamed: T, |
| 107 | } |
| 108 | |
| 109 | impl<T: PythonizeMappingType> PythonizeNamedMappingType for PythonizeUnnamedMappingAdapter<T> { |
| 110 | type Builder<'py> = T::Builder<'py>; |
| 111 | |
| 112 | fn builder<'py>( |
| 113 | py: Python<'py>, |
| 114 | len: usize, |
| 115 | _name: &'static str, |
| 116 | ) -> PyResult<Self::Builder<'py>> { |
| 117 | T::builder(py, Some(len)) |
| 118 | } |
| 119 | |
| 120 | fn push_field<'py>( |
| 121 | builder: &mut Self::Builder<'py>, |
| 122 | name: Bound<'py, PyString>, |
| 123 | value: Bound<'py, PyAny>, |
| 124 | ) -> PyResult<()> { |
| 125 | T::push_item(builder, name.into_any(), value) |
| 126 | } |
| 127 | |
| 128 | fn finish<'py>(builder: Self::Builder<'py>) -> PyResult<Bound<'py, PyMapping>> { |
| 129 | T::finish(builder) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | impl PythonizeListType for PyList { |
| 134 | fn create_sequence<'py, T, U>( |
| 135 | py: Python<'py>, |
| 136 | elements: impl IntoIterator<Item = T, IntoIter = U>, |
| 137 | ) -> PyResult<Bound<'py, PySequence>> |
| 138 | where |
| 139 | T: IntoPyObject<'py>, |
| 140 | U: ExactSizeIterator<Item = T>, |
| 141 | { |
| 142 | Ok(PyList::new(py, elements)?.into_sequence()) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | impl PythonizeListType for PyTuple { |
| 147 | fn create_sequence<'py, T, U>( |
| 148 | py: Python<'py>, |
| 149 | elements: impl IntoIterator<Item = T, IntoIter = U>, |
| 150 | ) -> PyResult<Bound<'py, PySequence>> |
| 151 | where |
| 152 | T: IntoPyObject<'py>, |
| 153 | U: ExactSizeIterator<Item = T>, |
| 154 | { |
| 155 | Ok(PyTuple::new(py, elements)?.into_sequence()) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | pub struct PythonizeDefault; |
| 160 | |
| 161 | impl PythonizeTypes for PythonizeDefault { |
| 162 | type Map = PyDict; |
| 163 | type NamedMap = PythonizeUnnamedMappingAdapter<PyDict>; |
| 164 | type List = PyList; |
| 165 | } |
| 166 | |
| 167 | /// Attempt to convert the given data into a Python object |
| 168 | pub fn pythonize<'py, T>(py: Python<'py>, value: &T) -> Result<Bound<'py, PyAny>> |
| 169 | where |
| 170 | T: ?Sized + Serialize, |
| 171 | { |
| 172 | value.serialize(Pythonizer::new(py)) |
| 173 | } |
| 174 | |
| 175 | /// Attempt to convert the given data into a Python object. |
| 176 | /// Also uses custom mapping python class for serialization. |
| 177 | pub fn pythonize_custom<'py, P, T>(py: Python<'py>, value: &T) -> Result<Bound<'py, PyAny>> |
| 178 | where |
| 179 | T: ?Sized + Serialize, |
| 180 | P: PythonizeTypes, |
| 181 | { |
| 182 | value.serialize(Pythonizer::custom::<P>(py)) |
| 183 | } |
| 184 | |
| 185 | /// A structure that serializes Rust values into Python objects |
| 186 | #[derive(Clone, Copy)] |
| 187 | pub struct Pythonizer<'py, P> { |
| 188 | py: Python<'py>, |
| 189 | _types: PhantomData<P>, |
| 190 | } |
| 191 | |
| 192 | impl<'py, P> From<Python<'py>> for Pythonizer<'py, P> { |
| 193 | fn from(py: Python<'py>) -> Self { |
| 194 | Self { |
| 195 | py, |
| 196 | _types: PhantomData, |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | impl<'py> Pythonizer<'py, PythonizeDefault> { |
| 202 | /// Creates a serializer to convert data into a Python object using the default mapping class |
| 203 | pub fn new(py: Python<'py>) -> Self { |
| 204 | Self::from(py) |
| 205 | } |
| 206 | |
| 207 | /// Creates a serializer to convert data into a Python object using a custom mapping class |
| 208 | pub fn custom<P>(py: Python<'py>) -> Pythonizer<'py, P> { |
| 209 | Pythonizer::from(py) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | #[doc(hidden)] |
| 214 | pub struct PythonCollectionSerializer<'py, P> { |
| 215 | items: Vec<Bound<'py, PyAny>>, |
| 216 | py: Python<'py>, |
| 217 | _types: PhantomData<P>, |
| 218 | } |
| 219 | |
| 220 | #[doc(hidden)] |
| 221 | pub struct PythonTupleVariantSerializer<'py, P> { |
| 222 | name: &'static str, |
| 223 | variant: &'static str, |
| 224 | inner: PythonCollectionSerializer<'py, P>, |
| 225 | } |
| 226 | |
| 227 | #[doc(hidden)] |
| 228 | pub struct PythonStructVariantSerializer<'py, P: PythonizeTypes> { |
| 229 | name: &'static str, |
| 230 | variant: &'static str, |
| 231 | inner: PythonStructDictSerializer<'py, P>, |
| 232 | } |
| 233 | |
| 234 | #[cfg(feature = "arbitrary_precision")] |
| 235 | #[doc(hidden)] |
| 236 | pub enum StructSerializer<'py, P: PythonizeTypes> { |
| 237 | Struct(PythonStructDictSerializer<'py, P>), |
| 238 | Number { |
| 239 | py: Python<'py>, |
| 240 | number_string: Option<String>, |
| 241 | _types: PhantomData<P>, |
| 242 | }, |
| 243 | } |
| 244 | |
| 245 | #[cfg(not(feature = "arbitrary_precision"))] |
| 246 | #[doc(hidden)] |
| 247 | pub type StructSerializer<'py, P> = PythonStructDictSerializer<'py, P>; |
| 248 | |
| 249 | #[doc(hidden)] |
| 250 | pub struct PythonStructDictSerializer<'py, P: PythonizeTypes> { |
| 251 | py: Python<'py>, |
| 252 | builder: <P::NamedMap as PythonizeNamedMappingType>::Builder<'py>, |
| 253 | _types: PhantomData<P>, |
| 254 | } |
| 255 | |
| 256 | #[doc(hidden)] |
| 257 | pub struct PythonMapSerializer<'py, P: PythonizeTypes> { |
| 258 | py: Python<'py>, |
| 259 | builder: <P::Map as PythonizeMappingType>::Builder<'py>, |
| 260 | key: Option<Bound<'py, PyAny>>, |
| 261 | _types: PhantomData<P>, |
| 262 | } |
| 263 | |
| 264 | impl<'py, P: PythonizeTypes> Pythonizer<'py, P> { |
| 265 | /// The default implementation for serialisation functions. |
| 266 | #[inline] |
| 267 | fn serialise_default<T>(self, v: T) -> Result<Bound<'py, PyAny>> |
| 268 | where |
| 269 | T: IntoPyObject<'py>, |
| 270 | <T as IntoPyObject<'py>>::Error: Into<PythonizeError>, |
| 271 | { |
| 272 | v.into_pyobject(self.py) |
| 273 | .map(|x| x.into_any().into_bound()) |
| 274 | .map_err(Into::into) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | impl<'py, P: PythonizeTypes> ser::Serializer for Pythonizer<'py, P> { |
| 279 | type Ok = Bound<'py, PyAny>; |
| 280 | type Error = PythonizeError; |
| 281 | type SerializeSeq = PythonCollectionSerializer<'py, P>; |
| 282 | type SerializeTuple = PythonCollectionSerializer<'py, P>; |
| 283 | type SerializeTupleStruct = PythonCollectionSerializer<'py, P>; |
| 284 | type SerializeTupleVariant = PythonTupleVariantSerializer<'py, P>; |
| 285 | type SerializeMap = PythonMapSerializer<'py, P>; |
| 286 | type SerializeStruct = StructSerializer<'py, P>; |
| 287 | type SerializeStructVariant = PythonStructVariantSerializer<'py, P>; |
| 288 | |
| 289 | fn serialize_bool(self, v: bool) -> Result<Bound<'py, PyAny>> { |
| 290 | self.serialise_default(v) |
| 291 | } |
| 292 | |
| 293 | fn serialize_i8(self, v: i8) -> Result<Bound<'py, PyAny>> { |
| 294 | self.serialise_default(v) |
| 295 | } |
| 296 | |
| 297 | fn serialize_i16(self, v: i16) -> Result<Bound<'py, PyAny>> { |
| 298 | self.serialise_default(v) |
| 299 | } |
| 300 | |
| 301 | fn serialize_i32(self, v: i32) -> Result<Bound<'py, PyAny>> { |
| 302 | self.serialise_default(v) |
| 303 | } |
| 304 | |
| 305 | fn serialize_i64(self, v: i64) -> Result<Bound<'py, PyAny>> { |
| 306 | self.serialise_default(v) |
| 307 | } |
| 308 | |
| 309 | fn serialize_u8(self, v: u8) -> Result<Bound<'py, PyAny>> { |
| 310 | self.serialise_default(v) |
| 311 | } |
| 312 | |
| 313 | fn serialize_u16(self, v: u16) -> Result<Bound<'py, PyAny>> { |
| 314 | self.serialise_default(v) |
| 315 | } |
| 316 | |
| 317 | fn serialize_u32(self, v: u32) -> Result<Bound<'py, PyAny>> { |
| 318 | self.serialise_default(v) |
| 319 | } |
| 320 | |
| 321 | fn serialize_u64(self, v: u64) -> Result<Bound<'py, PyAny>> { |
| 322 | self.serialise_default(v) |
| 323 | } |
| 324 | |
| 325 | fn serialize_f32(self, v: f32) -> Result<Bound<'py, PyAny>> { |
| 326 | self.serialise_default(v) |
| 327 | } |
| 328 | |
| 329 | fn serialize_f64(self, v: f64) -> Result<Bound<'py, PyAny>> { |
| 330 | self.serialise_default(v) |
| 331 | } |
| 332 | |
| 333 | fn serialize_char(self, v: char) -> Result<Bound<'py, PyAny>> { |
| 334 | self.serialize_str(&v.to_string()) |
| 335 | } |
| 336 | |
| 337 | fn serialize_str(self, v: &str) -> Result<Bound<'py, PyAny>> { |
| 338 | Ok(PyString::new(self.py, v).into_any()) |
| 339 | } |
| 340 | |
| 341 | fn serialize_bytes(self, v: &[u8]) -> Result<Bound<'py, PyAny>> { |
| 342 | self.serialise_default(v) |
| 343 | } |
| 344 | |
| 345 | fn serialize_none(self) -> Result<Bound<'py, PyAny>> { |
| 346 | Ok(self.py.None().into_bound(self.py)) |
| 347 | } |
| 348 | |
| 349 | fn serialize_some<T>(self, value: &T) -> Result<Bound<'py, PyAny>> |
| 350 | where |
| 351 | T: ?Sized + Serialize, |
| 352 | { |
| 353 | value.serialize(self) |
| 354 | } |
| 355 | |
| 356 | fn serialize_unit(self) -> Result<Bound<'py, PyAny>> { |
| 357 | self.serialize_none() |
| 358 | } |
| 359 | |
| 360 | fn serialize_unit_struct(self, _name: &'static str) -> Result<Bound<'py, PyAny>> { |
| 361 | self.serialize_none() |
| 362 | } |
| 363 | |
| 364 | fn serialize_unit_variant( |
| 365 | self, |
| 366 | _name: &'static str, |
| 367 | _variant_index: u32, |
| 368 | variant: &'static str, |
| 369 | ) -> Result<Bound<'py, PyAny>> { |
| 370 | self.serialize_str(variant) |
| 371 | } |
| 372 | |
| 373 | fn serialize_newtype_struct<T>( |
| 374 | self, |
| 375 | _name: &'static str, |
| 376 | value: &T, |
| 377 | ) -> Result<Bound<'py, PyAny>> |
| 378 | where |
| 379 | T: ?Sized + Serialize, |
| 380 | { |
| 381 | value.serialize(self) |
| 382 | } |
| 383 | |
| 384 | fn serialize_newtype_variant<T>( |
| 385 | self, |
| 386 | name: &'static str, |
| 387 | _variant_index: u32, |
| 388 | variant: &'static str, |
| 389 | value: &T, |
| 390 | ) -> Result<Bound<'py, PyAny>> |
| 391 | where |
| 392 | T: ?Sized + Serialize, |
| 393 | { |
| 394 | let mut m = P::NamedMap::builder(self.py, 1, name)?; |
| 395 | P::NamedMap::push_field( |
| 396 | &mut m, |
| 397 | PyString::new(self.py, variant), |
| 398 | value.serialize(self)?, |
| 399 | )?; |
| 400 | Ok(P::NamedMap::finish(m)?.into_any()) |
| 401 | } |
| 402 | |
| 403 | fn serialize_seq(self, len: Option<usize>) -> Result<PythonCollectionSerializer<'py, P>> { |
| 404 | let items = match len { |
| 405 | Some(len) => Vec::with_capacity(len), |
| 406 | None => Vec::new(), |
| 407 | }; |
| 408 | Ok(PythonCollectionSerializer { |
| 409 | items, |
| 410 | py: self.py, |
| 411 | _types: PhantomData, |
| 412 | }) |
| 413 | } |
| 414 | |
| 415 | fn serialize_tuple(self, len: usize) -> Result<PythonCollectionSerializer<'py, P>> { |
| 416 | Ok(PythonCollectionSerializer { |
| 417 | items: Vec::with_capacity(len), |
| 418 | py: self.py, |
| 419 | _types: PhantomData, |
| 420 | }) |
| 421 | } |
| 422 | |
| 423 | fn serialize_tuple_struct( |
| 424 | self, |
| 425 | _name: &'static str, |
| 426 | len: usize, |
| 427 | ) -> Result<PythonCollectionSerializer<'py, P>> { |
| 428 | self.serialize_tuple(len) |
| 429 | } |
| 430 | |
| 431 | fn serialize_tuple_variant( |
| 432 | self, |
| 433 | name: &'static str, |
| 434 | _variant_index: u32, |
| 435 | variant: &'static str, |
| 436 | len: usize, |
| 437 | ) -> Result<PythonTupleVariantSerializer<'py, P>> { |
| 438 | let inner = self.serialize_tuple(len)?; |
| 439 | Ok(PythonTupleVariantSerializer { |
| 440 | name, |
| 441 | variant, |
| 442 | inner, |
| 443 | }) |
| 444 | } |
| 445 | |
| 446 | fn serialize_map(self, len: Option<usize>) -> Result<PythonMapSerializer<'py, P>> { |
| 447 | Ok(PythonMapSerializer { |
| 448 | builder: P::Map::builder(self.py, len)?, |
| 449 | key: None, |
| 450 | py: self.py, |
| 451 | _types: PhantomData, |
| 452 | }) |
| 453 | } |
| 454 | |
| 455 | fn serialize_struct(self, name: &'static str, len: usize) -> Result<StructSerializer<'py, P>> { |
| 456 | #[cfg(feature = "arbitrary_precision")] |
| 457 | { |
| 458 | // With arbitrary_precision enabled, a serde_json::Number serializes as a "$serde_json::private::Number" |
| 459 | // struct with a "$serde_json::private::Number" field, whose value is the String in Number::n. |
| 460 | if name == "$serde_json::private::Number" && len == 1 { |
| 461 | return Ok(StructSerializer::Number { |
| 462 | py: self.py, |
| 463 | number_string: None, |
| 464 | _types: PhantomData, |
| 465 | }); |
| 466 | } |
| 467 | |
| 468 | Ok(StructSerializer::Struct(PythonStructDictSerializer { |
| 469 | py: self.py, |
| 470 | builder: P::NamedMap::builder(self.py, len, name)?, |
| 471 | _types: PhantomData, |
| 472 | })) |
| 473 | } |
| 474 | |
| 475 | #[cfg(not(feature = "arbitrary_precision"))] |
| 476 | { |
| 477 | Ok(PythonStructDictSerializer { |
| 478 | py: self.py, |
| 479 | builder: P::NamedMap::builder(self.py, len, name)?, |
| 480 | _types: PhantomData, |
| 481 | }) |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | fn serialize_struct_variant( |
| 486 | self, |
| 487 | name: &'static str, |
| 488 | _variant_index: u32, |
| 489 | variant: &'static str, |
| 490 | len: usize, |
| 491 | ) -> Result<PythonStructVariantSerializer<'py, P>> { |
| 492 | Ok(PythonStructVariantSerializer { |
| 493 | name, |
| 494 | variant, |
| 495 | inner: PythonStructDictSerializer { |
| 496 | py: self.py, |
| 497 | builder: P::NamedMap::builder(self.py, len, variant)?, |
| 498 | _types: PhantomData, |
| 499 | }, |
| 500 | }) |
| 501 | } |
| 502 | } |
| 503 | |
| 504 | impl<'py, P: PythonizeTypes> ser::SerializeSeq for PythonCollectionSerializer<'py, P> { |
| 505 | type Ok = Bound<'py, PyAny>; |
| 506 | type Error = PythonizeError; |
| 507 | |
| 508 | fn serialize_element<T>(&mut self, value: &T) -> Result<()> |
| 509 | where |
| 510 | T: ?Sized + Serialize, |
| 511 | { |
| 512 | self.items.push(pythonize_custom::<P, _>(self.py, value)?); |
| 513 | Ok(()) |
| 514 | } |
| 515 | |
| 516 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 517 | let instance = P::List::create_sequence(self.py, self.items)?; |
| 518 | Ok(instance.into_pyobject(self.py)?.into_any()) |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | impl<'py, P: PythonizeTypes> ser::SerializeTuple for PythonCollectionSerializer<'py, P> { |
| 523 | type Ok = Bound<'py, PyAny>; |
| 524 | type Error = PythonizeError; |
| 525 | |
| 526 | fn serialize_element<T>(&mut self, value: &T) -> Result<()> |
| 527 | where |
| 528 | T: ?Sized + Serialize, |
| 529 | { |
| 530 | ser::SerializeSeq::serialize_element(self, value) |
| 531 | } |
| 532 | |
| 533 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 534 | Ok(PyTuple::new(self.py, self.items)?.into_any()) |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | impl<'py, P: PythonizeTypes> ser::SerializeTupleStruct for PythonCollectionSerializer<'py, P> { |
| 539 | type Ok = Bound<'py, PyAny>; |
| 540 | type Error = PythonizeError; |
| 541 | |
| 542 | fn serialize_field<T>(&mut self, value: &T) -> Result<()> |
| 543 | where |
| 544 | T: ?Sized + Serialize, |
| 545 | { |
| 546 | ser::SerializeSeq::serialize_element(self, value) |
| 547 | } |
| 548 | |
| 549 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 550 | ser::SerializeTuple::end(self) |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | impl<'py, P: PythonizeTypes> ser::SerializeTupleVariant for PythonTupleVariantSerializer<'py, P> { |
| 555 | type Ok = Bound<'py, PyAny>; |
| 556 | type Error = PythonizeError; |
| 557 | |
| 558 | fn serialize_field<T>(&mut self, value: &T) -> Result<()> |
| 559 | where |
| 560 | T: ?Sized + Serialize, |
| 561 | { |
| 562 | ser::SerializeSeq::serialize_element(&mut self.inner, value) |
| 563 | } |
| 564 | |
| 565 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 566 | let mut m = P::NamedMap::builder(self.inner.py, 1, self.name)?; |
| 567 | P::NamedMap::push_field( |
| 568 | &mut m, |
| 569 | PyString::new(self.inner.py, self.variant), |
| 570 | ser::SerializeTuple::end(self.inner)?, |
| 571 | )?; |
| 572 | Ok(P::NamedMap::finish(m)?.into_any()) |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | impl<'py, P: PythonizeTypes> ser::SerializeMap for PythonMapSerializer<'py, P> { |
| 577 | type Ok = Bound<'py, PyAny>; |
| 578 | type Error = PythonizeError; |
| 579 | |
| 580 | fn serialize_key<T>(&mut self, key: &T) -> Result<()> |
| 581 | where |
| 582 | T: ?Sized + Serialize, |
| 583 | { |
| 584 | self.key = Some(pythonize_custom::<P, _>(self.py, key)?); |
| 585 | Ok(()) |
| 586 | } |
| 587 | |
| 588 | fn serialize_value<T>(&mut self, value: &T) -> Result<()> |
| 589 | where |
| 590 | T: ?Sized + Serialize, |
| 591 | { |
| 592 | P::Map::push_item( |
| 593 | &mut self.builder, |
| 594 | self.key |
| 595 | .take() |
| 596 | .expect("serialize_value should always be called after serialize_key"), |
| 597 | pythonize_custom::<P, _>(self.py, value)?, |
| 598 | )?; |
| 599 | Ok(()) |
| 600 | } |
| 601 | |
| 602 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 603 | Ok(P::Map::finish(self.builder)?.into_any()) |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | #[cfg(feature = "arbitrary_precision")] |
| 608 | impl<'py, P: PythonizeTypes> ser::SerializeStruct for StructSerializer<'py, P> { |
| 609 | type Ok = Bound<'py, PyAny>; |
| 610 | type Error = PythonizeError; |
| 611 | |
| 612 | fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> |
| 613 | where |
| 614 | T: ?Sized + Serialize, |
| 615 | { |
| 616 | match self { |
| 617 | StructSerializer::Struct(s) => s.serialize_field(key, value), |
| 618 | StructSerializer::Number { number_string, .. } => { |
| 619 | let serde_json::Value::String(s) = value |
| 620 | .serialize(serde_json::value::Serializer) |
| 621 | .map_err(|e| { |
| 622 | PythonizeError::msg(format!("Failed to serialize number: {}", e)) |
| 623 | })? |
| 624 | else { |
| 625 | return Err(PythonizeError::msg("Expected string in serde_json::Number")); |
| 626 | }; |
| 627 | |
| 628 | *number_string = Some(s); |
| 629 | Ok(()) |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 635 | match self { |
| 636 | StructSerializer::Struct(s) => s.end(), |
| 637 | StructSerializer::Number { |
| 638 | py, |
| 639 | number_string: Some(s), |
| 640 | .. |
| 641 | } => { |
| 642 | if let Ok(i) = s.parse::<i64>() { |
| 643 | return Ok(PyInt::new(py, i).into_any()); |
| 644 | } |
| 645 | if let Ok(u) = s.parse::<u64>() { |
| 646 | return Ok(PyInt::new(py, u).into_any()); |
| 647 | } |
| 648 | if s.chars().any(|c| c == '.' || c == 'e' || c == 'E') { |
| 649 | if let Ok(f) = s.parse::<f64>() { |
| 650 | return Ok(PyFloat::new(py, f).into_any()); |
| 651 | } |
| 652 | } |
| 653 | // Fall back to Python's int() constructor, which supports arbitrary precision. |
| 654 | py.get_type::<PyInt>() |
| 655 | .call1((s.as_str(),)) |
| 656 | .map_err(|e| PythonizeError::msg(format!("Invalid number: {}", e))) |
| 657 | } |
| 658 | StructSerializer::Number { .. } => Err(PythonizeError::msg("Empty serde_json::Number")), |
| 659 | } |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | impl<'py, P: PythonizeTypes> ser::SerializeStruct for PythonStructDictSerializer<'py, P> { |
| 664 | type Ok = Bound<'py, PyAny>; |
| 665 | type Error = PythonizeError; |
| 666 | |
| 667 | fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> |
| 668 | where |
| 669 | T: ?Sized + Serialize, |
| 670 | { |
| 671 | P::NamedMap::push_field( |
| 672 | &mut self.builder, |
| 673 | PyString::new(self.py, key), |
| 674 | pythonize_custom::<P, _>(self.py, value)?, |
| 675 | )?; |
| 676 | Ok(()) |
| 677 | } |
| 678 | |
| 679 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 680 | Ok(P::NamedMap::finish(self.builder)?.into_any()) |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | impl<'py, P: PythonizeTypes> ser::SerializeStructVariant for PythonStructVariantSerializer<'py, P> { |
| 685 | type Ok = Bound<'py, PyAny>; |
| 686 | type Error = PythonizeError; |
| 687 | |
| 688 | fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> |
| 689 | where |
| 690 | T: ?Sized + Serialize, |
| 691 | { |
| 692 | P::NamedMap::push_field( |
| 693 | &mut self.inner.builder, |
| 694 | PyString::new(self.inner.py, key), |
| 695 | pythonize_custom::<P, _>(self.inner.py, value)?, |
| 696 | )?; |
| 697 | Ok(()) |
| 698 | } |
| 699 | |
| 700 | fn end(self) -> Result<Bound<'py, PyAny>> { |
| 701 | let v = P::NamedMap::finish(self.inner.builder)?; |
| 702 | let mut m = P::NamedMap::builder(self.inner.py, 1, self.name)?; |
| 703 | P::NamedMap::push_field( |
| 704 | &mut m, |
| 705 | PyString::new(self.inner.py, self.variant), |
| 706 | v.into_any(), |
| 707 | )?; |
| 708 | Ok(P::NamedMap::finish(m)?.into_any()) |
| 709 | } |
| 710 | } |
| 711 | |
| 712 | #[cfg(test)] |
| 713 | mod test { |
| 714 | use super::pythonize; |
| 715 | use maplit::hashmap; |
| 716 | use pyo3::prelude::*; |
| 717 | use pyo3::pybacked::PyBackedStr; |
| 718 | use pyo3::types::{PyBytes, PyDict}; |
| 719 | use serde::Serialize; |
| 720 | |
| 721 | fn test_ser<T>(src: T, expected: &str) |
| 722 | where |
| 723 | T: Serialize, |
| 724 | { |
| 725 | Python::attach(|py| -> PyResult<()> { |
| 726 | let obj = pythonize(py, &src)?; |
| 727 | |
| 728 | let locals = PyDict::new(py); |
| 729 | locals.set_item("obj", obj)?; |
| 730 | |
| 731 | py.run( |
| 732 | c"import json; result = json.dumps(obj, separators=(',', ':'))", |
| 733 | None, |
| 734 | Some(&locals), |
| 735 | )?; |
| 736 | let result = locals.get_item("result")?.unwrap(); |
| 737 | let result = result.extract::<PyBackedStr>()?; |
| 738 | |
| 739 | assert_eq!(result, expected); |
| 740 | assert_eq!(serde_json::to_string(&src).unwrap(), expected); |
| 741 | |
| 742 | Ok(()) |
| 743 | }) |
| 744 | .unwrap(); |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn test_empty_struct() { |
| 749 | #[derive(Serialize)] |
| 750 | struct Empty; |
| 751 | |
| 752 | test_ser(Empty, "null"); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn test_struct() { |
| 757 | #[derive(Serialize)] |
| 758 | struct Struct { |
| 759 | foo: String, |
| 760 | bar: usize, |
| 761 | } |
| 762 | |
| 763 | test_ser( |
| 764 | Struct { |
| 765 | foo: "foo".to_string(), |
| 766 | bar: 5, |
| 767 | }, |
| 768 | r#"{"foo":"foo","bar":5}"#, |
| 769 | ); |
| 770 | } |
| 771 | |
| 772 | #[test] |
| 773 | fn test_nested_struct() { |
| 774 | #[derive(Serialize)] |
| 775 | struct Foo { |
| 776 | name: String, |
| 777 | bar: Bar, |
| 778 | } |
| 779 | |
| 780 | #[derive(Serialize)] |
| 781 | struct Bar { |
| 782 | name: String, |
| 783 | } |
| 784 | |
| 785 | test_ser( |
| 786 | Foo { |
| 787 | name: "foo".to_string(), |
| 788 | bar: Bar { |
| 789 | name: "bar".to_string(), |
| 790 | }, |
| 791 | }, |
| 792 | r#"{"name":"foo","bar":{"name":"bar"}}"#, |
| 793 | ) |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn test_tuple_struct() { |
| 798 | #[derive(Serialize)] |
| 799 | struct TupleStruct(String, usize); |
| 800 | |
| 801 | test_ser(TupleStruct("foo".to_string(), 5), r#"["foo",5]"#); |
| 802 | } |
| 803 | |
| 804 | #[test] |
| 805 | fn test_tuple() { |
| 806 | test_ser(("foo", 5), r#"["foo",5]"#); |
| 807 | } |
| 808 | |
| 809 | #[test] |
| 810 | fn test_vec() { |
| 811 | test_ser(vec![1, 2, 3], r#"[1,2,3]"#); |
| 812 | } |
| 813 | |
| 814 | #[test] |
| 815 | fn test_map() { |
| 816 | test_ser(hashmap! {"foo" => "foo"}, r#"{"foo":"foo"}"#); |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn test_enum_unit_variant() { |
| 821 | #[derive(Serialize)] |
| 822 | enum E { |
| 823 | Empty, |
| 824 | } |
| 825 | |
| 826 | test_ser(E::Empty, r#""Empty""#); |
| 827 | } |
| 828 | |
| 829 | #[test] |
| 830 | fn test_enum_tuple_variant() { |
| 831 | #[derive(Serialize)] |
| 832 | enum E { |
| 833 | Tuple(i32, String), |
| 834 | } |
| 835 | |
| 836 | test_ser(E::Tuple(5, "foo".to_string()), r#"{"Tuple":[5,"foo"]}"#); |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn test_enum_newtype_variant() { |
| 841 | #[derive(Serialize)] |
| 842 | enum E { |
| 843 | NewType(String), |
| 844 | } |
| 845 | |
| 846 | test_ser(E::NewType("foo".to_string()), r#"{"NewType":"foo"}"#); |
| 847 | } |
| 848 | |
| 849 | #[test] |
| 850 | fn test_enum_struct_variant() { |
| 851 | #[derive(Serialize)] |
| 852 | enum E { |
| 853 | Struct { foo: String, bar: usize }, |
| 854 | } |
| 855 | |
| 856 | test_ser( |
| 857 | E::Struct { |
| 858 | foo: "foo".to_string(), |
| 859 | bar: 5, |
| 860 | }, |
| 861 | r#"{"Struct":{"foo":"foo","bar":5}}"#, |
| 862 | ); |
| 863 | } |
| 864 | |
| 865 | #[test] |
| 866 | fn test_integers() { |
| 867 | #[derive(Serialize)] |
| 868 | struct Integers { |
| 869 | a: i8, |
| 870 | b: i16, |
| 871 | c: i32, |
| 872 | d: i64, |
| 873 | e: u8, |
| 874 | f: u16, |
| 875 | g: u32, |
| 876 | h: u64, |
| 877 | } |
| 878 | |
| 879 | test_ser( |
| 880 | Integers { |
| 881 | a: 1, |
| 882 | b: 2, |
| 883 | c: 3, |
| 884 | d: 4, |
| 885 | e: 5, |
| 886 | f: 6, |
| 887 | g: 7, |
| 888 | h: 8, |
| 889 | }, |
| 890 | r#"{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8}"#, |
| 891 | ) |
| 892 | } |
| 893 | |
| 894 | #[test] |
| 895 | fn test_floats() { |
| 896 | #[derive(Serialize)] |
| 897 | struct Floats { |
| 898 | a: f32, |
| 899 | b: f64, |
| 900 | } |
| 901 | |
| 902 | test_ser(Floats { a: 1.0, b: 2.0 }, r#"{"a":1.0,"b":2.0}"#) |
| 903 | } |
| 904 | |
| 905 | #[test] |
| 906 | fn test_char() { |
| 907 | #[derive(Serialize)] |
| 908 | struct Char { |
| 909 | a: char, |
| 910 | } |
| 911 | |
| 912 | test_ser(Char { a: 'a' }, r#"{"a":"a"}"#) |
| 913 | } |
| 914 | |
| 915 | #[test] |
| 916 | fn test_bool() { |
| 917 | test_ser(true, "true"); |
| 918 | test_ser(false, "false"); |
| 919 | } |
| 920 | |
| 921 | #[test] |
| 922 | fn test_none() { |
| 923 | #[derive(Serialize)] |
| 924 | struct S; |
| 925 | |
| 926 | test_ser((), "null"); |
| 927 | test_ser(S, "null"); |
| 928 | |
| 929 | test_ser(Some(1), "1"); |
| 930 | test_ser(None::<i32>, "null"); |
| 931 | } |
| 932 | |
| 933 | #[test] |
| 934 | fn test_bytes() { |
| 935 | // serde treats &[u8] as a sequence of integers due to lack of specialization |
| 936 | test_ser(b"foo", "[102,111,111]"); |
| 937 | |
| 938 | Python::attach(|py| { |
| 939 | assert!(pythonize(py, serde_bytes::Bytes::new(b"foo")) |
| 940 | .expect("bytes will always serialize successfully") |
| 941 | .eq(&PyBytes::new(py, b"foo")) |
| 942 | .expect("bytes will always compare successfully")); |
| 943 | }); |
| 944 | } |
| 945 | } |