qubit_budget/resource/budget/resource_budget/string_output.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//! Adds transactional UTF-8 output to [`ResourceBudget`].
9
10use std::fmt;
11
12use super::ResourceBudget;
13use crate::resource::ResourceQuantity;
14use crate::string::BudgetedStringError;
15use crate::string::BudgetedStringWriter;
16use crate::string::render_budgeted_string;
17
18impl<R, Q> ResourceBudget<R, Q>
19where
20 R: Clone + fmt::Debug,
21 Q: ResourceQuantity,
22{
23 /// Renders and transactionally commits a UTF-8 string under this budget.
24 ///
25 /// # Type Parameters
26 ///
27 /// * `E` - Error type returned by the caller-provided renderer.
28 /// * `F` - Closure used to render the output string.
29 ///
30 /// # Parameters
31 ///
32 /// * `render` - Caller-provided renderer writing into the transactional
33 /// adapter.
34 ///
35 /// # Returns
36 ///
37 /// `Ok(rendered)` after the complete UTF-8 output is charged and committed.
38 ///
39 /// # Errors
40 ///
41 /// Returns [`BudgetedStringError`] when rendering, allocation, UTF-8
42 /// validation, measurement, or budget accounting fails.
43 #[inline(always)]
44 pub fn try_write_string<E, F>(&mut self, render: F) -> Result<String, BudgetedStringError<R, E, Q>>
45 where
46 E: fmt::Debug + fmt::Display,
47 F: FnOnce(&mut BudgetedStringWriter<'_, R, Q>) -> Result<(), E>,
48 {
49 render_budgeted_string(self, render)
50 }
51}