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;
14 /// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
15 /// Used mainly for Lazy positions and lengths.
16 /// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
17 /// but this has no impact on safety.
18 pub(super) trait FixedSizeEncoding: Default {
19 /// This should be `[u8; BYTE_LEN]`;
22 fn from_bytes(b: &Self::ByteArray) -> Self;
23 fn write_to_bytes(self, b: &mut Self::ByteArray);
26 impl FixedSizeEncoding for u32 {
27 type ByteArray = [u8; 4];
30 fn from_bytes(b: &[u8; 4]) -> Self {
31 Self::from_le_bytes(*b)
35 fn write_to_bytes(self, b: &mut [u8; 4]) {
36 *b = self.to_le_bytes();
40 macro_rules! fixed_size_enum {
41 ($ty:ty { $(($($pat:tt)*))* }) => {
42 impl FixedSizeEncoding for Option<$ty> {
43 type ByteArray = [u8;1];
46 fn from_bytes(b: &[u8;1]) -> Self {
52 $(${index()} => Some($($pat)*),)*
53 _ => panic!("Unexpected ImplPolarity code: {:?}", b[0]),
58 fn write_to_bytes(self, b: &mut [u8;1]) {
62 $(Some($($pat)*) => 1 + ${index()},)*
99 ( Static(ast::Mutability::Not) )
100 ( Static(ast::Mutability::Mut) )
101 ( Ctor(CtorOf::Struct, CtorKind::Fn) )
102 ( Ctor(CtorOf::Struct, CtorKind::Const) )
103 ( Ctor(CtorOf::Struct, CtorKind::Fictive) )
104 ( Ctor(CtorOf::Variant, CtorKind::Fn) )
105 ( Ctor(CtorOf::Variant, CtorKind::Const) )
106 ( Ctor(CtorOf::Variant, CtorKind::Fictive) )
107 ( Macro(MacroKind::Bang) )
108 ( Macro(MacroKind::Attr) )
109 ( Macro(MacroKind::Derive) )
131 ( Default { has_value: false } )
132 ( Default { has_value: true } )
143 // We directly encode `DefPathHash` because a `LazyValue` would incur a 25% cost.
144 impl FixedSizeEncoding for Option<DefPathHash> {
145 type ByteArray = [u8; 16];
148 fn from_bytes(b: &[u8; 16]) -> Self {
149 Some(DefPathHash(Fingerprint::from_le_bytes(*b)))
153 fn write_to_bytes(self, b: &mut [u8; 16]) {
154 let Some(DefPathHash(fingerprint)) = self else {
155 panic!("Trying to encode absent DefPathHash.")
157 *b = fingerprint.to_le_bytes();
161 // We directly encode RawDefId because using a `LazyValue` would incur a 50% overhead in the worst case.
162 impl FixedSizeEncoding for Option<RawDefId> {
163 type ByteArray = [u8; 8];
166 fn from_bytes(b: &[u8; 8]) -> Self {
167 let krate = u32::from_le_bytes(b[0..4].try_into().unwrap());
168 let index = u32::from_le_bytes(b[4..8].try_into().unwrap());
172 Some(RawDefId { krate: krate - 1, index })
176 fn write_to_bytes(self, b: &mut [u8; 8]) {
179 Some(RawDefId { krate, index }) => {
180 // CrateNum is less than `CrateNum::MAX_AS_U32`.
181 debug_assert!(krate < u32::MAX);
182 b[0..4].copy_from_slice(&(1 + krate).to_le_bytes());
183 b[4..8].copy_from_slice(&index.to_le_bytes());
189 impl FixedSizeEncoding for Option<()> {
190 type ByteArray = [u8; 1];
193 fn from_bytes(b: &[u8; 1]) -> Self {
194 (b[0] != 0).then(|| ())
198 fn write_to_bytes(self, b: &mut [u8; 1]) {
199 b[0] = self.is_some() as u8
203 // NOTE(eddyb) there could be an impl for `usize`, which would enable a more
204 // generic `LazyValue<T>` impl, but in the general case we might not need / want
205 // to fit every `usize` in `u32`.
206 impl<T> FixedSizeEncoding for Option<LazyValue<T>> {
207 type ByteArray = [u8; 4];
210 fn from_bytes(b: &[u8; 4]) -> Self {
211 let position = NonZeroUsize::new(u32::from_bytes(b) as usize)?;
212 Some(LazyValue::from_position(position))
216 fn write_to_bytes(self, b: &mut [u8; 4]) {
217 let position = self.map_or(0, |lazy| lazy.position.get());
218 let position: u32 = position.try_into().unwrap();
219 position.write_to_bytes(b)
223 impl<T> FixedSizeEncoding for Option<LazyArray<T>> {
224 type ByteArray = [u8; 8];
227 fn from_bytes(b: &[u8; 8]) -> Self {
228 let ([ref position_bytes, ref meta_bytes],[])= b.as_chunks::<4>() else { panic!() };
229 let position = NonZeroUsize::new(u32::from_bytes(position_bytes) as usize)?;
230 let len = u32::from_bytes(meta_bytes) as usize;
231 Some(LazyArray::from_position_and_num_elems(position, len))
235 fn write_to_bytes(self, b: &mut [u8; 8]) {
236 let ([ref mut position_bytes, ref mut meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() };
238 let position = self.map_or(0, |lazy| lazy.position.get());
239 let position: u32 = position.try_into().unwrap();
240 position.write_to_bytes(position_bytes);
242 let len = self.map_or(0, |lazy| lazy.num_elems);
243 let len: u32 = len.try_into().unwrap();
244 len.write_to_bytes(meta_bytes);
248 /// Helper for constructing a table's serialization (also see `Table`).
249 pub(super) struct TableBuilder<I: Idx, T>
251 Option<T>: FixedSizeEncoding,
253 blocks: IndexVec<I, <Option<T> as FixedSizeEncoding>::ByteArray>,
254 _marker: PhantomData<T>,
257 impl<I: Idx, T> Default for TableBuilder<I, T>
259 Option<T>: FixedSizeEncoding,
261 fn default() -> Self {
262 TableBuilder { blocks: Default::default(), _marker: PhantomData }
266 impl<I: Idx, T> TableBuilder<I, T>
268 Option<T>: FixedSizeEncoding,
270 pub(crate) fn set<const N: usize>(&mut self, i: I, value: T)
272 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
274 // FIXME(eddyb) investigate more compact encodings for sparse tables.
275 // On the PR @michaelwoerister mentioned:
276 // > Space requirements could perhaps be optimized by using the HAMT `popcnt`
277 // > trick (i.e. divide things into buckets of 32 or 64 items and then
278 // > store bit-masks of which item in each bucket is actually serialized).
279 self.blocks.ensure_contains_elem(i, || [0; N]);
280 Some(value).write_to_bytes(&mut self.blocks[i]);
283 pub(crate) fn encode<const N: usize>(&self, buf: &mut FileEncoder) -> LazyTable<I, T>
285 Option<T>: FixedSizeEncoding<ByteArray = [u8; N]>,
287 let pos = buf.position();
288 for block in &self.blocks {
289 buf.emit_raw_bytes(block);
291 let num_bytes = self.blocks.len() * N;
292 LazyTable::from_position_and_encoded_size(
293 NonZeroUsize::new(pos as usize).unwrap(),
299 impl<I: Idx, T: ParameterizedOverTcx> LazyTable<I, T>
301 Option<T>: FixedSizeEncoding,
303 /// Given the metadata, extract out the value at a particular index (if any).
305 pub(super) fn get<'a, 'tcx, M: Metadata<'a, 'tcx>, const N: usize>(
309 ) -> Option<T::Value<'tcx>>
311 Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
313 debug!("LazyTable::lookup: index={:?} len={:?}", i, self.encoded_size);
315 let start = self.position.get();
316 let bytes = &metadata.blob()[start..start + self.encoded_size];
317 let (bytes, []) = bytes.as_chunks::<N>() else { panic!() };
318 let bytes = bytes.get(i.index())?;
319 FixedSizeEncoding::from_bytes(bytes)
322 /// Size of the table in entries, including possible gaps.
323 pub(super) fn size<const N: usize>(&self) -> usize
325 for<'tcx> Option<T::Value<'tcx>>: FixedSizeEncoding<ByteArray = [u8; N]>,
327 self.encoded_size / N