Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement new adapter PickFirst, picking between multiple deserialization options #291

Merged
merged 4 commits into from
Mar 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## Unreleased

### Added

* Added `PickFirst` adapter for `serde_as`.
It allows to deserialize from multiple different forms.
Deserializing a number from either a number or string can be implemented like:

```rust
#[serde_as(as = "PickFirst<(_, DisplayFromStr)>")]
value: u32,
```

### Changed

* Add a new `serde_with::rust::map_as_tuple_list` module as a replacement for `serde_with::rust::btreemap_as_tuple_list` and `serde_with::rust::hashmap_as_tuple_list`.
Expand Down
143 changes: 142 additions & 1 deletion src/de/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,148 @@ where
match h {
Helper::One(one) => Ok(vec![one.into_inner()]),
Helper::Many(many) => Ok(many.into_inner()),
_ => unreachable!(),
Helper::_JustAMarkerForTheLifetime(_) => unreachable!(),
}
}
}

impl<'de, T, TAs1> DeserializeAs<'de, T> for PickFirst<(TAs1,)>
where
TAs1: DeserializeAs<'de, T>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
{
Ok(DeserializeAsWrap::<T, TAs1>::deserialize(deserializer)?.into_inner())
}
}

impl<'de, T, TAs1, TAs2> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2)>
where
TAs1: DeserializeAs<'de, T>,
TAs2: DeserializeAs<'de, T>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(
untagged,
bound(deserialize = r#"
DeserializeAsWrap<T, TAs1>: Deserialize<'de>,
DeserializeAsWrap<T, TAs2>: Deserialize<'de>,
"#),
expecting = "PickFirst could not deserialize data"
)]
enum Helper<'a, T, TAs1, TAs2>
where
TAs1: DeserializeAs<'a, T>,
TAs2: DeserializeAs<'a, T>,
{
First(DeserializeAsWrap<T, TAs1>),
Second(DeserializeAsWrap<T, TAs2>),
#[serde(skip)]
_JustAMarkerForTheLifetime(PhantomData<&'a u32>),
}

let h: Helper<'de, T, TAs1, TAs2> = Deserialize::deserialize(deserializer)?;
match h {
Helper::First(first) => Ok(first.into_inner()),
Helper::Second(second) => Ok(second.into_inner()),
Helper::_JustAMarkerForTheLifetime(_) => unreachable!(),
}
}
}

impl<'de, T, TAs1, TAs2, TAs3> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3)>
where
TAs1: DeserializeAs<'de, T>,
TAs2: DeserializeAs<'de, T>,
TAs3: DeserializeAs<'de, T>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(
untagged,
bound(deserialize = r#"
DeserializeAsWrap<T, TAs1>: Deserialize<'de>,
DeserializeAsWrap<T, TAs2>: Deserialize<'de>,
DeserializeAsWrap<T, TAs3>: Deserialize<'de>,
"#),
expecting = "PickFirst could not deserialize data"
)]
enum Helper<'a, T, TAs1, TAs2, TAs3>
where
TAs1: DeserializeAs<'a, T>,
TAs2: DeserializeAs<'a, T>,
TAs3: DeserializeAs<'a, T>,
{
First(DeserializeAsWrap<T, TAs1>),
Second(DeserializeAsWrap<T, TAs2>),
Third(DeserializeAsWrap<T, TAs3>),
#[serde(skip)]
_JustAMarkerForTheLifetime(PhantomData<&'a u32>),
}

let h: Helper<'de, T, TAs1, TAs2, TAs3> = Deserialize::deserialize(deserializer)?;
match h {
Helper::First(first) => Ok(first.into_inner()),
Helper::Second(second) => Ok(second.into_inner()),
Helper::Third(third) => Ok(third.into_inner()),
Helper::_JustAMarkerForTheLifetime(_) => unreachable!(),
}
}
}

