mod int_validators;
mod list_validators;
mod string_validators;
use crate::Value;
pub use int_validators::{IntEqual, IntGreaterThan, IntLessThan, IntNonZero, IntRange};
pub use list_validators::{ListMaxLength, ListMinLength};
pub use string_validators::{Email, StringMaxLength, StringMinLength, MAC};
pub trait InputValueValidator
where
Self: Sync + Send,
{
fn is_valid(&self, value: &Value) -> Result<(), String>;
}
pub trait InputValueValidatorExt: InputValueValidator + Sized {
fn and<R: InputValueValidator>(self, other: R) -> And<Self, R> {
And(self, other)
}
fn or<R: InputValueValidator>(self, other: R) -> Or<Self, R> {
Or(self, other)
}
fn map_err<F: Fn(String) -> String>(self, f: F) -> MapErr<Self, F> {
MapErr(self, f)
}
}
impl<I: InputValueValidator> InputValueValidatorExt for I {}
pub struct And<A, B>(A, B);
impl<A, B> InputValueValidator for And<A, B>
where
A: InputValueValidator,
B: InputValueValidator,
{
fn is_valid(&self, value: &Value) -> Result<(), String> {
self.0.is_valid(value)?;
self.1.is_valid(value)
}
}
pub struct Or<A, B>(A, B);
impl<A, B> InputValueValidator for Or<A, B>
where
A: InputValueValidator,
B: InputValueValidator,
{
fn is_valid(&self, value: &Value) -> Result<(), String> {
if self.0.is_valid(value).is_err() {
self.1.is_valid(value)
} else {
Ok(())
}
}
}
pub struct MapErr<I, F>(I, F);
impl<I, F> InputValueValidator for MapErr<I, F>
where
I: InputValueValidator,
F: Fn(String) -> String + Send + Sync,
{
fn is_valid(&self, value: &Value) -> Result<(), String> {
self.0.is_valid(value).map_err(&self.1)
}
}