Skip to content

Commit

Permalink
Add Hash implementation for HSTRING (#2924)
Browse files Browse the repository at this point in the history
* Added Hash impl to HSTRING

* Added tests to validate API for hashing HSTRING works
  • Loading branch information
zardini123 authored Mar 12, 2024
1 parent 8bed196 commit 6f4a726
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
6 changes: 6 additions & 0 deletions crates/libs/core/src/strings/hstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,12 @@ impl Ord for HSTRING {
}
}

impl std::hash::Hash for HSTRING {
fn hash<H: std::hash::Hasher>(&self, hasher: &mut H) {
self.as_wide().hash(hasher)
}
}

impl PartialOrd for HSTRING {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
Expand Down
44 changes: 44 additions & 0 deletions crates/tests/core/tests/hstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,50 @@ fn hstring_to_os_string() {
assert_eq!(s, std::ffi::OsString::from_wide(wide_data));
}

#[test]
fn hstring_hashing_equal_strings() {
// Checks if two strings of identical contents have the same hash
use std::hash::{DefaultHasher, Hash, Hasher};

let hstring_1 = HSTRING::from("Hello World");
let hstring_2 = HSTRING::from("Hello World");

assert_eq!(hstring_1, hstring_2);

let mut hasher_1 = DefaultHasher::new();
let mut hasher_2 = DefaultHasher::new();

hstring_1.hash(&mut hasher_1);
hstring_2.hash(&mut hasher_2);

let h1_hash = hasher_1.finish();
let h2_hash = hasher_2.finish();

assert_eq!(h1_hash, h2_hash);
}

#[test]
fn hstring_hashing_different_strings() {
// Checks if two strings of different contents have the same hash
use std::hash::{DefaultHasher, Hash, Hasher};

let hstring_1 = HSTRING::from("Hello World");
let hstring_2 = HSTRING::from("Hello World 2");

assert_ne!(hstring_1, hstring_2);

let mut hasher_1 = DefaultHasher::new();
let mut hasher_2 = DefaultHasher::new();

hstring_1.hash(&mut hasher_1);
hstring_2.hash(&mut hasher_2);

let h1_hash = hasher_1.finish();
let h2_hash = hasher_2.finish();

assert_ne!(h1_hash, h2_hash);
}

#[test]
fn hstring_equality_combinations() {
let h = HSTRING::from("test");
Expand Down

0 comments on commit 6f4a726

Please sign in to comment.