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

impl Hash for Value #1127

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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