Skip to content

Commit

Permalink
impl Hash for Value
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardycl committed Apr 25, 2024
1 parent a3f62bb commit 16eb872
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/map.rs
Expand Up @@ -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;
Expand Down Expand Up @@ -368,6 +370,23 @@ impl PartialEq for Map<String, Value> {

impl Eq for Map<String, Value> {}

#[cfg(not(feature = "preserve_order"))]
impl Hash for Map<String, Value> {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.map.hash(state)
}
}
#[cfg(feature = "preserve_order")]
impl Hash for Map<String, Value> {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
let mut kv = self.map.iter().collect::<Vec<_>>();
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.
///
Expand Down
2 changes: 1 addition & 1 deletion src/value/mod.rs
Expand Up @@ -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.
///
Expand Down

0 comments on commit 16eb872

Please sign in to comment.