]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs
Rollup merge of #101429 - compiler-errors:issue-101119, r=lcnr
[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_middle::parameterized_over_tcx;
7 use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
8 use rustc_span::def_id::{DefIndex, DefPathHash};
9
10 pub(crate) enum DefPathHashMapRef<'tcx> {
11     OwnedFromMetadata(odht::HashTable<HashMapConfig, OwningRef<MetadataBlob, [u8]>>),
12     BorrowedFromTcx(&'tcx DefPathHashMap),
13 }
14
15 parameterized_over_tcx! {
16     DefPathHashMapRef,
17 }
18
19 impl DefPathHashMapRef<'_> {
20     #[inline]
21     pub fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex {
22         match *self {
23             DefPathHashMapRef::OwnedFromMetadata(ref map) => map.get(def_path_hash).unwrap(),
24             DefPathHashMapRef::BorrowedFromTcx(_) => {
25                 panic!("DefPathHashMap::BorrowedFromTcx variant only exists for serialization")
26             }
27         }
28     }
29 }
30
31 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefPathHashMapRef<'tcx> {
32     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
33         match *self {
34             DefPathHashMapRef::BorrowedFromTcx(def_path_hash_map) => {
35                 let bytes = def_path_hash_map.raw_bytes();
36                 e.emit_usize(bytes.len());
37                 e.emit_raw_bytes(bytes);
38             }
39             DefPathHashMapRef::OwnedFromMetadata(_) => {
40                 panic!("DefPathHashMap::OwnedFromMetadata variant only exists for deserialization")
41             }
42         }
43     }
44 }
45
46 impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static> {
47     fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefPathHashMapRef<'static> {
48         // Import TyDecoder so we can access the DecodeContext::position() method
49         use crate::rustc_middle::ty::codec::TyDecoder;
50
51         let len = d.read_usize();
52         let pos = d.position();
53         let o = OwningRef::new(d.blob().clone()).map(|x| &x[pos..pos + len]);
54
55         // Although we already have the data we need via the OwningRef, we still need
56         // to advance the DecodeContext's position so it's in a valid state after
57         // the method. We use read_raw_bytes() for that.
58         let _ = d.read_raw_bytes(len);
59
60         let inner = odht::HashTable::from_raw_bytes(o).unwrap_or_else(|e| {
61             panic!("decode error: {}", e);
62         });
63         DefPathHashMapRef::OwnedFromMetadata(inner)
64     }
65 }