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

Add helpers to deserialize into Option or Result #17

Merged
merged 3 commits into from
May 16, 2024
Merged

Conversation

romac
Copy link
Member

@romac romac commented May 15, 2024

cc @bugarela

Option

use serde::Deserialize;
use serde_json::json;

use itf::de::{self, As};

#[derive(Debug, PartialEq, Deserialize)]
struct FooOption {
    #[serde(with = "As::<de::Option::<_>>")]
    foo: Option<u64>,
}

let some_itf = json!({
    "foo": {
        "tag": "Some",
        "value": 42,
    }
});

let some_foo = itf::from_value::<FooOption>(some_itf).unwrap();
assert_eq!(some_foo, FooOption { foo: Some(42) });

let none_itf = json!({
    "foo": {
        "tag": "None",
        "value": {},
    }
});

let none_foo = itf::from_value::<FooOption>(none_itf).unwrap();
assert_eq!(none_foo, FooOption { foo: None });

Result

use serde::Deserialize;
use serde_json::json;

use itf::de::{self, As};

#[derive(Debug, PartialEq, Deserialize)]
struct FooResult {
    #[serde(with = "As::<de::Result::<_, _>>")]
    foo: Result<u64, u64>,
}

let ok_itf = json!({
    "foo": {
        "tag": "Ok",
        "value": 42,
    }
});

let ok = itf::from_value::<FooResult>(ok_itf).unwrap();
assert_eq!(ok.foo, Ok(42));

let err_itf = json!({
    "foo": {
        "tag": "Err",
        "value": 42,
    }
});

let err = itf::from_value::<FooResult>(err_itf).unwrap();
assert_eq!(err.foo, Err(42));

Copy link

@bugarela bugarela left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot @romac, this is exactly what I need!

@romac romac force-pushed the romac/option-result branch from 7293402 to da538c0 Compare May 16, 2024 07:07
@romac romac marked this pull request as ready for review May 16, 2024 07:08
@romac romac changed the title Add helper to deserialize into Option or Result Add helpers to deserialize into Option or Result May 16, 2024
@romac romac merged commit e9c5fce into main May 16, 2024
5 checks passed
@romac romac deleted the romac/option-result branch May 16, 2024 07:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants