Skip to main content

ViolationCode

Struct ViolationCode 

Source
pub struct ViolationCode(/* private fields */);
Expand description

A stable violation code using the point-separated ASCII protocol.

The value is non-empty and consists of one or more dot-separated segments. Each segment starts with an ASCII letter and continues with ASCII letters, digits, or underscores. Empty segments, whitespace, non-ASCII letters, and hyphens are rejected. No trimming or case normalization is performed.

§Examples

use qubit_validator::ViolationCode;
use qubit_validator::ViolationCodeError;

let code = ViolationCode::try_new("text.length.minimum")?;
assert_eq!(code.as_str(), "text.length.minimum");
let error = ViolationCode::try_new("text..minimum").unwrap_err();
assert_eq!(error, ViolationCodeError::EmptySegment);
assert_eq!(
    ViolationCode::try_new("text.min-length"),
    Err(ViolationCodeError::InvalidSegment),
);

Implementations§

Source§

impl ViolationCode

Source

pub const fn new(value: &'static str) -> Self

Creates a code from a valid static string.

§Parameters
  • value: A static string containing the complete protocol value.
§Returns

The validated violation code.

§Panics

Panics when value violates the syntax documented on ViolationCode.

Examples found in repository?
examples/local_registry.rs (line 71)
69fn prepare_non_blank(_reader: &mut ArgumentReader<'_>) -> Result<Arc<dyn PreparedValidator>, BindError> {
70    Ok(prepare_text_validator(NonBlank, |_| {
71        ViolationDraft::new(ViolationCode::new("text.blank"))
72    }))
73}
74
75static SIGNATURES: &[ValidatorSignature] = &[ValidatorSignature::new(InputType::Text, &[], prepare_non_blank)];
76static DESCRIPTOR: ValidatorDescriptor = ValidatorDescriptor::new(SIGNATURES);
77
78#[cfg(feature = "inventory")]
79register_validator!(id = "text.non_blank.global", descriptor = &DESCRIPTOR);
80
81static DEPENDENCIES: &[DependencySpec] = &[
82    DependencySpec::new("minimum", InputType::Text, false),
83    DependencySpec::new("maximum", InputType::Text, false),
84];
85
86struct CheckDependencySlots;
87
88impl PreparedValidator for CheckDependencySlots {
89    fn input_type(&self) -> InputType {
90        InputType::Text
91    }
92    fn dependency_specs(&self) -> &'static [DependencySpec] {
93        DEPENDENCIES
94    }
95
96    fn validate(
97        &self,
98        _: ValidationValue<'_>,
99        context: &BoundValidationContext<'_>,
100    ) -> Result<PreparedOutcome, ExecutionError> {
101        let valid = context.value(0)?.as_text() == Some("minimum") && context.value(1)?.as_text() == Some("maximum");
102        Ok(if valid {
103            PreparedOutcome::Valid
104        } else {
105            PreparedOutcome::Invalid(vec![ViolationDraft::new(ViolationCode::new(
106                "text.dependencies_mismatch",
107            ))])
108        })
109    }
110}
111
112fn prepare_dependency_slots(_reader: &mut ArgumentReader<'_>) -> Result<Arc<dyn PreparedValidator>, BindError> {
113    Ok(Arc::new(CheckDependencySlots))
114}
115
116static DEPENDENCY_SIGNATURES: &[ValidatorSignature] = &[ValidatorSignature::new(
117    InputType::Text,
118    DEPENDENCIES,
119    prepare_dependency_slots,
120)];
121static DEPENDENCY_DESCRIPTOR: ValidatorDescriptor = ValidatorDescriptor::new(DEPENDENCY_SIGNATURES);
122
123fn assert_dependency_specs_come_from_signature() -> Result<(), ExecutionError> {
124    let bound = DEPENDENCY_DESCRIPTOR
125        .bind(ValidatorId::new("text.dependent"), 0, &[])
126        .expect("signature binds");
127    assert_eq!(bound.dependency_specs(), DEPENDENCIES);
128    let dependencies = [
129        NamedValidationDependency::new("maximum", ValidationValue::Text("maximum")),
130        NamedValidationDependency::new("minimum", ValidationValue::Text("minimum")),
131    ];
132    assert_eq!(
133        bound.validate_named(ValidationValue::Text("target"), &dependencies)?,
134        ValidationOutcome::Valid,
135    );
136    Ok(())
137}
138
139fn assert_parameters_are_consumed_once() -> Result<(), BindError> {
140    let args = [NamedValidationArgument::new("limit", ValidationArgument::Unsigned(10))];
141    let mut reader = ArgumentReader::new(&args)?;
142    assert_eq!(reader.required_u32("limit")?, 10);
143    let error = reader
144        .required_u32("limit")
145        .expect_err("a parameter cannot be read twice");
146    assert_eq!(error.kind(), BindErrorKind::ParameterAlreadyConsumed);
147    Ok(())
148}
149
150fn main() -> Result<(), Box<dyn Error>> {
151    let registration = ValidatorRegistration::new(
152        ValidatorId::new("text.non_blank"),
153        &DESCRIPTOR,
154        RegistrationSource::new(env!("CARGO_PKG_NAME"), module_path!(), file!(), line!()),
155    );
156    let registry = ValidatorRegistry::from_registrations([registration])?;
157
158    assert!(registry.get("text.non_blank").is_some());
159    let validator = registry.bind("text.non_blank", InputType::Text, &[])?;
160    let context = BoundValidationContext::new(&[]);
161
162    let valid = validator.validate(ValidationValue::Text("Ada"), &context)?;
163    assert_eq!(valid, ValidationOutcome::Valid);
164
165    let invalid = validator.validate(ValidationValue::Text("   "), &context)?;
166    let ValidationOutcome::Invalid(violations) = invalid else {
167        panic!("blank text must be invalid");
168    };
169    assert_eq!(violations.len(), 1);
170    assert_eq!(violations[0].code(), ViolationCode::new("text.blank"));
171
172    assert_dependency_specs_come_from_signature()?;
173    assert_parameters_are_consumed_once()?;
174
175    #[cfg(feature = "inventory")]
176    {
177        let global = ValidatorRegistry::try_global()?;
178        assert!(global.get("text.non_blank.global").is_some());
179    }
180
181    Ok(())
182}
Source

pub const fn try_new(value: &'static str) -> Result<Self, ViolationCodeError>

Validates and creates a code.

§Parameters
  • value: A static string containing the complete protocol value.
§Returns

The validated violation code when value follows the protocol.

§Errors

Returns ViolationCodeError::Empty for an empty string, ViolationCodeError::EmptySegment for an empty dot-separated segment, or ViolationCodeError::InvalidSegment for a segment with invalid characters or an invalid first character.

Source

pub const fn as_str(self) -> &'static str

Returns the complete stable code.

Trait Implementations§

Source§

impl Clone for ViolationCode

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for ViolationCode

Source§

impl Debug for ViolationCode

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult

Formats the validated, program-declared code.

Source§

impl Display for ViolationCode

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult

Formats the validated, program-declared code.

Source§

impl Eq for ViolationCode

Source§

impl Hash for ViolationCode

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for ViolationCode

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for ViolationCode

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for ViolationCode

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for ViolationCode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.