[][src]Crate phf_codegen

A set of builders to generate Rust source for PHF data structures at compile time.

The provided builders are intended to be used in a Cargo build script to generate a Rust source file that will be included in a library at build time.

Examples

build.rs

extern crate phf_codegen;

use std::env;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;

fn main() {
    let path = Path::new(&env::var("OUT_DIR").unwrap()).join("codegen.rs");
    let mut file = BufWriter::new(File::create(&path).unwrap());

write!(&mut file, "static KEYWORDS: phf::Map<&'static str, Keyword> =
").unwrap();
    phf_codegen::Map::new()
        .entry("loop", "Keyword::Loop")
        .entry("continue", "Keyword::Continue")
        .entry("break", "Keyword::Break")
        .entry("fn", "Keyword::Fn")
        .entry("extern", "Keyword::Extern")
        .build(&mut file)
        .unwrap();
    write!(&mut file, ";\n").unwrap();
}

lib.rs

This example is not tested
extern crate phf;

#[derive(Clone)]
enum Keyword {
    Loop,
    Continue,
    Break,
    Fn,
    Extern,
}

include!(concat!(env!("OUT_DIR"), "/codegen.rs"));

pub fn parse_keyword(keyword: &str) -> Option<Keyword> {
    KEYWORDS.get(keyword).cloned()
}

Note

The compiler's stack will overflow when processing extremely long method chains (500+ calls). When generating large PHF data structures, consider looping over the entries or making each call a separate statement:

let entries = [("hello", "1"), ("world", "2")];

let mut builder = phf_codegen::Map::new();
for &(key, value) in &entries {
    builder.entry(key, value);
}
// ...
let mut builder = phf_codegen::Map::new();
builder.entry("hello", "1");
builder.entry("world", "2");
// ...

Structs

Map

A builder for the phf::Map type.

OrderedMap

A builder for the phf::OrderedMap type.

OrderedSet

A builder for the phf::OrderedSet type.

Set

A builder for the phf::Set type.