Skip to main content

qubit_redact/text/
bounded_log_safe_display.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//! Bounded display adapter for log-safe text.
9
10use std::fmt::{
11    self,
12    Display,
13    Formatter,
14    Write as _,
15};
16
17use super::{
18    LogOutputLimit,
19    LogSafeText,
20    internal::BoundedLogEscapeWriter,
21};
22
23/// A byte-bounded rendering of text that is already safe for a log boundary.
24///
25/// # Type Parameters
26///
27/// * `'a` - Lifetime of the borrowed log-safe text.
28#[must_use = "format the bounded log-safe text"]
29pub struct BoundedLogSafeDisplay<'a> {
30    /// Escaped source text.
31    value: &'a LogSafeText<'a>,
32    /// Validated rendered output limit.
33    limit: LogOutputLimit,
34}
35
36impl<'a> BoundedLogSafeDisplay<'a> {
37    /// Creates a bounded view of already escaped log-safe text.
38    ///
39    /// # Parameters
40    ///
41    /// * `value` - Escaped source text to render.
42    /// * `limit` - Validated final output-byte limit.
43    ///
44    /// # Returns
45    ///
46    /// A borrowed bounded display adapter.
47    #[inline(always)]
48    pub(super) const fn new(
49        value: &'a LogSafeText<'a>,
50        limit: LogOutputLimit,
51    ) -> Self {
52        Self { value, limit }
53    }
54}
55
56impl Display for BoundedLogSafeDisplay<'_> {
57    /// Writes the escaped source text without exceeding the output limit.
58    ///
59    /// # Parameters
60    ///
61    /// * `formatter` - Destination formatting context.
62    ///
63    /// # Returns
64    ///
65    /// The formatter result after writing bounded escaped text.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`fmt::Error`] when the destination formatter rejects output.
70    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
71        let mut writer = BoundedLogEscapeWriter::new(self.limit);
72        // The internal writer uses `fmt::Error` only to stop after recording
73        // truncation; `finish` renders that state with a complete marker.
74        let _ = writer.write_str(self.value.as_str());
75        formatter.write_str(&writer.finish())
76    }
77}