Implement Hash for Lua String

This commit is contained in:
Alex Orlenko 2022-04-08 16:43:09 +01:00
parent 55fac90a74
commit 28a063c1e5
No known key found for this signature in database
GPG key ID: 4C150C250863B96D
2 changed files with 32 additions and 1 deletions

View file

@ -1,4 +1,5 @@
use std::borrow::Cow;
use std::borrow::{Borrow, Cow};
use std::hash::{Hash, Hasher};
use std::string::String as StdString;
use std::{slice, str};
@ -119,6 +120,12 @@ impl<'lua> AsRef<[u8]> for String<'lua> {
}
}
impl<'lua> Borrow<[u8]> for String<'lua> {
fn borrow(&self) -> &[u8] {
self.as_bytes()
}
}
// Lua strings are basically &[u8] slices, so implement PartialEq for anything resembling that.
//
// This makes our `String` comparable with `Vec<u8>`, `[u8]`, `&str`, `String` and `mlua::String`
@ -136,6 +143,14 @@ where
}
}
impl<'lua> Eq for String<'lua> {}
impl<'lua> Hash for String<'lua> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_bytes().hash(state);
}
}
#[cfg(feature = "serialize")]
impl<'lua> Serialize for String<'lua> {
fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>

View file

@ -1,4 +1,5 @@
use std::borrow::Cow;
use std::collections::HashSet;
use mlua::{Lua, Result, String};
@ -67,3 +68,18 @@ fn test_raw_string() -> Result<()> {
Ok(())
}
#[test]
fn test_string_hash() -> Result<()> {
let lua = Lua::new();
let set: HashSet<String> = lua.load(r#"{"hello", "world", "abc", 321}"#).eval()?;
assert_eq!(set.len(), 4);
assert!(set.contains(b"hello".as_ref()));
assert!(set.contains(b"world".as_ref()));
assert!(set.contains(b"abc".as_ref()));
assert!(set.contains(b"321".as_ref()));
assert!(!set.contains(b"Hello".as_ref()));
Ok(())
}