From 16eb8723cd54b4cafd3d97a13ad3ac8a53d3f990 Mon Sep 17 00:00:00 2001 From: Youngchan Lee Date: Thu, 25 Apr 2024 15:26:36 +0900 Subject: [PATCH] impl `Hash` for `Value` --- src/map.rs | 19 +++++++++++++++++++ src/value/mod.rs | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/map.rs b/src/map.rs index 520cd6cf5..4a90830c4 100644 --- a/src/map.rs +++ b/src/map.rs @@ -8,6 +8,8 @@ use crate::value::Value; use alloc::string::String; +#[cfg(feature = "preserve_order")] +use alloc::vec::Vec; use core::borrow::Borrow; use core::fmt::{self, Debug}; use core::hash::Hash; @@ -368,6 +370,23 @@ impl PartialEq for Map { impl Eq for Map {} +#[cfg(not(feature = "preserve_order"))] +impl Hash for Map { + #[inline] + fn hash(&self, state: &mut H) { + self.map.hash(state) + } +} +#[cfg(feature = "preserve_order")] +impl Hash for Map { + #[inline] + fn hash(&self, state: &mut H) { + let mut kv = self.map.iter().collect::>(); + kv.sort_unstable_by(|a, b| a.0.cmp(b.0)); + kv.hash(state); + } +} + /// Access an element of this map. Panics if the given key is not present in the /// map. /// diff --git a/src/value/mod.rs b/src/value/mod.rs index b3f51ea0d..026f10dcb 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -112,7 +112,7 @@ pub use crate::raw::{to_raw_value, RawValue}; /// Represents any valid JSON value. /// /// See the [`serde_json::value` module documentation](self) for usage examples. -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Eq, PartialEq, Hash)] pub enum Value { /// Represents a JSON null value. ///