33//! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order`
44//! feature of serde_json to use [`IndexMap`] instead.
55//!
6+ //! In builds without the `std` feature, `preserve_order` hashes keys with
7+ //! foldhash's [`RandomState`]. Foldhash provides minimal HashDoS resistance,
8+ //! but does not protect against interactive attackers. Builds with `std` use
9+ //! the standard library's [`RandomState`].
10+ //!
611//! [`BTreeMap`]: std::collections::BTreeMap
712//! [`IndexMap`]: indexmap::IndexMap
13+ //! [`RandomState`]: std::collections::hash_map::RandomState
814
915use crate :: error:: Error ;
1016use crate :: value:: Value ;
@@ -33,14 +39,19 @@ pub struct Map<K, V> {
3339#[ cfg( not( feature = "preserve_order" ) ) ]
3440type MapImpl < K , V > = BTreeMap < K , V > ;
3541#[ cfg( feature = "preserve_order" ) ]
36- type MapImpl < K , V > = IndexMap < K , V > ;
42+ type MapImpl < K , V > = IndexMap < K , V , BuildHasherImpl > ;
43+
44+ #[ cfg( all( feature = "preserve_order" , feature = "std" ) ) ]
45+ type BuildHasherImpl = std:: collections:: hash_map:: RandomState ;
46+ #[ cfg( all( feature = "preserve_order" , not( feature = "std" ) ) ) ]
47+ type BuildHasherImpl = foldhash:: fast:: RandomState ;
3748
3849impl Map < String , Value > {
3950 /// Makes a new empty Map.
4051 #[ inline]
4152 pub fn new ( ) -> Self {
4253 Map {
43- map : MapImpl :: new ( ) ,
54+ map : MapImpl :: default ( ) ,
4455 }
4556 }
4657
@@ -55,7 +66,7 @@ impl Map<String, Value> {
5566 BTreeMap :: new ( )
5667 } ,
5768 #[ cfg( feature = "preserve_order" ) ]
58- map : IndexMap :: with_capacity ( capacity) ,
69+ map : IndexMap :: with_capacity_and_hasher ( capacity, BuildHasherImpl :: default ( ) ) ,
5970 }
6071 }
6172
@@ -386,9 +397,7 @@ impl Map<String, Value> {
386397impl Default for Map < String , Value > {
387398 #[ inline]
388399 fn default ( ) -> Self {
389- Map {
390- map : MapImpl :: new ( ) ,
391- }
400+ Map :: new ( )
392401 }
393402}
394403
0 commit comments