Skip to content

Commit

Permalink
Merge pull request #62 from juntyr/named-mapping-items
Browse files Browse the repository at this point in the history
Support serialising to named mappings
  • Loading branch information
davidhewitt authored Aug 7, 2024
2 parents 6c2c3f2 + 7c18b9f commit d7f54f1
Show file tree
Hide file tree
Showing 6 changed files with 345 additions and 82 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
- `Depythonizer` now contains a `&Bound` and so has an extra lifetime `'bound`
- `Depythonizer::from_object()` now takes a `&Bound` and is no longer deprecated
- Fix overflow error attempting to depythonize `u64` values greater than `i64::MAX` to types like `serde_json::Value`
- Implement `PythonizeListType` for `PyTuple`
- Support deserializing enums from any `PyMapping` instead of just `PyDict`
- Support serializing struct-like types to named mappings using `PythonizeTypes::NamedMap`

## 0.21.1 - 2024-04-02

Expand Down
16 changes: 8 additions & 8 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,21 +294,21 @@ impl<'a, 'py, 'de, 'bound> de::Deserializer<'de> for &'a mut Depythonizer<'py, '
V: de::Visitor<'de>,
{
let item = &self.input;
if let Ok(d) = item.downcast::<PyDict>() {
// Get the enum variant from the dict key
if d.len() != 1 {
if let Ok(s) = item.downcast::<PyString>() {
visitor.visit_enum(s.to_cow()?.into_deserializer())
} else if let Ok(m) = item.downcast::<PyMapping>() {
// Get the enum variant from the mapping key
if m.len()? != 1 {
return Err(PythonizeError::invalid_length_enum());
}
let variant = d
.keys()
let variant: Bound<PyString> = m
.keys()?
.get_item(0)?
.downcast_into::<PyString>()
.map_err(|_| PythonizeError::dict_key_not_string())?;
let value = d.get_item(&variant)?.unwrap();
let value = m.get_item(&variant)?;
let mut de = Depythonizer::from_object(&value);
visitor.visit_enum(PyEnumAccess::new(&mut de, variant))
} else if let Ok(s) = item.downcast::<PyString>() {
visitor.visit_enum(s.to_cow()?.into_deserializer())
} else {
Err(PythonizeError::invalid_enum_type())
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ pub use crate::de::depythonize_bound;
pub use crate::de::{depythonize, Depythonizer};
pub use crate::error::{PythonizeError, Result};
pub use crate::ser::{
pythonize, pythonize_custom, PythonizeDefault, PythonizeDictType, PythonizeListType,
PythonizeTypes, Pythonizer,
pythonize, pythonize_custom, PythonizeDefault, PythonizeListType, PythonizeMappingType,
PythonizeNamedMappingType, PythonizeTypes, PythonizeUnnamedMappingAdapter, Pythonizer,
};
Loading

0 comments on commit d7f54f1

Please sign in to comment.