rustc_metadata/rmeta/
def_path_hash_map.rs

1use rustc_data_structures::owned_slice::OwnedSlice;
2use rustc_hir::def_path_hash_map::{Config as HashMapConfig, DefPathHashMap};
3use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
4use rustc_span::def_id::{DefIndex, DefPathHash};
5
6use crate::rmeta::{DecodeContext, EncodeContext};
7
8pub(crate) enum DefPathHashMapRef<'tcx> {
9    OwnedFromMetadata(odht::HashTable<HashMapConfig, OwnedSlice>),
10    BorrowedFromTcx(&'tcx DefPathHashMap),
11}
12
13impl DefPathHashMapRef<'_> {
14    #[inline]
15    pub(crate) fn def_path_hash_to_def_index(
16        &self,
17        def_path_hash: &DefPathHash,
18    ) -> Option<DefIndex> {
19        match *self {
20            DefPathHashMapRef::OwnedFromMetadata(ref map) => map.get(&def_path_hash.local_hash()),
21            DefPathHashMapRef::BorrowedFromTcx(_) => {
22                panic!("DefPathHashMap::BorrowedFromTcx variant only exists for serialization")
23            }
24        }
25    }
26}
27
28impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefPathHashMapRef<'tcx> {
29    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
30        match *self {
31            DefPathHashMapRef::BorrowedFromTcx(def_path_hash_map) => {
32                let bytes = def_path_hash_map.raw_bytes();
33                e.emit_usize(bytes.len());
34                e.emit_raw_bytes(bytes);
35            }
36            DefPathHashMapRef::OwnedFromMetadata(_) => {
37                panic!("DefPathHashMap::OwnedFromMetadata variant only exists for deserialization")
38            }
39        }
40    }
41}
42
43impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for DefPathHashMapRef<'static> {
44    fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefPathHashMapRef<'static> {
45        let len = d.read_usize();
46        let pos = d.position();
47        let o = d.blob().bytes().clone().slice(|blob| &blob[pos..pos + len]);
48
49        // Although we already have the data we need via the `OwnedSlice`, we still need
50        // to advance the `DecodeContext`'s position so it's in a valid state after
51        // the method. We use `read_raw_bytes()` for that.
52        let _ = d.read_raw_bytes(len);
53
54        let inner = odht::HashTable::from_raw_bytes(o).unwrap_or_else(|e| {
55            panic!("decode error: {e}");
56        });
57        DefPathHashMapRef::OwnedFromMetadata(inner)
58    }
59}