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

Commit

Permalink
Merge pull request #462 from philn/master
Browse files Browse the repository at this point in the history
gstring: Implement Hash trait
  • Loading branch information
sdroege committed Feb 22, 2019
2 parents e6771a1 + 90f5dca commit f789f54
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/gstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::borrow::Borrow;
use std::cmp::Ordering;
use std::ffi::{CStr, CString, OsStr};
use std::fmt;
use std::hash;
use std::ops::Deref;
use std::os::raw::c_char;
use std::ptr;
Expand Down Expand Up @@ -71,6 +72,24 @@ impl fmt::Display for GString {
}
}

impl hash::Hash for GString {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
let bytes = match self {
GString::Borrowed(ptr, length) => unsafe {
slice::from_raw_parts(*ptr as *const u8, length + 1)
},
GString::Owned(ptr, length) => unsafe {
slice::from_raw_parts(*ptr as *const u8, length + 1)
},
GString::ForeignOwned(cstring) => cstring
.as_ref()
.expect("ForeignOwned shouldn't be empty")
.as_bytes(),
};
state.write(bytes);
}
}

impl Borrow<str> for GString {
fn borrow(&self) -> &str {
self.as_str()
Expand Down Expand Up @@ -449,4 +468,16 @@ mod tests {
assert_eq!(s.as_str(), "foo");
}

#[test]
fn test_hashmap() {
use std::collections::HashMap;

let cstr = CString::new("foo").unwrap();
let gstring = GString::from(cstr);
assert_eq!(gstring.as_str(), "foo");
let mut h: HashMap<GString, i32> = HashMap::new();
h.insert(gstring, 42);
let gstring: GString = "foo".into();
assert!(h.contains_key(&gstring));
}
}

0 comments on commit f789f54

Please sign in to comment.