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.
§Converting to serde_as
The same functionality can be more clearly expressed using the serde_as
macro and SetPreventDuplicates
.
The _
is a placeholder which works for any type which implements Serialize
/Deserialize
.
#[serde_as]
#[derive(Deserialize, Serialize)]
struct A {
#[serde_as(as = "SetPreventDuplicates<_, _>")]
s: HashSet<usize>,
}
§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