1 use crate::rmeta::DecodeContext;
2 use crate::rmeta::EncodeContext;
3 use crate::rmeta::MetadataBlob;
4 use rustc_data_structures::owning_ref::OwningRef;
5 use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap};
6 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
7 use rustc_span::def_id::{DefIndex, DefPathHash};
9 crate enum DefPathHashMapRef<'tcx> {
10 OwnedFromMetadata(odht::HashTable<HashMapConfig, OwningRef<MetadataBlob, [u8]>>),
11 BorrowedFromTcx(&'tcx DefPathHashMap),
14 impl DefPathHashMapRef<'tcx> {
16 pub fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex {
18 DefPathHashMapRef::OwnedFromMetadata(ref map) => map.get(def_path_hash).unwrap(),
19 DefPathHashMapRef::BorrowedFromTcx(_) => {
20 panic!("DefPathHashMap::BorrowedFromTcx variant only exists for serialization")
26 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefPathHashMapRef<'tcx> {
27 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
29 DefPathHashMapRef::BorrowedFromTcx(def_path_hash_map) => {
30 let bytes = def_path_hash_map.raw_bytes();
31 e.emit_usize(bytes.len())?;
32 e.emit_raw_bytes(bytes)
34 DefPathHashMapRef::OwnedFromMetadata(_) => {
35 panic!("DefPathHashMap::OwnedFromMetadata variant only exists for deserialization")
41 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static> {
42 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Result<DefPathHashMapRef<'static>, String> {
43 // Import TyDecoder so we can access the DecodeContext::position() method
44 use crate::rustc_middle::ty::codec::TyDecoder;
46 let len = d.read_usize()?;
47 let pos = d.position();
48 let o = OwningRef::new(d.blob().clone()).map(|x| &x[pos..pos + len]);
50 // Although we already have the data we need via the OwningRef, we still need
51 // to advance the DecodeContext's position so it's in a valid state after
52 // the method. We use read_raw_bytes() for that.
53 let _ = d.read_raw_bytes(len);
55 let inner = odht::HashTable::from_raw_bytes(o).map_err(|e| format!("{}", e))?;
56 Ok(DefPathHashMapRef::OwnedFromMetadata(inner))