Move simple_hash into its own module.

This commit is contained in:
Jakob Stoklund Olesen
2016-08-09 11:28:51 -07:00
parent 4efb0efb44
commit 24ec62d030
3 changed files with 24 additions and 10 deletions

View File

@@ -54,16 +54,6 @@ impl Opcode {
} }
} }
// A primitive hash function for matching opcodes.
// Must match `meta/constant_hash.py`.
fn simple_hash(s: &str) -> u32 {
let mut h: u32 = 5381;
for c in s.chars() {
h = (h ^ c as u32).wrapping_add(h.rotate_right(6));
}
h
}
// This trait really belongs in libreader where it is used by the .cton file parser, but since it // This trait really belongs in libreader where it is used by the .cton file parser, but since it
// critically depends on the `opcode_name()` function which is needed here anyway, it lives in this // critically depends on the `opcode_name()` function which is needed here anyway, it lives in this
// module. This also saves us from runing the build script twice to generate code for the two // module. This also saves us from runing the build script twice to generate code for the two
@@ -73,6 +63,7 @@ impl FromStr for Opcode {
/// Parse an Opcode name from a string. /// Parse an Opcode name from a string.
fn from_str(s: &str) -> Result<Opcode, &'static str> { fn from_str(s: &str) -> Result<Opcode, &'static str> {
use simple_hash::simple_hash;
let tlen = OPCODE_HASH_TABLE.len(); let tlen = OPCODE_HASH_TABLE.len();
assert!(tlen.is_power_of_two()); assert!(tlen.is_power_of_two());
let mut idx = simple_hash(s) as usize; let mut idx = simple_hash(s) as usize;

View File

@@ -15,4 +15,6 @@ pub mod dominator_tree;
pub mod entity_map; pub mod entity_map;
pub mod settings; pub mod settings;
mod simple_hash;
#[cfg(test)]pub mod test_utils; #[cfg(test)]pub mod test_utils;

View File

@@ -0,0 +1,21 @@
/// A primitive hash function for matching opcodes.
/// Must match `meta/constant_hash.py`.
pub fn simple_hash(s: &str) -> u32 {
let mut h: u32 = 5381;
for c in s.chars() {
h = (h ^ c as u32).wrapping_add(h.rotate_right(6));
}
h
}
#[cfg(test)]
mod tests {
use super::simple_hash;
#[test]
fn basic() {
// c.f. meta/constant_hash.py tests.
assert_eq!(simple_hash("Hello"), 0x2fa70c01);
assert_eq!(simple_hash("world"), 0x5b0c31d5);
}
}