impl<'de, T, TAs1, TAs2, TAs3, TAs4> DeserializeAs<'de, T> for PickFirst<(TAs1, TAs2, TAs3, TAs4)>
where
TAs1: DeserializeAs<'de, T>,
TAs2: DeserializeAs<'de, T>,
TAs3: DeserializeAs<'de, T>,
TAs4: DeserializeAs<'de, T>,
{
fn deserialize_as<D>(deserializer: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(
untagged,
bound(deserialize = r#"
DeserializeAsWrap<T, TAs1>: Deserialize<'de>,
DeserializeAsWrap<T, TAs2>: Deserialize<'de>,
DeserializeAsWrap<T, TAs3>: Deserialize<'de>,
DeserializeAsWrap<T, TAs4>: Deserialize<'de>,
"#),
expecting = "PickFirst could not deserialize data"
)]
enum Helper<'a, T, TAs1, TAs2, TAs3, TAs4>
where
TAs1: DeserializeAs<'a, T>,
TAs2: DeserializeAs<'a, T>,
TAs3: DeserializeAs<'a, T>,
TAs4: DeserializeAs<'a, T>,
{
First(DeserializeAsWrap<T, TAs1>),
Second(DeserializeAsWrap<T, TAs2>),
Third(DeserializeAsWrap<T, TAs3>),
Forth(DeserializeAsWrap<T, TAs4>),
#[serde(skip)]
_JustAMarkerForTheLifetime(PhantomData<&'a u32>),
}

let h: Helper<'de, T, TAs1, TAs2, TAs3, TAs4> = Deserialize::deserialize(deserializer)?;
match h {
Helper::First(first) => Ok(first.into_inner()),
Helper::Second(second) => Ok(second.into_inner()),
Helper::Third(third) => Ok(third.into_inner()),
Helper::Forth(forth) => Ok(forth.into_inner()),
Helper::_JustAMarkerForTheLifetime(_) => unreachable!(),
}
}
}
25 changes: 22 additions & 3 deletions src/guide/serde_as.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ The basic design of the system was done by [@markazmierczak](https://github.com/
9. [`NaiveDateTime` like UTC timestamp](#naivedatetime-like-utc-timestamp)
10. [`None` as empty `String`](#none-as-empty-string)
11. [One or many elements into `Vec`](#one-or-many-elements-into-vec)
12. [Timestamps as seconds since UNIX epoch](#timestamps-as-seconds-since-unix-epoch)
13. [Value into JSON String](#value-into-json-string)
14. [`Vec` of tuples to `Maps`](#vec-of-tuples-to-maps)
12. [Pick first successful deserialization](#pick-first-successful-deserialization)
13. [Timestamps as seconds since UNIX epoch](#timestamps-as-seconds-since-unix-epoch)
14. [Value into JSON String](#value-into-json-string)
15. [`Vec` of tuples to `Maps`](#vec-of-tuples-to-maps)

## Switching from serde's with to `serde_as`

Expand Down Expand Up @@ -470,6 +471,23 @@ value: Vec<String>,
"value": ["Hello", "World!"], // or lists of many
```

### Pick first successful deserialization

[`PickFirst`]

```ignore
// Rust
#[serde_as(as = "serde_with::PickFirst<(_, serde_with::DisplayFromStr)>")]
value: u32,

// JSON
// serialize into
"value": 666,
// deserialize from either
"value": 666,
"value": "666",
```

### Timestamps as seconds since UNIX epoch

[`TimestampSeconds`]
Expand Down Expand Up @@ -562,6 +580,7 @@ The [inverse operation](#maps-to-vec-of-tuples) is also available.
[`JsonString`]: crate::json::JsonString
[`NoneAsEmptyString`]: crate::NoneAsEmptyString
[`OneOrMany`]: crate::OneOrMany
[`PickFirst`]: crate::PickFirst
[`SerializeAs`]: crate::SerializeAs
[bytes to string converter]: crate::BytesOrString
[duration to UNIX epoch]: crate::DurationSeconds
Expand Down
61 changes: 61 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1495,3 +1495,64 @@ pub struct Bytes;
/// ```
#[derive(Copy, Clone, Debug, Default)]
pub struct OneOrMany<T, FORMAT: formats::Format = formats::PreferOne>(PhantomData<(T, FORMAT)>);

/// Try multiple deserialization options until one succeeds.
///
/// This adapter allows you to specify a list of deserialization options.
/// They are tried in order and the first one working is applied.
/// Serialization always picks the first option.
///
/// `PickFirst` has one type parameter which must be instanciated with a tuple of two, three, or four elements.
/// For example, `PickFirst<(_, DisplayFromStr)>` on a field of type `u32` allows to deserialize from a number or from a string via the `FromStr` trait.
/// The value will be serialized as a number, since that is what the first type `_` indicates.
///
/// # Examples
///
/// Deserialize a number from either a number or a string.
///
/// ```rust
/// # #[cfg(feature = "macros")] {
/// # use serde::Deserialize;
/// # use serde_json::json;
/// # use serde_with::{serde_as, DisplayFromStr, PickFirst};
/// #
/// #[serde_as]
/// # #[derive(Debug, PartialEq)]
/// #[derive(Deserialize, serde::Serialize)]
/// struct Data {
/// #[serde_as(as = "PickFirst<(_, DisplayFromStr)>")]
/// as_number: u32,
/// #[serde_as(as = "PickFirst<(DisplayFromStr, _)>")]
/// as_string: u32,
/// }
/// let data = Data {
/// as_number: 123,
/// as_string: 456
/// };
///
/// // Both fields can be deserialized from numbers:
/// let j = json!({
/// "as_number": 123,
/// "as_string": 456,
/// });
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // or from a string:
/// let j = json!({
/// "as_number": "123",
/// "as_string": "456",
/// });
/// assert_eq!(data, serde_json::from_value(j).unwrap());
///
/// // For serialization the first type in the tuple determines the behavior.
/// // The `as_number` field will use the normal `Serialize` behavior and produce a number,
/// // while `as_string` used `Display` to produce a string.
/// let expected = json!({
/// "as_number": 123,
/// "as_string": "456",
/// });
/// assert_eq!(expected, serde_json::to_value(&data).unwrap());
/// # }
/// ```
#[derive(Copy, Clone, Debug, Default)]
pub struct PickFirst<T>(PhantomData<T>);
48 changes: 48 additions & 0 deletions src/ser/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,3 +440,51 @@ where
SerializeAsWrap::<Vec<T>, Vec<U>>::new(source).serialize(serializer)
}
}

impl<T, TAs1> SerializeAs<T> for PickFirst<(TAs1,)>
where
TAs1: SerializeAs<T>,
{
fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
SerializeAsWrap::<T, TAs1>::new(source).serialize(serializer)
}
}

impl<T, TAs1, TAs2> SerializeAs<T> for PickFirst<(TAs1, TAs2)>
where
TAs1: SerializeAs<T>,
{
fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
SerializeAsWrap::<T, TAs1>::new(source).serialize(serializer)
}
}

impl<T, TAs1, TAs2, TAs3> SerializeAs<T> for PickFirst<(TAs1, TAs2, TAs3)>
where
TAs1: SerializeAs<T>,
{
fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
SerializeAsWrap::<T, TAs1>::new(source).serialize(serializer)
}
}

impl<T, TAs1, TAs2, TAs3, TAs4> SerializeAs<T> for PickFirst<(TAs1, TAs2, TAs3, TAs4)>
where
TAs1: SerializeAs<T>,
{
fn serialize_as<S>(source: &T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
SerializeAsWrap::<T, TAs1>::new(source).serialize(serializer)
}
}
1 change: 1 addition & 0 deletions tests/serde_as/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

mod default_on;
mod map_tuple_list;
mod pickfirst;
mod serde_as_macro;
mod time;
#[path = "../utils.rs"]
Expand Down
Loading