qubit_progress/reporter/impls/formatted_progress_reporter.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10use qubit_function::Consumer;
11
12use crate::{
13 model::ProgressEvent,
14 reporter::{
15 ProgressReporter,
16 format::MetricSnapshotFormatter,
17 },
18};
19
20/// Progress reporter that formats each metric snapshot and sends it to a consumer.
21///
22/// This reporter is the common adapter behind text and JSON progress reporters.
23/// It converts every counter in an event into a metric snapshot, formats the
24/// snapshot, then passes the formatted string to the configured consumer.
25pub struct FormattedProgressReporter<F, C> {
26 /// Formatter applied to each metric snapshot.
27 formatter: F,
28 /// Consumer receiving formatted snapshot strings.
29 consumer: C,
30}
31
32impl<F, C> FormattedProgressReporter<F, C> {
33 /// Creates a formatted progress reporter.
34 ///
35 /// # Parameters
36 ///
37 /// * `formatter` - Formatter applied to each metric snapshot.
38 /// * `consumer` - Consumer receiving formatted strings.
39 ///
40 /// # Returns
41 ///
42 /// A reporter that formats metric snapshots and sends strings to `consumer`.
43 #[inline]
44 pub const fn new(formatter: F, consumer: C) -> Self {
45 Self { formatter, consumer }
46 }
47
48 /// Returns the configured formatter.
49 ///
50 /// # Returns
51 ///
52 /// A shared reference to the metric snapshot formatter.
53 #[inline]
54 pub const fn formatter(&self) -> &F {
55 &self.formatter
56 }
57
58 /// Returns the configured consumer.
59 ///
60 /// # Returns
61 ///
62 /// A shared reference to the formatted string consumer.
63 #[inline]
64 pub const fn consumer(&self) -> &C {
65 &self.consumer
66 }
67}
68
69impl<F, C> ProgressReporter for FormattedProgressReporter<F, C>
70where
71 F: MetricSnapshotFormatter,
72 C: Consumer<String> + Send + Sync,
73{
74 /// Formats and consumes every metric snapshot in an event.
75 ///
76 /// # Parameters
77 ///
78 /// * `event` - Event whose metric snapshots should be formatted.
79 fn report(&self, event: &ProgressEvent) {
80 for snapshot in event.metric_snapshots() {
81 let line = self.formatter.format(&snapshot);
82 self.consumer.accept(&line);
83 }
84 }
85}