3 use rustc_data_structures::fingerprint::Fingerprint;
4 use rustc_hir::def::{CtorKind, CtorOf};
5 use rustc_index::vec::Idx;
6 use rustc_middle::ty::ParameterizedOverTcx;
7 use rustc_serialize::opaque::FileEncoder;
8 use rustc_serialize::Encoder as _;
9 use rustc_span::hygiene::MacroKind;
10 use std::convert::TryInto;
11 use std::marker::PhantomData;
12 use std::num::NonZeroUsize;
15 /// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
16 /// Used mainly for Lazy positions and lengths.
17 /// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
18 /// but this has no impact on safety.
19 pub(super) trait FixedSizeEncoding: Default {
20 /// This should be `[u8; BYTE_LEN]`;
23 fn from_bytes(b: &Self::ByteArray) -> Self;
24 fn write_to_bytes(self, b: &mut Self::ByteArray);
27 impl FixedSizeEncoding for u32 {
28 type ByteArray = [u8; 4];
31 fn from_bytes(b: &[u8; 4]) -> Self {
32 Self::from_le_bytes(*b)
36 fn write_to_bytes(self, b: &mut [u8; 4]) {
37 *b = self.to_le_bytes();
41 macro_rules! fixed_size_enum {
42 ($ty:ty { $(($($pat:tt)*))* }) => {
43 impl FixedSizeEncoding for Option<$ty> {
44 type ByteArray = [u8;1];
47 fn from_bytes(b: &[u8;1]) -> Self {
53 $(${index()} => Some($($pat)*),)*
54 _ => panic!("Unexpected ImplPolarity code: {:?}", b[0]),
59 fn write_to_bytes(self, b: &mut [u8;1]) {
63 $(Some($($pat)*) => 1 + ${index()},)*
100 ( Static(ast::Mutability::Not) )
101 ( Static(ast::Mutability::Mut) )
102 ( Ctor(CtorOf::Struct, CtorKind::Fn) )
103 ( Ctor(CtorOf::Struct, CtorKind::Const) )
104 ( Ctor(CtorOf::Struct, CtorKind::Fictive) )
105 ( Ctor(CtorOf::Variant, CtorKind::Fn) )
106 ( Ctor(CtorOf::Variant, CtorKind::Const) )
107 ( Ctor(CtorOf::Variant, CtorKind::Fictive) )
108 ( Macro(MacroKind::Bang) )
109 ( Macro(MacroKind::Attr) )
110 ( Macro(MacroKind::Derive) )
132 ( Default { has_value: false } )
133 ( Default { has_value: true } )
144 // We directly encode `DefPathHash` because a `LazyValue` would incur a 25% cost.
145 impl FixedSizeEncoding for Option<DefPathHash> {
146 type ByteArray = [u8; 16];
149 fn from_bytes(b: &[u8; 16]) -> Self {
150 Some(DefPathHash(Fingerprint::from_le_bytes(*b)))
154 fn write_to_bytes(self, b: &mut [u8; 16]) {
155 let Some(DefPathHash(fingerprint)) = self else {
156 panic!("Trying to encode absent DefPathHash.")
158 *b = fingerprint.to_le_bytes();
162 // We directly encode RawDefId because using a `LazyValue` would incur a 50% overhead in the worst case.
163 impl FixedSizeEncoding for Option<RawDefId> {
164 type ByteArray = [u8; 8];
167 fn from_bytes(b: &[u8; 8]) -> Self {
168 let krate = u32::from_le_bytes(b[0..4].try_into().unwrap());
169 let index = u32::from_le_bytes(b[4..8].try_into().unwrap());
173 Some(RawDefId { krate: krate - 1, index })
177 fn write_to_bytes(self, b: &mut [u8; 8]) {
180 Some(RawDefId { krate, index }) => {
181 // CrateNum is less than `CrateNum::MAX_AS_U32`.
182 debug_assert!(krate < u32::MAX);
183 b[0..4].copy_from_slice(&(1 + krate).to_le_bytes());
184 b[4..8].copy_from_slice(&index.to_le_bytes());
190 impl FixedSizeEncoding for Option<()> {
191 type ByteArray = [u8; 1];
194 fn from_bytes(b: &[u8; 1]) -> Self {
195 (b[0] != 0).then(|| ())
199 fn write_to_bytes(self, b: &mut [u8; 1]) {
200 b[0] = self.is_some() as u8
204 // NOTE(eddyb) there could be an impl for `usize`, which would enable a more
205 // generic `LazyValue<T>` impl, but in the general case we might not need / want
206 // to fit every `usize` in `u32`.
207 impl<T> FixedSizeEncoding for Option<LazyValue<T>> {
208 type ByteArray = [u8; 4];
211 fn from_bytes(b: &[u8; 4]) -> Self {
212 let position = NonZeroUsize::new(u32::from_bytes(b) as usize)?;
213 Some(LazyValue::from_position(position))
217 fn write_to_bytes(self, b: &mut [u8; 4]) {
218 let position = self.map_or(0, |lazy| lazy.position.get());
219 let position: u32 = position.try_into().unwrap();
220 position.write_to_bytes(b)
224 impl<T> FixedSizeEncoding for Option<LazyArray<T>> {
225 type ByteArray = [u8; 8];
228 fn from_bytes(b: &[u8; 8]) -> Self {
229 let ([ref position_bytes, ref meta_bytes],[])= b.as_chunks::<4>() else { panic!() };
230 let position = NonZeroUsize::new(u32::from_bytes(position_bytes) as usize)?;
231 let len = u32::from_bytes(meta_bytes) as usize;
232 Some(LazyArray::from_position_and_num_elems(position, len))
236 fn write_to_bytes(self, b: &mut [u8; 8]) {
237 let ([ref mut position_bytes, ref mut meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() };
239 let position = self.map_or(0, |lazy| lazy.position.get());
240 let position: u32 = position.try_into().unwrap();
241 position.write_to_bytes(position_bytes);
243 let len = self.map_or(0, |lazy| lazy.num_elems);
244 let len: u32 = len.try_into().unwrap();
245 len.write_to_bytes(meta_bytes);
249 /// Helper for constructing a table's serialization (also see `Table`).
250 pub(super) struct TableBuilder<I: Idx, T>
252 Option<T>: FixedSizeEncoding,
254 blocks: IndexVec<I, <Option<T> as FixedSizeEncoding>::ByteArray>,
255 _marker: PhantomData<T>,
258 impl<I: Idx, T> Default for TableBuilder<I, T>
260 Option<T>: FixedSizeEncoding,
262 fn default() -> Self {
263 TableBuilder { blocks: Default::default(), _marker: PhantomData }
267 impl<I: Idx, T> TableBuilder<I, T>
269 Option<T>: FixedSizeEncoding,
271 pub(crate) fn set<const N: usize>(&mut self, i: I, value: T)
273 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
275 // FIXME(eddyb) investigate more compact encodings for sparse tables.
276 // On the PR @michaelwoerister mentioned:
277 // > Space requirements could perhaps be optimized by using the HAMT `popcnt`
278 // > trick (i.e. divide things into buckets of 32 or 64 items and then
279 // > store bit-masks of which item in each bucket is actually serialized).
280 self.blocks.ensure_contains_elem(i, || [0; N]);
281 Some(value).write_to_bytes(&mut self.blocks[i]);
284 pub(crate) fn encode<const N: usize>(&self, buf: &mut FileEncoder) -> LazyTable<I, T>
286 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
288 let pos = buf.position();
289 for block in &self.blocks {
290 buf.emit_raw_bytes(block);
292 let num_bytes = self.blocks.len() * N;
293 LazyTable::from_position_and_encoded_size(
294 NonZeroUsize::new(pos as usize).unwrap(),
300 impl<I: Idx, T: ParameterizedOverTcx> LazyTable<I, T>
302 Option<T>: FixedSizeEncoding,
304 /// Given the metadata, extract out the value at a particular index (if any).
306 pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>, const N: usize>(
310 ) -> Option<T::Value<'tcx>>
312 Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
314 debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
316 let start = self.position.get();
317 let bytes = &metadata.blob()[start..start + self.encoded_size];
318 let (bytes, []) = bytes.as_chunks::<N>() else { panic!() };
319 let bytes = bytes.get(i.index())?;
320 FixedSizeEncoding::from_bytes(bytes)
323 /// Size of the table in entries, including possible gaps.
324 pub(super) fn size<const N: usize>(&self) -> usize
326 for<'tcx> Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
328 self.encoded_size / N