Skip to content
This repository was archived by the owner on Jun 8, 2021. It is now read-only.

Commit f789f54

Browse files
authored
Merge pull request #462 from philn/master
gstring: Implement Hash trait
2 parents e6771a1 + 90f5dca commit f789f54

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/gstring.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::borrow::Borrow;
66
use std::cmp::Ordering;
77
use std::ffi::{CStr, CString, OsStr};
88
use std::fmt;
9+
use std::hash;
910
use std::ops::Deref;
1011
use std::os::raw::c_char;
1112
use std::ptr;
@@ -71,6 +72,24 @@ impl fmt::Display for GString {
7172
}
7273
}
7374

75+
impl hash::Hash for GString {
76+
fn hash<H: hash::Hasher>(&self, state: &mut H) {
77+
let bytes = match self {
78+
GString::Borrowed(ptr, length) => unsafe {
79+
slice::from_raw_parts(*ptr as *const u8, length + 1)
80+
},
81+
GString::Owned(ptr, length) => unsafe {
82+
slice::from_raw_parts(*ptr as *const u8, length + 1)
83+
},
84+
GString::ForeignOwned(cstring) => cstring
85+
.as_ref()
86+
.expect("ForeignOwned shouldn't be empty")
87+
.as_bytes(),
88+
};
89+
state.write(bytes);
90+
}
91+
}
92+
7493
impl Borrow<str> for GString {
7594
fn borrow(&self) -> &str {
7695
self.as_str()
@@ -449,4 +468,16 @@ mod tests {
449468
assert_eq!(s.as_str(), "foo");
450469
}
451470

471+
#[test]
472+
fn test_hashmap() {
473+
use std::collections::HashMap;
474+
475+
let cstr = CString::new("foo").unwrap();
476+
let gstring = GString::from(cstr);
477+
assert_eq!(gstring.as_str(), "foo");
478+
let mut h: HashMap<GString, i32> = HashMap::new();
479+
h.insert(gstring, 42);
480+
let gstring: GString = "foo".into();
481+
assert!(h.contains_key(&gstring));
482+
}
452483
}

0 commit comments

Comments
 (0)