Path: blob/main/cranelift/codegen/meta/src/constant_hash.rs
1692 views
//! Build support for precomputed constant hash tables.1//!2//! This module can generate constant hash tables using open addressing and quadratic probing.3//!4//! The hash tables are arrays that are guaranteed to:5//!6//! - Have a power-of-two size.7//! - Contain at least one empty slot.89use std::iter;1011/// Compute an open addressed, quadratically probed hash table containing12/// `items`. The returned table is a list containing the elements of the13/// iterable `items` and `None` in unused slots.14pub fn generate_table<'cont, T, I: iter::Iterator<Item = &'cont T>, H: Fn(&T) -> usize>(15items: I,16num_items: usize,17hash_function: H,18) -> Vec<Option<&'cont T>> {19let size = (1.20 * num_items as f64) as usize;2021// Probing code's stop condition relies on the table having one vacant entry at least.22let size = if size.is_power_of_two() {23size * 224} else {25size.next_power_of_two()26};2728let mut table = vec![None; size];2930for i in items {31let mut h = hash_function(i) % size;32let mut s = 0;33while table[h].is_some() {34s += 1;35h = (h + s) % size;36}37table[h] = Some(i);38}3940table41}4243#[cfg(test)]44mod tests {45use super::generate_table;46use cranelift_codegen_shared::constant_hash::simple_hash;4748#[test]49fn test_generate_table() {50let v = vec!["Hello".to_string(), "world".to_string()];51let table = generate_table(v.iter(), v.len(), |s| simple_hash(&s));52assert_eq!(53table,54vec![55None,56Some(&"Hello".to_string()),57Some(&"world".to_string()),58None59]60);61}62}636465