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 } )
145 ty::AssocItemContainer {
159 // We directly encode `DefPathHash` because a `LazyValue` would incur a 25% cost.
160 impl FixedSizeEncoding for Option<DefPathHash> {
161 type ByteArray = [u8; 16];
164 fn from_bytes(b: &[u8; 16]) -> Self {
165 Some(DefPathHash(Fingerprint::from_le_bytes(*b)))
169 fn write_to_bytes(self, b: &mut [u8; 16]) {
170 let Some(DefPathHash(fingerprint)) = self else {
171 panic!("Trying to encode absent DefPathHash.")
173 *b = fingerprint.to_le_bytes();
177 // We directly encode RawDefId because using a `LazyValue` would incur a 50% overhead in the worst case.
178 impl FixedSizeEncoding for Option<RawDefId> {
179 type ByteArray = [u8; 8];
182 fn from_bytes(b: &[u8; 8]) -> Self {
183 let krate = u32::from_le_bytes(b[0..4].try_into().unwrap());
184 let index = u32::from_le_bytes(b[4..8].try_into().unwrap());
188 Some(RawDefId { krate: krate - 1, index })
192 fn write_to_bytes(self, b: &mut [u8; 8]) {
195 Some(RawDefId { krate, index }) => {
196 // CrateNum is less than `CrateNum::MAX_AS_U32`.
197 debug_assert!(krate < u32::MAX);
198 b[0..4].copy_from_slice(&(1 + krate).to_le_bytes());
199 b[4..8].copy_from_slice(&index.to_le_bytes());
205 impl FixedSizeEncoding for Option<()> {
206 type ByteArray = [u8; 1];
209 fn from_bytes(b: &[u8; 1]) -> Self {
210 (b[0] != 0).then(|| ())
214 fn write_to_bytes(self, b: &mut [u8; 1]) {
215 b[0] = self.is_some() as u8
219 // NOTE(eddyb) there could be an impl for `usize`, which would enable a more
220 // generic `LazyValue<T>` impl, but in the general case we might not need / want
221 // to fit every `usize` in `u32`.
222 impl<T> FixedSizeEncoding for Option<LazyValue<T>> {
223 type ByteArray = [u8; 4];
226 fn from_bytes(b: &[u8; 4]) -> Self {
227 let position = NonZeroUsize::new(u32::from_bytes(b) as usize)?;
228 Some(LazyValue::from_position(position))
232 fn write_to_bytes(self, b: &mut [u8; 4]) {
233 let position = self.map_or(0, |lazy| lazy.position.get());
234 let position: u32 = position.try_into().unwrap();
235 position.write_to_bytes(b)
239 impl<T> FixedSizeEncoding for Option<LazyArray<T>> {
240 type ByteArray = [u8; 8];
243 fn from_bytes(b: &[u8; 8]) -> Self {
244 let ([ref position_bytes, ref meta_bytes],[])= b.as_chunks::<4>() else { panic!() };
245 let position = NonZeroUsize::new(u32::from_bytes(position_bytes) as usize)?;
246 let len = u32::from_bytes(meta_bytes) as usize;
247 Some(LazyArray::from_position_and_num_elems(position, len))
251 fn write_to_bytes(self, b: &mut [u8; 8]) {
252 let ([ref mut position_bytes, ref mut meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() };
254 let position = self.map_or(0, |lazy| lazy.position.get());
255 let position: u32 = position.try_into().unwrap();
256 position.write_to_bytes(position_bytes);
258 let len = self.map_or(0, |lazy| lazy.num_elems);
259 let len: u32 = len.try_into().unwrap();
260 len.write_to_bytes(meta_bytes);
264 /// Helper for constructing a table's serialization (also see `Table`).
265 pub(super) struct TableBuilder<I: Idx, T>
267 Option<T>: FixedSizeEncoding,
269 blocks: IndexVec<I, <Option<T> as FixedSizeEncoding>::ByteArray>,
270 _marker: PhantomData<T>,
273 impl<I: Idx, T> Default for TableBuilder<I, T>
275 Option<T>: FixedSizeEncoding,
277 fn default() -> Self {
278 TableBuilder { blocks: Default::default(), _marker: PhantomData }
282 impl<I: Idx, T> TableBuilder<I, T>
284 Option<T>: FixedSizeEncoding,
286 pub(crate) fn set<const N: usize>(&mut self, i: I, value: T)
288 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
290 // FIXME(eddyb) investigate more compact encodings for sparse tables.
291 // On the PR @michaelwoerister mentioned:
292 // > Space requirements could perhaps be optimized by using the HAMT `popcnt`
293 // > trick (i.e. divide things into buckets of 32 or 64 items and then
294 // > store bit-masks of which item in each bucket is actually serialized).
295 self.blocks.ensure_contains_elem(i, || [0; N]);
296 Some(value).write_to_bytes(&mut self.blocks[i]);
299 pub(crate) fn encode<const N: usize>(&self, buf: &mut FileEncoder) -> LazyTable<I, T>
301 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
303 let pos = buf.position();
304 for block in &self.blocks {
305 buf.emit_raw_bytes(block);
307 let num_bytes = self.blocks.len() * N;
308 LazyTable::from_position_and_encoded_size(
309 NonZeroUsize::new(pos as usize).unwrap(),
315 impl<I: Idx, T: ParameterizedOverTcx> LazyTable<I, T>
317 Option<T>: FixedSizeEncoding,
319 /// Given the metadata, extract out the value at a particular index (if any).
321 pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>, const N: usize>(
325 ) -> Option<T::Value<'tcx>>
327 Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
329 debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
331 let start = self.position.get();
332 let bytes = &metadata.blob()[start..start + self.encoded_size];
333 let (bytes, []) = bytes.as_chunks::<N>() else { panic!() };
334 let bytes = bytes.get(i.index())?;
335 FixedSizeEncoding::from_bytes(bytes)
338 /// Size of the table in entries, including possible gaps.
339 pub(super) fn size<const N: usize>(&self) -> usize
341 for<'tcx> Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
343 self.encoded_size / N