Skip to content

Commit

Permalink
Merge pull request #294 from Swatinem/generate-with-fn
Browse files Browse the repository at this point in the history
Allow using an arbitrary hash_fn for generation
  • Loading branch information
JohnTitor committed Oct 28, 2023
2 parents b7116ff + a714e10 commit 8ecc019
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions phf_generator/src/lib.rs
Expand Up @@ -3,7 +3,7 @@
//! [phf]: https://docs.rs/phf

#![doc(html_root_url = "https://docs.rs/phf_generator/0.11")]
use phf_shared::{HashKey, PhfHash};
use phf_shared::{HashKey, Hashes, PhfHash};
use rand::distributions::Standard;
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};
Expand All @@ -19,23 +19,28 @@ pub struct HashState {
}

pub fn generate_hash<H: PhfHash>(entries: &[H]) -> HashState {
generate_hash_with_hash_fn(entries, phf_shared::hash)
}

pub fn generate_hash_with_hash_fn<T, F>(entries: &[T], hash_fn: F) -> HashState
where
F: Fn(&T, &HashKey) -> Hashes,
{
SmallRng::seed_from_u64(FIXED_SEED)
.sample_iter(Standard)
.find_map(|key| try_generate_hash(entries, key))
.find_map(|key| {
let hashes: Vec<_> = entries.iter().map(|entry| hash_fn(entry, &key)).collect();
try_generate_hash(&hashes, key)
})
.expect("failed to solve PHF")
}

fn try_generate_hash<H: PhfHash>(entries: &[H], key: HashKey) -> Option<HashState> {
fn try_generate_hash(hashes: &[Hashes], key: HashKey) -> Option<HashState> {
struct Bucket {
idx: usize,
keys: Vec<usize>,
}

let hashes: Vec<_> = entries
.iter()
.map(|entry| phf_shared::hash(entry, &key))
.collect();

let buckets_len = (hashes.len() + DEFAULT_LAMBDA - 1) / DEFAULT_LAMBDA;
let mut buckets = (0..buckets_len)
.map(|i| Bucket {
Expand Down

0 comments on commit 8ecc019

Please sign in to comment.