Skip to content

Allow encoding/decoding of HashMap and HashSet with custom hash algorithms #529

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

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/features/impl_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ impl Decode for SocketAddrV6 {
impl std::error::Error for EncodeError {}
impl std::error::Error for DecodeError {}

impl<K, V> Encode for HashMap<K, V>
impl<K, V, S> Encode for HashMap<K, V, S>
where
K: Encode,
V: Encode,
Expand All @@ -376,16 +376,18 @@ where
}
}

impl<K, V> Decode for HashMap<K, V>
impl<K, V, S> Decode for HashMap<K, V, S>
where
K: Decode + Eq + std::hash::Hash,
V: Decode,
S: std::hash::BuildHasher + Default,
{
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
let len = crate::de::decode_slice_len(decoder)?;
decoder.claim_container_read::<(K, V)>(len)?;

let mut map = HashMap::with_capacity(len);
let hash_builder: S = Default::default();
let mut map = HashMap::with_capacity_and_hasher(len, hash_builder);
for _ in 0..len {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<(K, V)>());
Expand All @@ -398,15 +400,17 @@ where
}
}

impl<T> Decode for HashSet<T>
impl<T, S> Decode for HashSet<T, S>
where
T: Decode + Eq + Hash,
S: std::hash::BuildHasher + Default,
{
fn decode<D: Decoder>(decoder: &mut D) -> Result<Self, DecodeError> {
let len = crate::de::decode_slice_len(decoder)?;
decoder.claim_container_read::<T>(len)?;

let mut map = HashSet::new();
let hash_builder: S = Default::default();
let mut map: HashSet<T, S> = HashSet::with_capacity_and_hasher(len, hash_builder);
for _ in 0..len {
// See the documentation on `unclaim_bytes_read` as to why we're doing this here
decoder.unclaim_bytes_read(core::mem::size_of::<T>());
Expand All @@ -418,7 +422,7 @@ where
}
}

impl<T> Encode for HashSet<T>
impl<T, S> Encode for HashSet<T, S>
where
T: Encode,
{
Expand Down
32 changes: 32 additions & 0 deletions tests/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ fn test_std_commons() {
set.insert("World".to_string());
the_same(set);

// HashMap and HashSet with custom hash algorithm
type MyBuildHasher = std::hash::BuildHasherDefault<ExampleCustomHasher>;
let mut custom_map: std::collections::HashMap<String, String, MyBuildHasher> =
Default::default();
custom_map.insert("Hello".to_owned(), "world".to_owned());
custom_map.insert("How".to_owned(), "are".to_owned());
custom_map.insert("you".to_owned(), "doing?".to_owned());
the_same(custom_map);

let mut custom_set: std::collections::HashSet<String, MyBuildHasher> = Default::default();
custom_set.insert("Hello".to_string());
custom_set.insert("World".to_string());
the_same(custom_set);

// Borrowed values
let config = bincode::config::standard();
let mut buffer = [0u8; 1024];
Expand Down Expand Up @@ -141,3 +155,21 @@ fn test_system_time_out_of_range() {
}
);
}

/// Simple example of user-defined hasher to test encoding/decoding HashMap and HashSet with custom hash algorithms.
#[derive(Copy, Clone, Default)]
pub struct ExampleCustomHasher {
pub hash: u64,
}

impl std::hash::Hasher for ExampleCustomHasher {
fn write(&mut self, value: &[u8]) {
for (index, &item) in value.iter().enumerate() {
self.hash ^= u64::from(item) << ((index % 8) * 8);
}
}

fn finish(&self) -> u64 {
self.hash
}
}