]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs
Rollup merge of #88895 - camelid:cleanup-pt2, r=jyn514
[rust.git] / compiler / rustc_metadata / src / rmeta / def_path_hash_map.rs
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};
8
9 crate enum DefPathHashMapRef<'tcx> {
10     OwnedFromMetadata(odht::HashTable<HashMapConfig, OwningRef<MetadataBlob, [u8]>>),
11     BorrowedFromTcx(&'tcx DefPathHashMap),
12 }
13
14 impl DefPathHashMapRef<'tcx> {
15     #[inline]
16     pub fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex {
17         match *self {
18             DefPathHashMapRef::OwnedFromMetadata(ref map) => map.get(def_path_hash).unwrap(),
19             DefPathHashMapRef::BorrowedFromTcx(_) => {
20                 panic!("DefPathHashMap::BorrowedFromTcx variant only exists for serialization")
21             }
22         }
23     }
24 }
25
26 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefPathHashMapRef<'tcx> {
27     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
28         match *self {
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)
33             }
34             DefPathHashMapRef::OwnedFromMetadata(_) => {
35                 panic!("DefPathHashMap::OwnedFromMetadata variant only exists for deserialization")
36             }
37         }
38     }
39 }
40
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;
45
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]);
49
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);
54
55         let inner = odht::HashTable::from_raw_bytes(o).map_err(|e| format!("{}", e))?;
56         Ok(DefPathHashMapRef::OwnedFromMetadata(inner))
57     }
58 }