qubit_argument/argument/argument_result_ext.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//! Nested path propagation for argument validation results.
9
10use crate::argument::ArgumentResult;
11use crate::argument::internal::Sealed;
12
13/// Adds nested argument-path context to validation results.
14///
15/// Successful results are returned unchanged and do not allocate a path.
16/// Failed results consume their [`crate::ArgumentError`] and prepend the
17/// supplied parent path while preserving the structured failure kind.
18///
19/// The trait is sealed and implemented only for [`ArgumentResult`].
20///
21/// # Type Parameters
22///
23/// - `T`: The value type carried by a successful argument result.
24///
25/// # Examples
26///
27/// ```
28/// use qubit_argument::{ArgumentError, ArgumentErrorKind, ArgumentResultExt};
29///
30/// let result: Result<(), _> = Err(ArgumentError::new(
31/// "value",
32/// ArgumentErrorKind::Missing,
33/// ));
34/// let error = result.with_path_prefix("user").unwrap_err();
35/// assert_eq!(error.path().as_str(), "user.value");
36/// ```
37pub trait ArgumentResultExt<T>: Sealed + Sized {
38 /// Prepends a parent path to a validation failure.
39 ///
40 /// # Parameters
41 ///
42 /// - `prefix`: The parent path to add before an error's current path.
43 ///
44 /// # Returns
45 ///
46 /// The unchanged successful value, or the original validation error with
47 /// its path prefixed.
48 ///
49 /// # Errors
50 ///
51 /// Returns the original validation error with `prefix` prepended to its
52 /// path when the result is an error.
53 fn with_path_prefix(self, prefix: &str) -> ArgumentResult<T>;
54}
55
56impl<T> ArgumentResultExt<T> for ArgumentResult<T> {
57 /// Prefixes only the error branch and leaves success values untouched.
58 #[inline]
59 fn with_path_prefix(self, prefix: &str) -> ArgumentResult<T> {
60 self.map_err(|error| error.with_path_prefix(prefix))
61 }
62}