Implement #[serde(with = "...")] for containers
#3014
+341
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1118, at least the original request. I understand some people wanted finalizers / some other kind of thing, this does not address that but I can't really see how it would be incompatible with doing that as well later. On the
deside, this is just another implementation fordeserialize_body, like from/try_from/transparent. Edit: indeed, seems compatible with #2891, which runs straight afterdeserialize_body.I submit this PR out of light frustration, from the 100 times in the last decade that I have tried to write
#[serde(with)]on a container and it hasn't existed.serde(with)modules and functions are fantastic and very reusable, and there's a whole ecosystem built around them, but they come with the silly caveat that they do not work on containers. It's silly because the pattern works on a single-variant enum, which is really just a struct, but not a struct that happens to be a container. It's an attribute that could work anywhere and function identically, but doesn't. So I think this is long overdue.I came to this specifically after trying to tweak the serialization for a whole lot of
bitflagsflags. V2 of bitflags changed the serialization format to a string representation"A | B", which I have gripes with as a default, but ok. The only way to change to integer serialization for all of the bitflags is toimpl Serializeandimpl Deserializeon all of them, which is a lot of boilerplate. There's bitflags-serde-legacy, which would be much easier to use if only#[serde(with)]worked on containers. With this functionality, you can just write a serde-with module that's generic overT: bitflags::Flags, and you're done.Would need docs at https://serde.rs/container-attrs.html