Skip to main content

cargo/core/compiler/
job.rs

1use std::fmt;
2use std::mem;
3
4use super::job_queue::JobState;
5use crate::util::CargoResult;
6
7pub struct Job {
8    work: Work,
9    fresh: Freshness,
10}
11
12/// Each proc should send its description before starting.
13/// It should send either once or close immediately.
14pub struct Work {
15    inner: Box<dyn FnOnce(&JobState<'_>) -> CargoResult<()> + Send>,
16}
17
18impl Work {
19    pub fn new<F>(f: F) -> Work
20    where
21        F: FnOnce(&JobState<'_>) -> CargoResult<()> + Send + 'static,
22    {
23        Work { inner: Box::new(f) }
24    }
25
26    pub fn noop() -> Work {
27        Work::new(|_| Ok(()))
28    }
29
30    pub fn call(self, tx: &JobState<'_>) -> CargoResult<()> {
31        (self.inner)(tx)
32    }
33
34    pub fn then(self, next: Work) -> Work {
35        Work::new(move |state| {
36            self.call(state)?;
37            next.call(state)
38        })
39    }
40}
41
42impl Job {
43    /// Creates a new job representing a unit of work.
44    pub fn new(work: Work, fresh: Freshness) -> Job {
45        Job { work, fresh }
46    }
47
48    /// Consumes this job by running it, returning the result of the
49    /// computation.
50    pub fn run(self, state: &JobState<'_>) -> CargoResult<()> {
51        self.work.call(state)
52    }
53
54    /// Returns whether this job was fresh/dirty, where "fresh" means we're
55    /// likely to perform just some small bookkeeping where "dirty" means we'll
56    /// probably do something slow like invoke rustc.
57    pub fn freshness(&self) -> Freshness {
58        self.fresh
59    }
60
61    pub fn before(&mut self, next: Work) {
62        let prev = mem::replace(&mut self.work, Work::noop());
63        self.work = next.then(prev);
64    }
65}
66
67impl fmt::Debug for Job {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "Job {{ ... }}")
70    }
71}
72
73/// Indication of the freshness of a package.
74///
75/// A fresh package does not necessarily need to be rebuilt (unless a dependency
76/// was also rebuilt), and a dirty package must always be rebuilt.
77#[derive(PartialEq, Eq, Debug, Clone, Copy)]
78pub enum Freshness {
79    Fresh,
80    Dirty,
81}