Skip to main content

Crate qubit_validator

Crate qubit_validator 

Source
Expand description

Type-safe validation traits and immutable validator registries.

Use Validator for direct typed validation. Use a prepared adapter when a domain rule must cross an erased input boundary. For configured execution, declare ValidatorSignature values in a ValidatorDescriptor, register the descriptor, then bind it into a reusable BoundValidator. Aggregate bound results explicitly with ValidationReport when a caller needs a report; this crate does not schedule rules.

A prepared validator is a lower-level entry point. Direct callers must provide a context that satisfies its declared dependency contract; bound execution performs the input and dependency checks before invoking it.

§Direct typed validation

use std::fmt;

use qubit_validator::Validator;

struct Positive;
#[derive(Debug)]
struct NotPositive;

impl fmt::Display for NotPositive {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("value must be positive")
    }
}
impl std::error::Error for NotPositive {}

impl Validator<i32> for Positive {
    type Error = NotPositive;

    fn validate(&self, value: &i32, _: &()) -> Result<(), Self::Error> {
        if *value > 0 { Ok(()) } else { Err(NotPositive) }
    }
}

Positive.validate(&7, &()).unwrap();
assert!(Positive.validate(&0, &()).is_err());

§Configured validation and reporting

use std::sync::Arc;

use qubit_validator::{
    ArgumentReader, BindError, BoundValidationContext, InputType,
    PreparedValidator, RegistrationSource, ValidationOutcome, ValidationPath,
    ValidationReport, ValidationValue, Validator, ValidatorDescriptor, ValidatorId,
    ValidatorRegistration, ValidatorRegistry, ValidatorSignature, ViolationCode,
    prepare_text_validator,
};

struct NonBlank;
#[derive(Debug)]
struct Blank;
impl std::fmt::Display for Blank {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("blank name")
    }
}
impl std::error::Error for Blank {}

impl Validator<str> for NonBlank {
    type Error = Blank;

    fn validate(&self, value: &str, _: &()) -> Result<(), Self::Error> {
        if value.trim().is_empty() { Err(Blank) } else { Ok(()) }
    }
}

fn prepare(_reader: &mut ArgumentReader<'_>) -> Result<Arc<dyn PreparedValidator>, BindError> {
    Ok(prepare_text_validator(NonBlank, |_| {
        qubit_validator::ViolationDraft::new(qubit_validator::ViolationCode::new("text.blank"))
    }))
}

static SIGNATURES: &[ValidatorSignature] = &[ValidatorSignature::new(InputType::Text, &[], prepare)];
static DESCRIPTOR: ValidatorDescriptor = ValidatorDescriptor::new(SIGNATURES);
static REGISTRATION: ValidatorRegistration = ValidatorRegistration::new(
    ValidatorId::new("profile.name.non_blank"),
    &DESCRIPTOR,
    RegistrationSource::new("profile-rules", "profile", "rules.rs", 1),
);

let registry = ValidatorRegistry::from_registrations([&REGISTRATION])?;
let rule = registry.bind("profile.name.non_blank", InputType::Text, &[])?;
let outcome = rule.validate(
    ValidationValue::Text("Ada"),
    &BoundValidationContext::new(&[]),
)?;
let mut report = ValidationReport::new();
report.record_outcome(0, ValidationPath::root().with_field("name"), outcome)?;
assert!(report.is_valid());

let invalid = rule.validate(
    ValidationValue::Text("  "),
    &BoundValidationContext::new(&[]),
)?;
assert!(matches!(invalid, ValidationOutcome::Invalid(_)));
report.record_outcome(
    1,
    ValidationPath::root().with_field("name"),
    invalid,
)?;
assert!(!report.is_valid());
assert_eq!(report.violations()[0].code(), ViolationCode::new("text.blank"));

Macros§

register_validator
Registers a static typed validator descriptor in the optional global registry.

Structs§

ArgumentReader
Reads declared arguments exactly once while rejecting duplicates, unknown names, and lossy numeric conversions.
BindError
A binding error that does not retain raw parameter values.
BoundValidationContext
Borrowed dependency slots used during a synchronous validation call.
BoundValidator
A bound occurrence that owns a reusable prepared validator instance.
DependencySpec
Describes one ordered dependency slot supplied to a validator.
ExecutionError
An execution error with a safe public diagnostic surface.
FailureId
Identifies one retained failure within its originating report.
NamedValidationArgument
One named validator parameter.
NamedValidationDependency
One dependency value identified by its signature name.
RecordedOutcome
Describes whether an outcome fit the report limits and identifies its retained failures.
RegistrationSource
Source location for one linked registration.
SkippedValidation
One validation occurrence that was skipped by the executor.
ValidationLimits
Explicit bounds applied while collecting a validation report.
ValidationPath
A structured path to a value being validated.
ValidationReport
A bounded collection of validation violations and skipped occurrences.
ValidatorDescriptor
A definition containing one or more input/dependency signatures.
ValidatorId
A validated, process-independent validator identifier.
ValidatorRegistration
One validator definition associated with a stable identifier.
ValidatorRegistry
A deterministic local registry containing one definition per stable ID.
ValidatorSignature
One statically declared way to bind a validator.
Violation
One rule violation without the rejected value.
ViolationCode
A stable violation code using the point-separated ASCII protocol.
ViolationDraft
A structured violation draft without a rule identity.

Enums§

BindErrorKind
A configuration or declaration error found while binding a rule.
ExecutionErrorKind
A failure in the validation execution infrastructure.
InputType
The two intentionally small input views used by the validation boundary.
PathSegment
One location segment in a validation path.
PreparedOutcome
The type-erased result produced before rule identity is attached.
SkipReason
Why a rule did not run.
ValidationArgument
One statically typed validator parameter value.
ValidationOutcome
The observable result of executing one bound validator occurrence.
ValidationOutcomeError
An outcome violates the invariant required by its declared variant.
ValidationValue
A value view that deliberately avoids implicit stringification and cloning.
ValidatorIdError
A stable validator ID protocol violation.
ValidatorRegistryError
Failure while freezing a validator registry.
ViolationCodeError
The reason a candidate string violates the stable violation-code protocol.
ViolationParam
A restricted vocabulary for diagnostic parameters. The type limits how a value is represented; it cannot prove where the value came from. Callers must supply only program-declared tokens or rule configuration values, never rejected input or sensitive values derived from it.

Traits§

PreparedValidator
A configured, immutable validator instance safe to share between calls.
Validator
Validates a borrowed value using an immutable, typed context.

Functions§

prepare_contextual_text_validator
Prepares a text validator that reads its declared dependency slots.
prepare_contextual_typed_validator
Prepares a typed validator that reads its declared dependency slots.
prepare_text_domain_rule
Prepares a text domain validator with dependency context and error mapping.
prepare_text_validator
Prepares a text validator using a domain-error mapper.
prepare_text_with_context
Prepares a text validation closure that receives its checked dependency context.
prepare_typed_domain_rule
Prepares a typed domain validator with dependency context and error mapping.
prepare_typed_validator
Prepares a typed validator using a domain-error mapper.
prepare_typed_with_context
Prepares a typed validation closure that receives its checked dependency context.

Type Aliases§

PrepareFn
Constructs an owned prepared validator from declaration parameters.