Module serde_with::rust::sets_duplicate_value_is_error
source · [−]Expand description
Ensure no duplicate values exist in a set.
By default serde has a last-value-wins implementation, if duplicate values for a set exist. Sometimes it is desirable to know when such an event happens, as the first value is overwritten and it can indicate an error in the serialized data.
This helper returns an error if two identical values exist in a set.
The implementation supports both the HashSet
and the BTreeSet
from the standard library.
Example
#[derive(Deserialize)]
struct Doc {
#[serde(with = "::serde_with::rust::sets_duplicate_value_is_error")]
set: HashSet<usize>,
}
// Sets are serialized normally,
let s = r#"{"set": [1, 2, 3, 4]}"#;
let v = Doc {
set: HashSet::from_iter(vec![1, 2, 3, 4]),
};
assert_eq!(v, serde_json::from_str(s).unwrap());
// but create an error if duplicate values, like the `1`, exist.
let s = r#"{"set": [1, 2, 3, 4, 1]}"#;
let res: Result<Doc, _> = serde_json::from_str(s);
assert!(res.is_err());
Functions
Deserialize a set and return an error on duplicate values
Serialize the set with the default serializer