Module serde_with::rust::maps_first_key_wins

source ·
Expand description

Ensure that the first key is taken, if duplicate keys exist

By default serde has a last-key-wins implementation, if duplicate keys for a map exist. Sometimes the opposite strategy is desired. This helper implements a first-key-wins strategy.

The implementation supports both the HashMap and the BTreeMap from the standard library.

§Converting to serde_as

The same functionality can be more clearly expressed using the serde_as macro and MapFirstKeyWins. The _ is a placeholder which works for any type which implements Serialize/Deserialize.

#[serde_as]
#[derive(Deserialize, Serialize)]
struct A {
    #[serde_as(as = "MapFirstKeyWins<_, _>")]
    s: HashMap<usize, usize>,
}

§Example

#[derive(Deserialize)]
struct Doc {
    #[serde(with = "::serde_with::rust::maps_first_key_wins")]
    map: HashMap<usize, usize>,
}

// Maps are serialized normally,
let s = r#"{"map": {"1": 1, "2": 2, "3": 3}}"#;
let mut v = Doc {
    map: HashMap::new(),
};
v.map.insert(1, 1);
v.map.insert(2, 2);
v.map.insert(3, 3);
assert_eq!(v, serde_json::from_str(s).unwrap());

// but create an error if duplicate keys, like the `1`, exist.
let s = r#"{"map": {"1": 1, "2": 2, "1": 3}}"#;
let mut v = Doc {
    map: HashMap::new(),
};
v.map.insert(1, 1);
v.map.insert(2, 2);
assert_eq!(v, serde_json::from_str(s).unwrap());

Functions§

  • Deserialize a map and return an error on duplicate keys
  • Serialize the map with the default serializer