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::{
12    error::Error,
13    fmt,
14    time::Duration,
15};
16
17use crate::error::EmissionError;
18
19/// Terminal emission failure paired with elapsed operation time.
20#[derive(Clone, Debug)]
21pub struct TerminalError {
22    elapsed: Duration,
23    source: EmissionError,
24}
25
26impl TerminalError {
27    /// Creates a terminal error.
28    pub(crate) const fn new(elapsed: Duration, source: EmissionError) -> Self {
29        Self { elapsed, source }
30    }
31
32    /// Returns elapsed operation time at terminal failure.
33    #[must_use]
34    pub const fn elapsed(&self) -> Duration {
35        self.elapsed
36    }
37
38    /// Returns the emission failure.
39    #[must_use]
40    pub const fn emission_error(&self) -> &EmissionError {
41        &self.source
42    }
43
44    /// Consumes the terminal error and returns its emission failure.
45    #[must_use]
46    pub fn into_emission_error(self) -> EmissionError {
47        self.source
48    }
49
50    /// Consumes the terminal error and returns elapsed time and failure.
51    #[must_use]
52    pub fn into_parts(self) -> (Duration, EmissionError) {
53        (self.elapsed, self.source)
54    }
55}
56
57impl fmt::Display for TerminalError {
58    /// Formats terminal elapsed time and the nested failure.
59    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(
61            formatter,
62            "terminal progress report failed after {:?}: {}",
63            self.elapsed, self.source
64        )
65    }
66}
67
68impl Error for TerminalError {
69    /// Returns the emission failure.
70    fn source(&self) -> Option<&(dyn Error + 'static)> {
71        Some(&self.source)
72    }
73}