]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_type_ir/src/codec.rs
Auto merge of #103390 - compiler-errors:metadata-mod-regions, r=eholk
[rust.git] / compiler / rustc_type_ir / src / codec.rs
1 use crate::Interner;
2
3 use rustc_data_structures::fx::FxHashMap;
4 use rustc_serialize::{Decoder, Encoder};
5
6 /// The shorthand encoding uses an enum's variant index `usize`
7 /// and is offset by this value so it never matches a real variant.
8 /// This offset is also chosen so that the first byte is never < 0x80.
9 pub const SHORTHAND_OFFSET: usize = 0x80;
10
11 /// Trait for decoding to a reference.
12 ///
13 /// This is a separate trait from `Decodable` so that we can implement it for
14 /// upstream types, such as `FxHashSet`.
15 ///
16 /// The `TyDecodable` derive macro will use this trait for fields that are
17 /// references (and don't use a type alias to hide that).
18 ///
19 /// `Decodable` can still be implemented in cases where `Decodable` is required
20 /// by a trait bound.
21 pub trait RefDecodable<'tcx, D: TyDecoder> {
22     fn decode(d: &mut D) -> &'tcx Self;
23 }
24
25 pub trait TyEncoder: Encoder {
26     type I: Interner;
27     const CLEAR_CROSS_CRATE: bool;
28
29     fn position(&self) -> usize;
30     fn type_shorthands(&mut self) -> &mut FxHashMap<<Self::I as Interner>::Ty, usize>;
31     fn predicate_shorthands(
32         &mut self,
33     ) -> &mut FxHashMap<<Self::I as Interner>::PredicateKind, usize>;
34     fn encode_alloc_id(&mut self, alloc_id: &<Self::I as Interner>::AllocId);
35 }
36
37 pub trait TyDecoder: Decoder {
38     type I: Interner;
39     const CLEAR_CROSS_CRATE: bool;
40
41     fn interner(&self) -> Self::I;
42
43     fn peek_byte(&self) -> u8;
44
45     fn position(&self) -> usize;
46
47     fn cached_ty_for_shorthand<F>(
48         &mut self,
49         shorthand: usize,
50         or_insert_with: F,
51     ) -> <Self::I as Interner>::Ty
52     where
53         F: FnOnce(&mut Self) -> <Self::I as Interner>::Ty;
54
55     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
56     where
57         F: FnOnce(&mut Self) -> R;
58
59     fn positioned_at_shorthand(&self) -> bool {
60         (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0
61     }
62
63     fn decode_alloc_id(&mut self) -> <Self::I as Interner>::AllocId;
64 }