-
Notifications
You must be signed in to change notification settings - Fork 150
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 serde_seq to serialize maps as a sequence #158
Conversation
//! The default `serde` implementation serializes `IndexMap` as a normal map, | ||
//! but there is no guarantee that serialization formats will preserve the order | ||
//! of the key-value pairs. This module serializes `IndexMap` as a sequence of | ||
//! `(key, value)` elements instead, in order. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure whether serializing tuples is a good choice, although it's the easiest to implement. Alternatively, serde sequences may be heterogeneous, so we could use a flat sequence of key0, value0, key1, value1, ...
instead. I don't know whether all serialization formats support that though.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is also just a helper, so we don't have to be perfect here. A third party can write a similar custom module with different choices, as there aren't issues like trait coherence for this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yet another possibility is a pair of sequences, ([key, ...], [value, ...])
, but when deserializing we would have to read keys into temporary storage before we start reading values and insert into the map.
This seems good to support, I fear most users won't find this feature until after the first bug happens, but at least there's a solution then. |
Our default serde implementation treats `IndexMap` as a normal map, which is often a nice representation in serialization formats, but they might not preserve the order. This commit adds a `serde_seq` module with `serialize` and `deserialize` functions, which makes it suitable for serde's field attributes, like `#[serde(with = "indexmap::serde_seq")]`. This mode treats `IndexMap` as a sequence of `(key, value)` pairs, which should always preserve order.
Our default serde implementation treats
IndexMap
as a normal map,which is often a nice representation in serialization formats, but they
might not preserve the order.
This commit adds a
serde_seq
module withserialize
anddeserialize
functions, which makes it suitable for serde's field attributes, like
#[serde(with = "indexmap::serde_seq")]
. This mode treatsIndexMap
asa sequence of
(key, value)
pairs, which should always preserve order.Closes #156.