Skip to main content

rustc_serialize/
opaque.rs

1use std::fs::File;
2use std::io::{self, Write};
3use std::marker::PhantomData;
4use std::ops::Range;
5use std::path::{Path, PathBuf};
6
7// This code is very hot and uses lots of arithmetic, avoid overflow checks for performance.
8// See https://github.com/rust-lang/rust/pull/119440#issuecomment-1874255727
9use crate::int_overflow::DebugStrictAdd;
10use crate::leb128;
11use crate::serialize::{Decodable, Decoder, Encodable, Encoder};
12
13pub mod mem_encoder;
14
15// -----------------------------------------------------------------------------
16// Encoder
17// -----------------------------------------------------------------------------
18
19pub type FileEncodeResult = Result<usize, (PathBuf, io::Error)>;
20
21pub const MAGIC_END_BYTES: &[u8] = b"rust-end-file";
22
23/// The size of the buffer in `FileEncoder`.
24const BUF_SIZE: usize = 64 * 1024;
25
26/// `FileEncoder` encodes data to file via fixed-size buffer.
27///
28/// There used to be a `MemEncoder` type that encoded all the data into a
29/// `Vec`. `FileEncoder` is better because its memory use is determined by the
30/// size of the buffer, rather than the full length of the encoded data, and
31/// because it doesn't need to reallocate memory along the way.
32///
33/// The `'a` lifetime is the borrow of the optional flush strategy (see
34/// `flush_strategy`); it is unused (`'static`) for encoders created without one.
35pub struct FileEncoder<'a> {
36    // The input buffer. For adequate performance, we need to be able to write
37    // directly to the unwritten region of the buffer, without calling copy_from_slice.
38    // Note that our buffer is always initialized so that we can do that direct access
39    // without unsafe code. Users of this type write many more than BUF_SIZE bytes, so the
40    // initialization is approximately free.
41    buf: Box<[u8; BUF_SIZE]>,
42    buffered: usize,
43    flushed: usize,
44    file: File,
45    // This is used to implement delayed error handling, as described in the
46    // comment on `trait Encoder`.
47    res: Result<(), io::Error>,
48    path: PathBuf,
49    flush_strategy: Option<&'a mut (dyn FnMut(&[u8]) + Send)>,
50    #[cfg(debug_assertions)]
51    finished: bool,
52}
53
54impl<'a> FileEncoder<'a> {
55    pub fn new<P: AsRef<Path>>(path: P) -> io::Result<Self> {
56        // File::create opens the file for writing only. When -Zmeta-stats is enabled, the metadata
57        // encoder rewinds the file to inspect what was written. So we need to always open the file
58        // for reading and writing.
59        let file =
60            File::options().read(true).write(true).create(true).truncate(true).open(&path)?;
61
62        Ok(FileEncoder {
63            buf: ::alloc::vec::from_elem(0u8, BUF_SIZE)vec![0u8; BUF_SIZE].into_boxed_slice().try_into().unwrap(),
64            path: path.as_ref().into(),
65            buffered: 0,
66            flushed: 0,
67            file,
68            res: Ok(()),
69            flush_strategy: None,
70            #[cfg(debug_assertions)]
71            finished: false,
72        })
73    }
74
75    pub fn with_flush_strategy<P: AsRef<Path>>(
76        path: P,
77        strategy: &'a mut (dyn FnMut(&[u8]) + Send),
78    ) -> io::Result<Self> {
79        let mut encoder = Self::new(path)?;
80        encoder.flush_strategy = Some(strategy);
81        Ok(encoder)
82    }
83
84    #[inline]
85    pub fn position(&self) -> usize {
86        // Tracking position this way instead of having a `self.position` field
87        // means that we only need to update `self.buffered` on a write call,
88        // as opposed to updating `self.position` and `self.buffered`.
89        self.flushed.debug_strict_add(self.buffered)
90    }
91
92    #[cold]
93    #[inline(never)]
94    pub fn flush(&mut self) {
95        #[cfg(debug_assertions)]
96        {
97            self.finished = false;
98        }
99        if self.res.is_ok() {
100            self.res = self.file.write_all(&self.buf[..self.buffered]);
101        }
102        self.flushed += self.buffered;
103        if let Some(f) = &mut self.flush_strategy {
104            f(&self.buf[..self.buffered]);
105        }
106        self.buffered = 0;
107    }
108
109    #[inline]
110    pub fn file(&self) -> &File {
111        &self.file
112    }
113
114    #[inline]
115    pub fn path(&self) -> &Path {
116        &self.path
117    }
118
119    #[inline]
120    fn buffer_empty(&mut self) -> &mut [u8] {
121        // SAFETY: self.buffered is inbounds as an invariant of the type
122        unsafe { self.buf.get_unchecked_mut(self.buffered..) }
123    }
124
125    #[cold]
126    #[inline(never)]
127    fn write_all_cold_path(&mut self, buf: &[u8]) {
128        self.flush();
129        if let Some(dest) = self.buf.get_mut(..buf.len()) {
130            dest.copy_from_slice(buf);
131            self.buffered += buf.len();
132        } else {
133            if self.res.is_ok() {
134                self.res = self.file.write_all(buf);
135                if let Some(f) = &mut self.flush_strategy {
136                    f(buf);
137                }
138            }
139            self.flushed += buf.len();
140        }
141    }
142
143    #[inline]
144    fn write_all(&mut self, buf: &[u8]) {
145        #[cfg(debug_assertions)]
146        {
147            self.finished = false;
148        }
149        if let Some(dest) = self.buffer_empty().get_mut(..buf.len()) {
150            dest.copy_from_slice(buf);
151            self.buffered = self.buffered.debug_strict_add(buf.len());
152        } else {
153            self.write_all_cold_path(buf);
154        }
155    }
156
157    /// Write up to `N` bytes to this encoder.
158    ///
159    /// This function can be used to avoid the overhead of calling memcpy for writes that
160    /// have runtime-variable length, but are small and have a small fixed upper bound.
161    ///
162    /// This can be used to do in-place encoding as is done for leb128 (without this function
163    /// we would need to write to a temporary buffer then memcpy into the encoder), and it can
164    /// also be used to implement the varint scheme we use for rmeta and dep graph encoding,
165    /// where we only want to encode the first few bytes of an integer. Copying in the whole
166    /// integer then only advancing the encoder state for the few bytes we care about is more
167    /// efficient than calling [`FileEncoder::write_all`], because variable-size copies are
168    /// always lowered to `memcpy`, which has overhead and contains a lot of logic we can bypass
169    /// with this function. Note that common architectures support fixed-size writes up to 8 bytes
170    /// with one instruction, so while this does in some sense do wasted work, we come out ahead.
171    #[inline]
172    pub fn write_with<const N: usize>(&mut self, visitor: impl FnOnce(&mut [u8; N]) -> usize) {
173        #[cfg(debug_assertions)]
174        {
175            self.finished = false;
176        }
177        let flush_threshold = const { BUF_SIZE.checked_sub(N).unwrap() };
178        if std::intrinsics::unlikely(self.buffered > flush_threshold) {
179            self.flush();
180        }
181        // SAFETY: We checked above that N < self.buffer_empty().len(),
182        // and if isn't, flush ensures that our empty buffer is now BUF_SIZE.
183        // We produce a post-mono error if N > BUF_SIZE.
184        let buf = unsafe { self.buffer_empty().first_chunk_mut::<N>().unwrap_unchecked() };
185        let written = visitor(buf);
186        // We have to ensure that an errant visitor cannot cause self.buffered to exceed BUF_SIZE.
187        if written > N {
188            Self::panic_invalid_write::<N>(written);
189        }
190        self.buffered = self.buffered.debug_strict_add(written);
191    }
192
193    #[cold]
194    #[inline(never)]
195    fn panic_invalid_write<const N: usize>(written: usize) {
196        {
    ::core::panicking::panic_fmt(format_args!("FileEncoder::write_with::<{0}> cannot be used to write {1} bytes",
            N, written));
};panic!("FileEncoder::write_with::<{N}> cannot be used to write {written} bytes");
197    }
198
199    /// Helper for calls where [`FileEncoder::write_with`] always writes the whole array.
200    #[inline]
201    pub fn write_array<const N: usize>(&mut self, buf: [u8; N]) {
202        self.write_with(|dest| {
203            *dest = buf;
204            N
205        })
206    }
207
208    pub fn finish(&mut self) -> FileEncodeResult {
209        self.write_all(MAGIC_END_BYTES);
210        self.flush();
211        #[cfg(debug_assertions)]
212        {
213            self.finished = true;
214        }
215        match std::mem::replace(&mut self.res, Ok(())) {
216            Ok(()) => Ok(self.position()),
217            Err(e) => Err((self.path.clone(), e)),
218        }
219    }
220}
221
222#[cfg(debug_assertions)]
223impl Drop for FileEncoder<'_> {
224    fn drop(&mut self) {
225        if !std::thread::panicking() {
226            if !self.finished {
    ::core::panicking::panic("assertion failed: self.finished")
};assert!(self.finished);
227        }
228    }
229}
230
231macro_rules! write_leb128 {
232    ($this_fn:ident, $int_ty:ty, $write_leb_fn:ident) => {
233        #[inline]
234        fn $this_fn(&mut self, v: $int_ty) {
235            self.write_with(|buf| leb128::$write_leb_fn(buf, v))
236        }
237    };
238}
239
240impl Encoder for FileEncoder<'_> {
241    #[inline]
fn emit_usize(&mut self, v: usize) {
    self.write_with(|buf| leb128::write_usize_leb128(buf, v))
}write_leb128!(emit_usize, usize, write_usize_leb128);
242    #[inline]
fn emit_u128(&mut self, v: u128) {
    self.write_with(|buf| leb128::write_u128_leb128(buf, v))
}write_leb128!(emit_u128, u128, write_u128_leb128);
243    #[inline]
fn emit_u64(&mut self, v: u64) {
    self.write_with(|buf| leb128::write_u64_leb128(buf, v))
}write_leb128!(emit_u64, u64, write_u64_leb128);
244    #[inline]
fn emit_u32(&mut self, v: u32) {
    self.write_with(|buf| leb128::write_u32_leb128(buf, v))
}write_leb128!(emit_u32, u32, write_u32_leb128);
245
246    #[inline]
247    fn emit_u16(&mut self, v: u16) {
248        self.write_array(v.to_le_bytes());
249    }
250
251    #[inline]
252    fn emit_u8(&mut self, v: u8) {
253        self.write_array([v]);
254    }
255
256    #[inline]
fn emit_isize(&mut self, v: isize) {
    self.write_with(|buf| leb128::write_isize_leb128(buf, v))
}write_leb128!(emit_isize, isize, write_isize_leb128);
257    #[inline]
fn emit_i128(&mut self, v: i128) {
    self.write_with(|buf| leb128::write_i128_leb128(buf, v))
}write_leb128!(emit_i128, i128, write_i128_leb128);
258    #[inline]
fn emit_i64(&mut self, v: i64) {
    self.write_with(|buf| leb128::write_i64_leb128(buf, v))
}write_leb128!(emit_i64, i64, write_i64_leb128);
259    #[inline]
fn emit_i32(&mut self, v: i32) {
    self.write_with(|buf| leb128::write_i32_leb128(buf, v))
}write_leb128!(emit_i32, i32, write_i32_leb128);
260
261    #[inline]
262    fn emit_i16(&mut self, v: i16) {
263        self.write_array(v.to_le_bytes());
264    }
265
266    #[inline]
267    fn emit_raw_bytes(&mut self, s: &[u8]) {
268        self.write_all(s);
269    }
270}
271
272// -----------------------------------------------------------------------------
273// Decoder
274// -----------------------------------------------------------------------------
275
276// Conceptually, `MemDecoder` wraps a `&[u8]` with a cursor into it that is always valid.
277// This is implemented with three pointers, two which represent the original slice and a
278// third that is our cursor.
279// It is an invariant of this type that start <= current <= end.
280// Additionally, the implementation of this type never modifies start and end.
281pub struct MemDecoder<'a> {
282    start: *const u8,
283    current: *const u8,
284    end: *const u8,
285    _marker: PhantomData<&'a u8>,
286}
287
288impl<'a> MemDecoder<'a> {
289    #[inline]
290    pub fn new(data: &'a [u8], position: usize) -> Result<MemDecoder<'a>, ()> {
291        let data = data.strip_suffix(MAGIC_END_BYTES).ok_or(())?;
292        let Range { start, end } = data.as_ptr_range();
293        Ok(MemDecoder { start, current: data[position..].as_ptr(), end, _marker: PhantomData })
294    }
295
296    #[inline]
297    pub fn split_at(&self, position: usize) -> MemDecoder<'a> {
298        if !(position <= self.len()) {
    ::core::panicking::panic("assertion failed: position <= self.len()")
};assert!(position <= self.len());
299        // SAFETY: We checked above that this offset is within the original slice
300        let current = unsafe { self.start.add(position) };
301        MemDecoder { start: self.start, current, end: self.end, _marker: PhantomData }
302    }
303
304    #[inline]
305    pub fn len(&self) -> usize {
306        // SAFETY: This recovers the length of the original slice, only using members we never modify.
307        unsafe { self.end.offset_from_unsigned(self.start) }
308    }
309
310    #[inline]
311    pub fn remaining(&self) -> usize {
312        // SAFETY: This type guarantees current <= end.
313        unsafe { self.end.offset_from_unsigned(self.current) }
314    }
315
316    #[cold]
317    #[inline(never)]
318    fn decoder_exhausted() -> ! {
319        { ::core::panicking::panic_fmt(format_args!("MemDecoder exhausted")); }panic!("MemDecoder exhausted")
320    }
321
322    #[inline]
323    pub fn read_array<const N: usize>(&mut self) -> [u8; N] {
324        self.read_raw_bytes(N).try_into().unwrap()
325    }
326
327    /// While we could manually expose manipulation of the decoder position,
328    /// all current users of that method would need to reset the position later,
329    /// incurring the bounds check of set_position twice.
330    #[inline]
331    pub fn with_position<F, T>(&mut self, pos: usize, func: F) -> T
332    where
333        F: Fn(&mut MemDecoder<'a>) -> T,
334    {
335        struct SetOnDrop<'a, 'guarded> {
336            decoder: &'guarded mut MemDecoder<'a>,
337            current: *const u8,
338        }
339        impl Drop for SetOnDrop<'_, '_> {
340            fn drop(&mut self) {
341                self.decoder.current = self.current;
342            }
343        }
344
345        if pos >= self.len() {
346            Self::decoder_exhausted();
347        }
348        let previous = self.current;
349        // SAFETY: We just checked if this add is in-bounds above.
350        unsafe {
351            self.current = self.start.add(pos);
352        }
353        let guard = SetOnDrop { current: previous, decoder: self };
354        func(guard.decoder)
355    }
356}
357
358macro_rules! read_leb128 {
359    ($this_fn:ident, $int_ty:ty, $read_leb_fn:ident) => {
360        #[inline]
361        fn $this_fn(&mut self) -> $int_ty {
362            leb128::$read_leb_fn(self)
363        }
364    };
365}
366
367impl<'a> Decoder for MemDecoder<'a> {
368    #[inline]
fn read_usize(&mut self) -> usize { leb128::read_usize_leb128(self) }read_leb128!(read_usize, usize, read_usize_leb128);
369    #[inline]
fn read_u128(&mut self) -> u128 { leb128::read_u128_leb128(self) }read_leb128!(read_u128, u128, read_u128_leb128);
370    #[inline]
fn read_u64(&mut self) -> u64 { leb128::read_u64_leb128(self) }read_leb128!(read_u64, u64, read_u64_leb128);
371    #[inline]
fn read_u32(&mut self) -> u32 { leb128::read_u32_leb128(self) }read_leb128!(read_u32, u32, read_u32_leb128);
372
373    #[inline]
374    fn read_u16(&mut self) -> u16 {
375        u16::from_le_bytes(self.read_array())
376    }
377
378    #[inline]
379    fn read_u8(&mut self) -> u8 {
380        if self.current == self.end {
381            Self::decoder_exhausted();
382        }
383        // SAFETY: This type guarantees current <= end, and we just checked current == end.
384        unsafe {
385            let byte = *self.current;
386            self.current = self.current.add(1);
387            byte
388        }
389    }
390
391    #[inline]
fn read_isize(&mut self) -> isize { leb128::read_isize_leb128(self) }read_leb128!(read_isize, isize, read_isize_leb128);
392    #[inline]
fn read_i128(&mut self) -> i128 { leb128::read_i128_leb128(self) }read_leb128!(read_i128, i128, read_i128_leb128);
393    #[inline]
fn read_i64(&mut self) -> i64 { leb128::read_i64_leb128(self) }read_leb128!(read_i64, i64, read_i64_leb128);
394    #[inline]
fn read_i32(&mut self) -> i32 { leb128::read_i32_leb128(self) }read_leb128!(read_i32, i32, read_i32_leb128);
395
396    #[inline]
397    fn read_i16(&mut self) -> i16 {
398        i16::from_le_bytes(self.read_array())
399    }
400
401    #[inline]
402    fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] {
403        if bytes > self.remaining() {
404            Self::decoder_exhausted();
405        }
406        // SAFETY: We just checked if this range is in-bounds above.
407        unsafe {
408            let slice = std::slice::from_raw_parts(self.current, bytes);
409            self.current = self.current.add(bytes);
410            slice
411        }
412    }
413
414    #[inline]
415    fn peek_byte(&self) -> u8 {
416        if self.current == self.end {
417            Self::decoder_exhausted();
418        }
419        // SAFETY: This type guarantees current is inbounds or one-past-the-end, which is end.
420        // Since we just checked current == end, the current pointer must be inbounds.
421        unsafe { *self.current }
422    }
423
424    #[inline]
425    fn position(&self) -> usize {
426        // SAFETY: This type guarantees start <= current
427        unsafe { self.current.offset_from_unsigned(self.start) }
428    }
429}
430
431// Specializations for contiguous byte sequences follow. The default implementations for slices
432// encode and decode each element individually. This isn't necessary for `u8` slices when using
433// opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding.
434// Therefore, we can use more efficient implementations that process the entire sequence at once.
435
436// Specialize encoding byte slices. This specialization also applies to encoding `Vec<u8>`s, etc.,
437// since the default implementations call `encode` on their slices internally.
438impl Encodable<FileEncoder<'_>> for [u8] {
439    fn encode(&self, e: &mut FileEncoder<'_>) {
440        Encoder::emit_usize(e, self.len());
441        e.emit_raw_bytes(self);
442    }
443}
444
445// Specialize decoding `Vec<u8>`. This specialization also applies to decoding `Box<[u8]>`s, etc.,
446// since the default implementations call `decode` to produce a `Vec<u8>` internally.
447impl<'a> Decodable<MemDecoder<'a>> for Vec<u8> {
448    fn decode(d: &mut MemDecoder<'a>) -> Self {
449        let len = Decoder::read_usize(d);
450        d.read_raw_bytes(len).to_owned()
451    }
452}
453
454/// An integer that will always encode to 8 bytes.
455pub struct IntEncodedWithFixedSize(pub u64);
456
457impl IntEncodedWithFixedSize {
458    pub const ENCODED_SIZE: usize = 8;
459}
460
461impl Encodable<FileEncoder<'_>> for IntEncodedWithFixedSize {
462    #[inline]
463    fn encode(&self, e: &mut FileEncoder<'_>) {
464        let start_pos = e.position();
465        e.write_array(self.0.to_le_bytes());
466        let end_pos = e.position();
467        if true {
    match (&(end_pos - start_pos), &IntEncodedWithFixedSize::ENCODED_SIZE) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    };
};debug_assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
468    }
469}
470
471impl<'a> Decodable<MemDecoder<'a>> for IntEncodedWithFixedSize {
472    #[inline]
473    fn decode(decoder: &mut MemDecoder<'a>) -> IntEncodedWithFixedSize {
474        let bytes = decoder.read_array::<{ IntEncodedWithFixedSize::ENCODED_SIZE }>();
475        IntEncodedWithFixedSize(u64::from_le_bytes(bytes))
476    }
477}
478
479#[cfg(test)]
480mod tests;