cphf
CPHF is a library to generate efficient lookup tables at compile time using perfect hash functions.
It currently uses the CHD algorithm and can generate a 120 entry map in roughly 1 second.
MSRV (minimum supported rust version) is Rust 1.85.
In contrast to the excellent phf crate, this crate
uses no code generation outside of normal macro_rules. Instead it generates maps using const expressions.
As such, this crate is several orders of magnitude slower than phf (so maps with thousands of entries would probably be
better served by phf), but doing so allows it to avoid all the major drawbacks. Namely, nested maps are supported any type can be used as a key (provided it implements the correct traits and pseudo-traits).
Usage
Simply add cphf as a depenency and utilize the included phf_ordered_map macro to construct an OrderedMap
or the phf_ordered_set macro to construct an OrderedSet
use ;
static KEYWORDS: = phf_ordered_map! ;
Inclusion of duplicate keys will result in a compiler error.
use cphf::{phf_ordered_set, OrderedSet};
static DUPLICATE_KEYS: OrderedSet<u32> = phf_ordered_set! {u32;
0,
1,
0,
};
use cphf::{phf_ordered_map, OrderedMap};
static DUPLICATE_KEYS: OrderedMap<u32, ()> = phf_ordered_map! {u32, ();
0 => (),
1 => (),
0 => (),
};
Advanced Usage
If we wanted to make Keyword above into a key are as follows, we would implement traits (and pseudo-traits) like this:
use Borrow;
use ;
// We now require `Eq` to be a key
// Define a new type for our pseudo-trait
;
// Glue our marker type to the real type.
// Implement our pseudo-trait. These are `const` inherent methods since there
// is current no method of adding `const` methods to a trait
// Finally we add a trait implementation to allow usage of indexing methods like `get`.
// You can make this broad or narrow as you would like, doing so just modifies what types callers can pass to `OrderedMap::get`,
// but `?Sized + Borrow<Self>` is a pretty good baseline.
// Now we can make use `Keyword` as a key
static KEYWORDS: OrderedMap = phf_ordered_map! ;
License
Licensed under
- MIT license (LICENSE or https://opensource.org/licenses/MIT)