Skip to main content

qubit_validator/binding/
contextual_text_validator_adapter.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
9//! Adapter from text validators that consume dependency context.
10
11use std::error::Error;
12use std::sync::Arc;
13
14use super::BoundValidationContext;
15use super::DependencySpec;
16use super::PreparedValidator;
17use super::internal::ContextualTextValidatorAdapter;
18use crate::Validator;
19use crate::ViolationDraft;
20
21/// Prepares a text validator that reads its declared dependency slots.
22///
23/// The adapter passes the supplied [`BoundValidationContext`] directly to the
24/// typed validator. When execution goes through [`super::BoundValidator`],
25/// that boundary checks dependency count, shape, optionality, and paths before
26/// invoking the adapter. The returned adapter does not validate the declared
27/// dependency contract itself. Callers invoking [`PreparedValidator::validate`]
28/// directly must supply a context satisfying
29/// [`PreparedValidator::dependency_specs`]. Domain errors are converted with
30/// `map_error`; callers must keep raw input out of the resulting draft.
31///
32/// # Type Parameters
33///
34/// - `V`: Text validator implementing the context-aware [`Validator`] contract.
35/// - `E`: Its static domain error type, created and mapped within the
36///   synchronous call, so it need not be `Send` or `Sync`.
37/// - `M`: Mapper from the domain error to a safe violation draft.
38///
39/// # Panics
40///
41/// This function does not panic. A non-text erased input is returned as an
42/// execution error by the prepared adapter.
43///
44/// # Parameters
45///
46/// - `dependencies`: Static dependency slots declared in execution order.
47/// - `validator`: Thread-safe validator invoked with checked text and context.
48/// - `map_error`: Converts a domain error to safe violation metadata.
49///
50/// # Returns
51///
52/// A shared prepared adapter for the supplied validator and mapper.
53#[must_use]
54pub fn prepare_contextual_text_validator<V, E, M>(
55    dependencies: &'static [DependencySpec],
56    validator: V,
57    map_error: M,
58) -> Arc<dyn PreparedValidator>
59where
60    V: for<'a> Validator<str, BoundValidationContext<'a>, Error = E> + Send + Sync + 'static,
61    E: Error + 'static,
62    M: Fn(E) -> ViolationDraft + Send + Sync + 'static,
63{
64    Arc::new(ContextualTextValidatorAdapter::new(validator, map_error, dependencies))
65}