Skip to content

Commit eb0330a

Browse files
authored
Merge pull request #1127 from edwardycl/hash
impl `Hash` for `Value`
2 parents 24d868f + 16eb872 commit eb0330a

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/map.rs

+19
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
99
use crate::value::Value;
1010
use alloc::string::String;
11+
#[cfg(feature = "preserve_order")]
12+
use alloc::vec::Vec;
1113
use core::borrow::Borrow;
1214
use core::fmt::{self, Debug};
1315
use core::hash::Hash;
@@ -368,6 +370,23 @@ impl PartialEq for Map<String, Value> {
368370

369371
impl Eq for Map<String, Value> {}
370372

373+
#[cfg(not(feature = "preserve_order"))]
374+
impl Hash for Map<String, Value> {
375+
#[inline]
376+
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
377+
self.map.hash(state)
378+
}
379+
}
380+
#[cfg(feature = "preserve_order")]
381+
impl Hash for Map<String, Value> {
382+
#[inline]
383+
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
384+
let mut kv = self.map.iter().collect::<Vec<_>>();
385+
kv.sort_unstable_by(|a, b| a.0.cmp(b.0));
386+
kv.hash(state);
387+
}
388+
}
389+
371390
/// Access an element of this map. Panics if the given key is not present in the
372391
/// map.
373392
///

src/value/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ pub use crate::raw::{to_raw_value, RawValue};
112112
/// Represents any valid JSON value.
113113
///
114114
/// See the [`serde_json::value` module documentation](self) for usage examples.
115-
#[derive(Clone, Eq, PartialEq)]
115+
#[derive(Clone, Eq, PartialEq, Hash)]
116116
pub enum Value {
117117
/// Represents a JSON null value.
118118
///

0 commit comments

Comments
 (0)