wasmer_compiler/
progress.rs

1//! Shared helpers for reporting compilation progress across the different backends.
2
3use crate::lib::std::{
4    borrow::Cow,
5    sync::{
6        Arc,
7        atomic::{AtomicU64, Ordering},
8    },
9};
10use wasmer_types::{CompilationProgress, CompilationProgressCallback, CompileError};
11
12/// Tracks progress within a compilation phase and forwards updates to a callback.
13///
14/// Convenience wrapper around a [`CompilationProgressCallback`] for the compilers.
15#[derive(Clone)]
16pub struct ProgressContext {
17    callback: CompilationProgressCallback,
18    counter: Arc<AtomicU64>,
19    total: u64,
20    phase_name: &'static str,
21}
22
23impl ProgressContext {
24    /// Creates a new [`ProgressContext`] for the given phase.
25    pub fn new(
26        callback: CompilationProgressCallback,
27        total: u64,
28        phase_name: &'static str,
29    ) -> Self {
30        Self {
31            callback,
32            counter: Arc::new(AtomicU64::new(0)),
33            total,
34            phase_name,
35        }
36    }
37
38    /// Notifies the callback that the next step in the phase has completed.
39    pub fn notify(&self) -> Result<(), CompileError> {
40        self.notify_steps(1)
41    }
42
43    /// Notifies the callback that the next N steps in the phase are completed.
44    pub fn notify_steps(&self, steps: u64) -> Result<(), CompileError> {
45        let step = self.counter.fetch_add(steps, Ordering::SeqCst) + steps;
46        self.callback
47            .notify(CompilationProgress::new(
48                Some(Cow::Borrowed(self.phase_name)),
49                Some(self.total),
50                Some(step),
51            ))
52            .map_err(CompileError::from)
53    }
54}