Share constant_hash code between the meta and codegen crates;

This commit is contained in:
Benjamin Bouvier
2019-10-09 16:35:33 +02:00
parent c062f12d7c
commit d404368dea
8 changed files with 94 additions and 84 deletions

View File

@@ -1,55 +0,0 @@
use std::iter;
pub(crate) fn simple_hash(s: &str) -> usize {
let mut h: u32 = 5381;
for c in s.chars() {
h = (h ^ c as u32).wrapping_add(h.rotate_right(6));
}
h as usize
}
/// Compute an open addressed, quadratically probed hash table containing
/// `items`. The returned table is a list containing the elements of the
/// iterable `items` and `None` in unused slots.
pub(crate) fn generate_table<'cont, T, I: iter::Iterator<Item = &'cont T>, H: Fn(&T) -> usize>(
items: I,
num_items: usize,
hash_function: H,
) -> Vec<Option<&'cont T>> {
let size = (1.20 * num_items as f64) as usize;
// TODO do we really need the multiply by two here?
let size = if size.is_power_of_two() {
size * 2
} else {
size.next_power_of_two()
};
let mut table = vec![None; size];
for i in items {
let mut h = hash_function(&i) % size;
let mut s = 0;
while table[h].is_some() {
s += 1;
h = (h + s) % size;
}
table[h] = Some(i);
}
table
}
#[test]
fn test_generate_table() {
let v = vec!["Hello".to_string(), "world".to_string()];
let table = generate_table(v.iter(), v.len(), |s| simple_hash(&s));
assert_eq!(
table,
vec![
None,
Some(&"Hello".to_string()),
Some(&"world".to_string()),
None
]
);
}

View File

@@ -49,6 +49,7 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::iter::FromIterator;
use cranelift_codegen_shared::constant_hash::generate_table;
use cranelift_entity::EntityRef;
use crate::error;
@@ -66,7 +67,6 @@ use crate::cdsl::xform::TransformGroupIndex;
use crate::shared::Definitions as SharedDefinitions;
use crate::constant_hash::generate_table;
use crate::default_map::MapWithDefault;
use crate::unique_table::UniqueSeqTable;

View File

@@ -1,5 +1,6 @@
use std::fmt;
use cranelift_codegen_shared::constant_hash;
use cranelift_entity::EntityRef;
use crate::cdsl::camel_case;
@@ -10,7 +11,6 @@ use crate::cdsl::typevar::{TypeSet, TypeVar};
use crate::shared::Definitions as SharedDefinitions;
use crate::constant_hash;
use crate::error;
use crate::srcgen::{Formatter, Match};
use crate::unique_table::{UniqueSeqTable, UniqueTable};

View File

@@ -1,12 +1,14 @@
use std::collections::HashMap;
use cranelift_codegen_shared::constant_hash::{generate_table, simple_hash};
use crate::cdsl::camel_case;
use crate::cdsl::settings::{
BoolSetting, Predicate, Preset, Setting, SettingGroup, SpecificSetting,
};
use crate::constant_hash::{generate_table, simple_hash};
use crate::error;
use crate::srcgen::{Formatter, Match};
use crate::unique_table::UniqueSeqTable;
use std::collections::HashMap;
pub enum ParentGroup {
None,

View File

@@ -13,7 +13,6 @@ mod gen_registers;
mod gen_settings;
mod gen_types;
mod constant_hash;
mod default_map;
mod shared;
mod unique_table;