Skip to content
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 feature to error on duplicate key in Map<String, Value> #1113

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,8 @@ raw_value = []
# overflow the stack after deserialization has completed, including, but not
# limited to, Display and Debug and Drop impls.
unbounded_depth = []

# When deserializing Map<String, Value>, return an error if a key is found that
# is already in the Map.
no_duplicate_keys = []

8 changes: 8 additions & 0 deletions src/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ use core::mem;
use core::ops;
use serde::de;

#[cfg(feature = "no_duplicate_keys")]
use std::format;

#[cfg(not(feature = "preserve_order"))]
use alloc::collections::{btree_map, BTreeMap};

#[cfg(feature = "preserve_order")]
use indexmap::IndexMap;

Expand Down Expand Up @@ -472,6 +476,10 @@ impl<'de> de::Deserialize<'de> for Map<String, Value> {
let mut values = Map::new();

while let Some((key, value)) = tri!(visitor.next_entry()) {
#[cfg(feature = "no_duplicate_keys")]
if values.contains_key(&key) {
Err(serde::de::Error::custom(format!("duplicate key '{key}'")))?
}
values.insert(key, value);
}

Expand Down
8 changes: 8 additions & 0 deletions src/value/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ use alloc::vec::{self, Vec};
use core::fmt;
use core::slice;
use core::str::FromStr;

#[cfg(feature = "no_duplicate_keys")]
use std::format;

use serde::de::{
self, Deserialize, DeserializeSeed, EnumAccess, Expected, IntoDeserializer, MapAccess,
SeqAccess, Unexpected, VariantAccess, Visitor,
Expand Down Expand Up @@ -122,6 +126,10 @@ impl<'de> Deserialize<'de> for Value {

values.insert(first_key, tri!(visitor.next_value()));
while let Some((key, value)) = tri!(visitor.next_entry()) {
#[cfg(feature = "no_duplicate_keys")]
if values.contains_key(&key) {
Err(serde::de::Error::custom(format!("duplicate key '{key}'")))?
}
values.insert(key, value);
}

Expand Down