Skip to main content

qubit_progress/error/
terminal_error.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Errors returned after a terminal emission is attempted.
9// qubit-style: allow source-test-pair
10
11use std::error::Error;
12use std::fmt;
13use std::time::Duration;
14
15use crate::error::EmissionError;
16
17/// Terminal emission failure paired with elapsed operation time.
18#[derive(Clone, Debug)]
19pub struct TerminalError {
20    elapsed: Duration,
21    source: EmissionError,
22}
23
24impl TerminalError {
25    /// Creates a terminal error.
26    pub(crate) const fn new(elapsed: Duration, source: EmissionError) -> Self {
27        Self { elapsed, source }
28    }
29
30    /// Returns elapsed operation time at terminal failure.
31    #[must_use]
32    pub const fn elapsed(&self) -> Duration {
33        self.elapsed
34    }
35
36    /// Returns the emission failure.
37    #[must_use]
38    pub const fn emission_error(&self) -> &EmissionError {
39        &self.source
40    }
41
42    /// Consumes the terminal error and returns its emission failure.
43    #[must_use]
44    pub fn into_emission_error(self) -> EmissionError {
45        self.source
46    }
47
48    /// Consumes the terminal error and returns elapsed time and failure.
49    #[must_use]
50    pub fn into_parts(self) -> (Duration, EmissionError) {
51        (self.elapsed, self.source)
52    }
53}
54
55impl fmt::Display for TerminalError {
56    /// Formats terminal elapsed time and the nested failure.
57    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58        write!(
59            formatter,
60            "terminal progress report failed after {:?}: {}",
61            self.elapsed, self.source
62        )
63    }
64}
65
66impl Error for TerminalError {
67    /// Returns the emission failure.
68    fn source(&self) -> Option<&(dyn Error + 'static)> {
69        Some(&self.source)
70    }
71}