// Copyright 2014-2015 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 or the MIT license
// , at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate phf_codegen;
extern crate rustc_serialize;
use rustc_serialize::json::{Json, Decoder};
use rustc_serialize::Decodable;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
fn main() {
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
named_entities_to_phf(
&Path::new(&manifest_dir).join("data/entities.json"),
&Path::new(&env::var("OUT_DIR").unwrap()).join("named_entities.rs"))
}
fn named_entities_to_phf(from: &Path, to: &Path) {
// A struct matching the entries in entities.json.
#[derive(RustcDecodable)]
struct CharRef {
codepoints: Vec,
//characters: String, // Present in the file but we don't need it
}
let json = Json::from_reader(&mut File::open(from).unwrap()).unwrap();
let entities: HashMap = Decodable::decode(&mut Decoder::new(json)).unwrap();
let mut entities: HashMap<&str, (u32, u32)> = entities.iter().map(|(name, char_ref)| {
assert!(name.starts_with("&"));
assert!(char_ref.codepoints.len() <= 2);
(&name[1..], (char_ref.codepoints[0], *char_ref.codepoints.get(1).unwrap_or(&0)))
}).collect();
// Add every missing prefix of those keys, mapping to NULL characters.
for key in entities.keys().cloned().collect::>() {
for n in 1 .. key.len() {
entities.entry(&key[..n]).or_insert((0, 0));
}
}
entities.insert("", (0, 0));
let mut phf_map = phf_codegen::Map::new();
for (key, value) in entities {
phf_map.entry(key, &format!("{:?}", value));
}
let mut file = File::create(to).unwrap();
write!(&mut file, "pub static NAMED_ENTITIES: Map<&'static str, (u32, u32)> = ").unwrap();
phf_map.build(&mut file).unwrap();
write!(&mut file, ";\n").unwrap();
}