1use std::fs::File;
2use std::io::{self, Write};
3use std::marker::PhantomData;
4use std::ops::Range;
5use std::path::{Path, PathBuf};
67// 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};
1213pub mod mem_encoder;
1415// -----------------------------------------------------------------------------
16// Encoder
17// -----------------------------------------------------------------------------
1819pub type FileEncodeResult = Result<usize, (PathBuf, io::Error)>;
2021pub const MAGIC_END_BYTES: &[u8] = b"rust-end-file";
2223/// The size of the buffer in `FileEncoder`.
24const BUF_SIZE: usize = 64 * 1024;
2526/// `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.
41buf: 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`.
47res: Result<(), io::Error>,
48 path: PathBuf,
49 flush_strategy: Option<&'a mut (dyn FnMut(&[u8]) + Send)>,
50#[cfg(debug_assertions)]
51finished: bool,
52}
5354impl<'a> FileEncoder<'a> {
55pub 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.
59let file =
60 File::options().read(true).write(true).create(true).truncate(true).open(&path)?;
6162Ok(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,
67file,
68 res: Ok(()),
69 flush_strategy: None,
70#[cfg(debug_assertions)]
71finished: false,
72 })
73 }
7475pub fn with_flush_strategy<P: AsRef<Path>>(
76 path: P,
77 strategy: &'a mut (dyn FnMut(&[u8]) + Send),
78 ) -> io::Result<Self> {
79let mut encoder = Self::new(path)?;
80encoder.flush_strategy = Some(strategy);
81Ok(encoder)
82 }
8384#[inline]
85pub 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`.
89self.flushed.debug_strict_add(self.buffered)
90 }
9192#[cold]
93 #[inline(never)]
94pub fn flush(&mut self) {
95#[cfg(debug_assertions)]
96{
97self.finished = false;
98 }
99if self.res.is_ok() {
100self.res = self.file.write_all(&self.buf[..self.buffered]);
101 }
102self.flushed += self.buffered;
103if let Some(f) = &mut self.flush_strategy {
104f(&self.buf[..self.buffered]);
105 }
106self.buffered = 0;
107 }
108109#[inline]
110pub fn file(&self) -> &File {
111&self.file
112 }
113114#[inline]
115pub fn path(&self) -> &Path {
116&self.path
117 }
118119#[inline]
120fn buffer_empty(&mut self) -> &mut [u8] {
121// SAFETY: self.buffered is inbounds as an invariant of the type
122unsafe { self.buf.get_unchecked_mut(self.buffered..) }
123 }
124125#[cold]
126 #[inline(never)]
127fn write_all_cold_path(&mut self, buf: &[u8]) {
128self.flush();
129if let Some(dest) = self.buf.get_mut(..buf.len()) {
130dest.copy_from_slice(buf);
131self.buffered += buf.len();
132 } else {
133if self.res.is_ok() {
134self.res = self.file.write_all(buf);
135if let Some(f) = &mut self.flush_strategy {
136f(buf);
137 }
138 }
139self.flushed += buf.len();
140 }
141 }
142143#[inline]
144fn write_all(&mut self, buf: &[u8]) {
145#[cfg(debug_assertions)]
146{
147self.finished = false;
148 }
149if let Some(dest) = self.buffer_empty().get_mut(..buf.len()) {
150dest.copy_from_slice(buf);
151self.buffered = self.buffered.debug_strict_add(buf.len());
152 } else {
153self.write_all_cold_path(buf);
154 }
155 }
156157/// 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]
172pub fn write_with<const N: usize>(&mut self, visitor: impl FnOnce(&mut [u8; N]) -> usize) {
173#[cfg(debug_assertions)]
174{
175self.finished = false;
176 }
177let flush_threshold = const { BUF_SIZE.checked_sub(N).unwrap() };
178if std::intrinsics::unlikely(self.buffered > flush_threshold) {
179self.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.
184let buf = unsafe { self.buffer_empty().first_chunk_mut::<N>().unwrap_unchecked() };
185let written = visitor(buf);
186// We have to ensure that an errant visitor cannot cause self.buffered to exceed BUF_SIZE.
187if written > N {
188Self::panic_invalid_write::<N>(written);
189 }
190self.buffered = self.buffered.debug_strict_add(written);
191 }
192193#[cold]
194 #[inline(never)]
195fn 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 }
198199/// Helper for calls where [`FileEncoder::write_with`] always writes the whole array.
200#[inline]
201pub fn write_array<const N: usize>(&mut self, buf: [u8; N]) {
202self.write_with(|dest| {
203*dest = buf;
204N205 })
206 }
207208pub fn finish(&mut self) -> FileEncodeResult {
209self.write_all(MAGIC_END_BYTES);
210self.flush();
211#[cfg(debug_assertions)]
212{
213self.finished = true;
214 }
215match std::mem::replace(&mut self.res, Ok(())) {
216Ok(()) => Ok(self.position()),
217Err(e) => Err((self.path.clone(), e)),
218 }
219 }
220}
221222#[cfg(debug_assertions)]
223impl Dropfor FileEncoder<'_> {
224fn drop(&mut self) {
225if !std::thread::panicking() {
226if !self.finished {
::core::panicking::panic("assertion failed: self.finished")
};assert!(self.finished);
227 }
228 }
229}
230231macro_rules!write_leb128 {
232 ($this_fn:ident, $int_ty:ty, $write_leb_fn:ident) => {
233#[inline]
234fn $this_fn(&mut self, v: $int_ty) {
235self.write_with(|buf| leb128::$write_leb_fn(buf, v))
236 }
237 };
238}
239240impl Encoderfor 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);
245246#[inline]
247fn emit_u16(&mut self, v: u16) {
248self.write_array(v.to_le_bytes());
249 }
250251#[inline]
252fn emit_u8(&mut self, v: u8) {
253self.write_array([v]);
254 }
255256#[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);
260261#[inline]
262fn emit_i16(&mut self, v: i16) {
263self.write_array(v.to_le_bytes());
264 }
265266#[inline]
267fn emit_raw_bytes(&mut self, s: &[u8]) {
268self.write_all(s);
269 }
270}
271272// -----------------------------------------------------------------------------
273// Decoder
274// -----------------------------------------------------------------------------
275276// 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}
287288impl<'a> MemDecoder<'a> {
289#[inline]
290pub fn new(data: &'a [u8], position: usize) -> Result<MemDecoder<'a>, ()> {
291let data = data.strip_suffix(MAGIC_END_BYTES).ok_or(())?;
292let Range { start, end } = data.as_ptr_range();
293Ok(MemDecoder { start, current: data[position..].as_ptr(), end, _marker: PhantomData })
294 }
295296#[inline]
297pub fn split_at(&self, position: usize) -> MemDecoder<'a> {
298if !(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
300let current = unsafe { self.start.add(position) };
301MemDecoder { start: self.start, current, end: self.end, _marker: PhantomData }
302 }
303304#[inline]
305pub fn len(&self) -> usize {
306// SAFETY: This recovers the length of the original slice, only using members we never modify.
307unsafe { self.end.offset_from_unsigned(self.start) }
308 }
309310#[inline]
311pub fn remaining(&self) -> usize {
312// SAFETY: This type guarantees current <= end.
313unsafe { self.end.offset_from_unsigned(self.current) }
314 }
315316#[cold]
317 #[inline(never)]
318fn decoder_exhausted() -> ! {
319{ ::core::panicking::panic_fmt(format_args!("MemDecoder exhausted")); }panic!("MemDecoder exhausted")320 }
321322#[inline]
323pub fn read_array<const N: usize>(&mut self) -> [u8; N] {
324self.read_raw_bytes(N).try_into().unwrap()
325 }
326327/// 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]
331pub fn with_position<F, T>(&mut self, pos: usize, func: F) -> T
332where
333F: Fn(&mut MemDecoder<'a>) -> T,
334 {
335struct SetOnDrop<'a, 'guarded> {
336 decoder: &'guarded mut MemDecoder<'a>,
337 current: *const u8,
338 }
339impl Dropfor SetOnDrop<'_, '_> {
340fn drop(&mut self) {
341self.decoder.current = self.current;
342 }
343 }
344345if pos >= self.len() {
346Self::decoder_exhausted();
347 }
348let previous = self.current;
349// SAFETY: We just checked if this add is in-bounds above.
350unsafe {
351self.current = self.start.add(pos);
352 }
353let guard = SetOnDrop { current: previous, decoder: self };
354func(guard.decoder)
355 }
356}
357358macro_rules!read_leb128 {
359 ($this_fn:ident, $int_ty:ty, $read_leb_fn:ident) => {
360#[inline]
361fn $this_fn(&mut self) -> $int_ty {
362 leb128::$read_leb_fn(self)
363 }
364 };
365}
366367impl<'a> Decoderfor 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);
372373#[inline]
374fn read_u16(&mut self) -> u16 {
375u16::from_le_bytes(self.read_array())
376 }
377378#[inline]
379fn read_u8(&mut self) -> u8 {
380if self.current == self.end {
381Self::decoder_exhausted();
382 }
383// SAFETY: This type guarantees current <= end, and we just checked current == end.
384unsafe {
385let byte = *self.current;
386self.current = self.current.add(1);
387byte388 }
389 }
390391#[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);
395396#[inline]
397fn read_i16(&mut self) -> i16 {
398i16::from_le_bytes(self.read_array())
399 }
400401#[inline]
402fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] {
403if bytes > self.remaining() {
404Self::decoder_exhausted();
405 }
406// SAFETY: We just checked if this range is in-bounds above.
407unsafe {
408let slice = std::slice::from_raw_parts(self.current, bytes);
409self.current = self.current.add(bytes);
410slice411 }
412 }
413414#[inline]
415fn peek_byte(&self) -> u8 {
416if self.current == self.end {
417Self::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.
421unsafe { *self.current }
422 }
423424#[inline]
425fn position(&self) -> usize {
426// SAFETY: This type guarantees start <= current
427unsafe { self.current.offset_from_unsigned(self.start) }
428 }
429}
430431// 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.
435436// 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] {
439fn encode(&self, e: &mut FileEncoder<'_>) {
440 Encoder::emit_usize(e, self.len());
441e.emit_raw_bytes(self);
442 }
443}
444445// 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> {
448fn decode(d: &mut MemDecoder<'a>) -> Self {
449let len = Decoder::read_usize(d);
450d.read_raw_bytes(len).to_owned()
451 }
452}
453454/// An integer that will always encode to 8 bytes.
455pub struct IntEncodedWithFixedSize(pub u64);
456457impl IntEncodedWithFixedSize {
458pub const ENCODED_SIZE: usize = 8;
459}
460461impl Encodable<FileEncoder<'_>> for IntEncodedWithFixedSize {
462#[inline]
463fn encode(&self, e: &mut FileEncoder<'_>) {
464let start_pos = e.position();
465e.write_array(self.0.to_le_bytes());
466let end_pos = e.position();
467if 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}
470471impl<'a> Decodable<MemDecoder<'a>> for IntEncodedWithFixedSize {
472#[inline]
473fn decode(decoder: &mut MemDecoder<'a>) -> IntEncodedWithFixedSize {
474let bytes = decoder.read_array::<{ IntEncodedWithFixedSize::ENCODED_SIZE }>();
475IntEncodedWithFixedSize(u64::from_le_bytes(bytes))
476 }
477}
478479#[cfg(test)]
480mod tests;