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

Way to pair serialize_with and deserialize_with into one attribute #763

Closed
dtolnay opened this issue Feb 14, 2017 · 5 comments
Closed

Way to pair serialize_with and deserialize_with into one attribute #763

dtolnay opened this issue Feb 14, 2017 · 5 comments
Assignees

Comments

@dtolnay
Copy link
Member

dtolnay commented Feb 14, 2017

#[serde(serialize_with = "url_serde::serialize",
        deserialize_with = "url_serde::deserialize")]

This gets tedious because you almost always want these paired. Can we deduplicate into one attribute?

#[serde(with = "url_serde")]
@oli-obk
Copy link
Member

oli-obk commented Feb 14, 2017

So the use = "type" would require type to implement both Serialize and Deserialize (barring further attributes like deserialize_default)?

@dtolnay
Copy link
Member Author

dtolnay commented Feb 14, 2017

I haven't thought about how it would work yet.

I think the way you are suggesting is you give the attribute a path to a wrapper type:

struct Url(url::Url);
impl Serialize for Url { ... }
impl Deserialize for Url { ... }

A different approach that would be more similar to serialize_with and deserialize_with would be to give the attribute a path to a module containing ser and de functions:

mod url {
    fn serialize<S>(...) { ... }
    fn deserialize<D>(...) { ... }
}

Right now I am leaning toward the module approach because it means that simple wrapper libraries like url_serde can be used just with #[serde(use = "url_serde")].

@oli-obk
Copy link
Member

oli-obk commented Feb 14, 2017

Oh, your idea is much more general, since it also supports the case where the "wrapper type" is not a wrapper type at all, but e.g. some random type from another crate.

@dtolnay
Copy link
Member Author

dtolnay commented Feb 15, 2017

@nox my mod proposal would work with hyper_serde out of the box without any code change on your end.

 #[derive(Serialize, Deserialize)]
 struct MyStruct {
-    #[serde(deserialize_with = "hyper_serde::deserialize",
-            serialize_with = "hyper_serde::serialize")]
+    #[serde(with = "hyper_serde")]
     headers: Headers,
 }

Any concerns or suggestions?

@dtolnay
Copy link
Member Author

dtolnay commented Feb 21, 2017

I released this in 0.9.8.

@dtolnay dtolnay self-assigned this Apr 9, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants