Skip to main content

retex_engine/
snapshot.rs

1//! Resuming a run from a snapshot of the process.
2//!
3//! The pass driver (in `retex-cli`) forks the process when LaTeX begins
4//! the document: everything before is the same in every pass, so later
5//! passes resume from that point instead of running the preamble again.
6//! The engine's part is the hook that marks the point
7//! ([`Engine::snapshot_hook`]) and the output files: they are flushed
8//! before the fork, and a resumed process reopens them, cut back to their
9//! length at the snapshot.
10
11use std::io::{Seek, SeekFrom};
12use std::path::PathBuf;
13use std::rc::Rc;
14
15use crate::Engine;
16use crate::input::{Level, LineSource};
17
18/// The snapshot hook (see [`Engine::snapshot_hook`]).
19pub type Hook = Box<dyn FnOnce(&mut Engine)>;
20
21/// New contents of the input files being read (see
22/// [`Engine::reloaded_inputs`]).
23pub struct Reload(Vec<(usize, Rc<[u8]>)>);
24
25/// An output file open when the snapshot was taken.
26#[derive(Clone, Debug)]
27pub struct OpenOutput {
28    /// The file.
29    pub path: PathBuf,
30    /// Its length at the snapshot.
31    pub len: u64,
32    /// The `\write` stream, or `None` for the log file.
33    stream: Option<u32>,
34}
35
36impl Engine {
37    /// Flushes all output and lists the output files that are open.
38    pub fn snapshot_outputs(&mut self) -> Vec<OpenOutput> {
39        self.printer.flush();
40        let mut out = Vec::new();
41        if self.printer.log_opened()
42            && let Some(path) = &self.files.log_name
43        {
44            out.push(OpenOutput {
45                path: path.clone(),
46                len: std::fs::metadata(path).map_or(0, |m| m.len()),
47                stream: None,
48            });
49        }
50        for n in self.printer.open_write_streams() {
51            if let Some(Some(path)) = self.write_paths.get(n as usize) {
52                out.push(OpenOutput {
53                    path: path.clone(),
54                    len: std::fs::metadata(path).map_or(0, |m| m.len()),
55                    stream: Some(n),
56                });
57            }
58        }
59        out
60    }
61
62    /// In a process resumed from a snapshot: reopens the output files
63    /// listed by [`snapshot_outputs`](Self::snapshot_outputs), truncated to
64    /// their length at the snapshot.
65    pub fn resume_outputs(&mut self, outputs: &[OpenOutput]) -> std::io::Result<()> {
66        for o in outputs {
67            let mut f = std::fs::OpenOptions::new().write(true).open(&o.path)?;
68            f.set_len(o.len)?;
69            f.seek(SeekFrom::End(0))?;
70            match o.stream {
71                None => self
72                    .printer
73                    .set_log(Box::new(std::io::BufWriter::with_capacity(1 << 16, f))),
74                Some(n) => {
75                    let w = crate::files::RecordingWriter::resume(
76                        f,
77                        o.path.clone(),
78                        self.written_sink.clone(),
79                    );
80                    self.printer.open_write(n, Box::new(w));
81                }
82            }
83        }
84        Ok(())
85    }
86
87    /// The input files being read, from the outermost.
88    pub fn open_input_files(&self) -> Vec<PathBuf> {
89        self.file_levels().map(|(_, path, _, _)| path).collect()
90    }
91
92    /// The text levels reading files: stack index, path, content and
93    /// number of bytes read.
94    fn file_levels(&self) -> impl Iterator<Item = (usize, PathBuf, &[u8], usize)> {
95        self.input
96            .stack
97            .iter()
98            .enumerate()
99            .filter_map(|(i, l)| match l {
100                Level::Text(t) => match &t.source {
101                    LineSource::File { data, pos } => {
102                        let path = PathBuf::from(String::from_utf8_lossy(&t.name).into_owned());
103                        Some((i, path, &data[..], *pos))
104                    }
105                    _ => None,
106                },
107                Level::Tokens(_) => None,
108            })
109    }
110
111    /// Reads the input files being read again, for a process resumed from
112    /// a snapshot after they were edited (`--watch`): the part already read
113    /// must be unchanged; the rest may differ. Returns the first file
114    /// whose read part changed (or that cannot be read) as the error.
115    pub fn reloaded_inputs(&self) -> Result<Reload, PathBuf> {
116        let mut out = Vec::new();
117        for (i, path, data, pos) in self.file_levels() {
118            match std::fs::read(&path) {
119                Ok(new) if new.get(..pos) == data.get(..pos) => out.push((i, Rc::from(new))),
120                _ => return Err(path),
121            }
122        }
123        Ok(Reload(out))
124    }
125
126    /// Continues reading the input files with the contents of `reload`.
127    pub fn reload_inputs(&mut self, reload: Reload) {
128        for (i, new) in reload.0 {
129            if let Some(Level::Text(t)) = self.input.stack.get_mut(i)
130                && let LineSource::File { data, .. } = &mut t.source
131            {
132                *data = new;
133            }
134        }
135    }
136
137    /// Runs the snapshot hook if `cs` is the control sequence it waits for.
138    #[inline]
139    pub(crate) fn check_snapshot(&mut self) {
140        if self.snapshot_cs.is_some_and(|cs| cs == self.cur_cs) {
141            self.snapshot_cs = None;
142            if let Some(hook) = self.snapshot_hook.take() {
143                hook(self);
144            }
145        }
146    }
147}