use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
use std::hash::{BuildHasher, Hash};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
};
use std::rc::Rc;
use std::sync::Arc;
use crate::context::ValidationContext;
use crate::error::{AsyncValidationError, FieldIssue, HostError};
use crate::schema::ModelSchema;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Server;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Client;
pub trait Normalize {
fn normalize(&mut self);
}
pub trait Validate {
fn validate(&self) -> Result<(), Vec<FieldIssue>> {
self.validate_with(&ValidationContext::default())
}
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
}
pub trait ScopedValidate<Scope> {
fn validate_scoped(&self) -> Result<(), Vec<FieldIssue>> {
self.validate_scoped_with(&ValidationContext::default())
}
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AsyncCheckResult {
Issues(Vec<FieldIssue>),
Host(HostError),
}
pub trait IntoSyncError {
fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue>;
}
impl IntoSyncError for &'static str {
fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue> {
vec![FieldIssue::new(field, code, self)]
}
}
impl IntoSyncError for String {
fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue> {
vec![FieldIssue::new(field, code, self)]
}
}
impl IntoSyncError for (&'static str, &'static str) {
fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
vec![FieldIssue::new(field, self.0, self.1)]
}
}
impl IntoSyncError for (String, String) {
fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
vec![FieldIssue::new(field, self.0, self.1)]
}
}
impl IntoSyncError for FieldIssue {
fn into_sync_issues(mut self, field: &str, _code: &str) -> Vec<FieldIssue> {
if self.field.is_empty() {
self.field = field.to_string();
}
vec![self]
}
}
impl IntoSyncError for Vec<FieldIssue> {
fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
self.into_iter()
.map(|mut v| {
if v.field.is_empty() {
v.field = field.to_string();
}
v
})
.collect()
}
}
pub trait IntoAsyncError {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult;
}
impl IntoAsyncError for &'static str {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
}
}
impl IntoAsyncError for String {
fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
}
}
impl IntoAsyncError for (&'static str, &'static str) {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
}
}
impl IntoAsyncError for (String, String) {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
}
}
impl IntoAsyncError for FieldIssue {
fn into_async_error_result(mut self, field: &str, _code: &str) -> AsyncCheckResult {
if self.field.is_empty() {
self.field = field.to_string();
}
AsyncCheckResult::Issues(vec![self])
}
}
impl IntoAsyncError for Vec<FieldIssue> {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(
self.into_iter()
.map(|mut v| {
if v.field.is_empty() {
v.field = field.to_string();
}
v
})
.collect(),
)
}
}
impl IntoAsyncError for HostError {
fn into_async_error_result(self, _field: &str, _code: &str) -> AsyncCheckResult {
AsyncCheckResult::Host(self)
}
}
impl IntoAsyncError for AsyncValidationError {
fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
match self {
Self::Issues(vs) => vs.into_async_error_result(field, ""),
Self::Host(err) => AsyncCheckResult::Host(err),
}
}
}
pub trait AsyncCheckOutcome {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult;
}
impl AsyncCheckOutcome for bool {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
AsyncCheckResult::Issues(CheckOutcome::into_issues(self, field, code, reason))
}
}
impl<E: IntoAsyncError> AsyncCheckOutcome for Result<(), E> {
fn into_async_result(self, field: &str, code: &str, _reason: &str) -> AsyncCheckResult {
match self {
Ok(()) => AsyncCheckResult::Issues(Vec::new()),
Err(err) => err.into_async_error_result(field, code),
}
}
}
impl<E: IntoAsyncError> AsyncCheckOutcome for Result<bool, E> {
fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
match self {
Ok(true) => AsyncCheckResult::Issues(Vec::new()),
Ok(false) => AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, reason)]),
Err(err) => err.into_async_error_result(field, code),
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
pub trait AsyncValidate<R: ?Sized + Sync, Scope = ()> {
async fn validate_async(&self, resolver: &R) -> Result<(), AsyncValidationError> {
self.validate_async_with(&ValidationContext::default(), resolver)
.await
}
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError>;
}
pub trait DescribeModel {
fn model_schema() -> ModelSchema;
}
pub trait CheckOutcome {
fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
}
impl CheckOutcome for bool {
fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
if self {
Vec::new()
} else {
vec![FieldIssue::new(field, code, reason)]
}
}
}
impl<E: IntoSyncError> CheckOutcome for Result<(), E> {
fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
match self {
Ok(()) => Vec::new(),
Err(err) => err.into_sync_issues(field, code),
}
}
}
impl<E: IntoSyncError> CheckOutcome for Result<bool, E> {
fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
match self {
Ok(true) => Vec::new(),
Ok(false) => vec![FieldIssue::new(field, code, reason)],
Err(err) => err.into_sync_issues(field, code),
}
}
}
fn push_indexed_issues(issues: &mut Vec<FieldIssue>, index: usize, inner: Vec<FieldIssue>) {
for mut issue in inner {
if issue.field.is_empty() || issue.field == "body" {
issue.field = format!("[{index}]");
} else if issue.field.starts_with('[') {
issue.field = format!("[{index}]{}", issue.field);
} else {
issue.field = format!("[{index}].{}", issue.field);
}
issues.push(issue);
}
}
fn push_keyed_issues(
issues: &mut Vec<FieldIssue>,
key: &impl std::fmt::Display,
inner: Vec<FieldIssue>,
) {
for mut issue in inner {
if issue.field.is_empty() || issue.field == "body" {
issue.field = key.to_string();
} else if issue.field.starts_with('[') {
issue.field = format!("{key}{}", issue.field);
} else {
issue.field = format!("{key}.{}", issue.field);
}
issues.push(issue);
}
}
fn sort_issue_groups(groups: &mut [Vec<FieldIssue>]) {
groups.sort_by(|a, b| match (a.first(), b.first()) {
(Some(fa), Some(fb)) => fa
.field
.cmp(&fb.field)
.then_with(|| fa.code.cmp(&fb.code))
.then_with(|| fa.reason.cmp(&fb.reason)),
(None, Some(_)) => std::cmp::Ordering::Less,
(Some(_), None) => std::cmp::Ordering::Greater,
(None, None) => std::cmp::Ordering::Equal,
});
}
macro_rules! impl_noop_model_traits {
($($ty:ty),*) => {
$(
impl Normalize for $ty {
fn normalize(&mut self) {}
}
impl Validate for $ty {
fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
impl<S> ScopedValidate<S> for $ty {
fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S> AsyncValidate<R, S> for $ty {
async fn validate_async_with(
&self,
_ctx: &ValidationContext,
_resolver: &R,
) -> Result<(), AsyncValidationError> {
Ok(())
}
}
)*
};
}
impl_noop_model_traits!(
(),
String,
bool,
char,
i8,
i16,
i32,
i64,
i128,
isize,
u8,
u16,
u32,
u64,
u128,
usize,
f32,
f64,
IpAddr,
Ipv4Addr,
Ipv6Addr,
NonZeroI8,
NonZeroI16,
NonZeroI32,
NonZeroI64,
NonZeroI128,
NonZeroIsize,
NonZeroU8,
NonZeroU16,
NonZeroU32,
NonZeroU64,
NonZeroU128,
NonZeroUsize
);
impl Normalize for str {
fn normalize(&mut self) {}
}
impl Validate for str {
fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
impl<S> ScopedValidate<S> for str {
fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
Ok(())
}
}
impl<'a, T> Normalize for Cow<'a, T>
where
T: ?Sized + ToOwned,
T::Owned: Normalize,
{
fn normalize(&mut self) {
self.to_mut().normalize();
}
}
impl<'a, T> Validate for Cow<'a, T>
where
T: ?Sized + ToOwned + Validate,
{
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_with(ctx)
}
}
impl<'a, S, T> ScopedValidate<S> for Cow<'a, T>
where
T: ?Sized + ToOwned + ScopedValidate<S>,
{
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_scoped_with(ctx)
}
}
impl<T: Normalize + Clone> Normalize for Arc<T> {
fn normalize(&mut self) {
Arc::make_mut(self).normalize();
}
}
impl<T: Validate> Validate for Arc<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_with(ctx)
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Arc<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_scoped_with(ctx)
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync + Send> AsyncValidate<R, S> for Arc<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
(**self).validate_async_with(ctx, resolver).await
}
}
impl<T: Normalize + Clone> Normalize for Rc<T> {
fn normalize(&mut self) {
Rc::make_mut(self).normalize();
}
}
impl<T: Validate> Validate for Rc<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_with(ctx)
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Rc<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_scoped_with(ctx)
}
}
impl<T: Normalize, const N: usize> Normalize for [T; N] {
fn normalize(&mut self) {
for item in self {
item.normalize();
}
}
}
impl<T: Validate, const N: usize> Validate for [T; N] {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>, const N: usize> ScopedValidate<S> for [T; N] {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync, const N: usize> AsyncValidate<R, S>
for [T; N]
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize> Normalize for Option<T> {
fn normalize(&mut self) {
if let Some(value) = self {
value.normalize();
}
}
}
impl<T: Validate> Validate for Option<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
match self {
Some(value) => value.validate_with(ctx),
None => Ok(()),
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Option<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
match self {
Some(value) => value.validate_scoped_with(ctx),
None => Ok(()),
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Option<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
match self {
Some(value) => value.validate_async_with(ctx, resolver).await,
None => Ok(()),
}
}
}
impl<T: Normalize> Normalize for Box<T> {
fn normalize(&mut self) {
(**self).normalize();
}
}
impl<T: Validate> Validate for Box<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_with(ctx)
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Box<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
(**self).validate_scoped_with(ctx)
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Box<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
(**self).validate_async_with(ctx, resolver).await
}
}
impl<T: Normalize> Normalize for Vec<T> {
fn normalize(&mut self) {
for item in self {
item.normalize();
}
}
}
impl<T: Validate> Validate for Vec<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Vec<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Vec<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize> Normalize for VecDeque<T> {
fn normalize(&mut self) {
for item in self {
item.normalize();
}
}
}
impl<T: Validate> Validate for VecDeque<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for VecDeque<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for VecDeque<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize + Ord> Normalize for BTreeSet<T> {
fn normalize(&mut self) {
if self.is_empty() {
return;
}
let items = std::mem::take(self);
for mut item in items {
item.normalize();
self.insert(item);
}
}
}
impl<T: Validate> Validate for BTreeSet<T> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, T: ScopedValidate<S>> ScopedValidate<S> for BTreeSet<T> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
if let Err(inner) = item.validate_scoped_with(ctx) {
push_indexed_issues(&mut issues, index, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for BTreeSet<T> {
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (index, item) in self.iter().enumerate() {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_indexed_issues(&mut issues, index, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<T: Normalize + Eq + Hash, H: BuildHasher + Default> Normalize for HashSet<T, H> {
fn normalize(&mut self) {
if self.is_empty() {
return;
}
let items = std::mem::take(self);
for mut item in items {
item.normalize();
self.insert(item);
}
}
}
impl<T: Validate, H: BuildHasher> Validate for HashSet<T, H> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut groups = Vec::new();
for item in self {
if let Err(inner) = item.validate_with(ctx) {
groups.push(inner);
}
}
if groups.is_empty() {
return Ok(());
}
sort_issue_groups(&mut groups);
let mut issues = Vec::new();
for (index, inner) in groups.into_iter().enumerate() {
push_indexed_issues(&mut issues, index, inner);
}
Err(issues)
}
}
impl<S, T: ScopedValidate<S>, H: BuildHasher> ScopedValidate<S> for HashSet<T, H> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut groups = Vec::new();
for item in self {
if let Err(inner) = item.validate_scoped_with(ctx) {
groups.push(inner);
}
}
if groups.is_empty() {
return Ok(());
}
sort_issue_groups(&mut groups);
let mut issues = Vec::new();
for (index, inner) in groups.into_iter().enumerate() {
push_indexed_issues(&mut issues, index, inner);
}
Err(issues)
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync, H: BuildHasher + Sync> AsyncValidate<R, S>
for HashSet<T, H>
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut groups = Vec::new();
for item in self {
match item.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => groups.push(inner),
}
}
if groups.is_empty() {
return Ok(());
}
sort_issue_groups(&mut groups);
let mut issues = Vec::new();
for (index, inner) in groups.into_iter().enumerate() {
push_indexed_issues(&mut issues, index, inner);
}
Err(AsyncValidationError::Issues(issues))
}
}
impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
fn normalize(&mut self) {
for value in self.values_mut() {
value.normalize();
}
}
}
impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
impl<S, K: std::fmt::Display, V: ScopedValidate<S>> ScopedValidate<S> for BTreeMap<K, V> {
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut issues = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_scoped_with(ctx) {
push_keyed_issues(&mut issues, key, inner);
}
}
if issues.is_empty() {
Ok(())
} else {
Err(issues)
}
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<R: ?Sized + Sync, S, K: std::fmt::Display + Sync, V: AsyncValidate<R, S> + Sync>
AsyncValidate<R, S> for BTreeMap<K, V>
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut issues = Vec::new();
for (key, value) in self {
match value.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => {
push_keyed_issues(&mut issues, key, inner);
}
}
}
if issues.is_empty() {
Ok(())
} else {
Err(AsyncValidationError::Issues(issues))
}
}
}
impl<K: Eq + Hash, V: Normalize, H: BuildHasher> Normalize for HashMap<K, V, H> {
fn normalize(&mut self) {
for value in self.values_mut() {
value.normalize();
}
}
}
impl<K: std::fmt::Display + Eq + Hash, V: Validate, H: BuildHasher> Validate for HashMap<K, V, H> {
fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut keyed = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_with(ctx) {
keyed.push((key.to_string(), inner));
}
}
if keyed.is_empty() {
return Ok(());
}
keyed.sort_by(|a, b| a.0.cmp(&b.0));
let mut issues = Vec::new();
for (key_str, inner) in keyed {
push_keyed_issues(&mut issues, &key_str, inner);
}
Err(issues)
}
}
impl<S, K: std::fmt::Display + Eq + Hash, V: ScopedValidate<S>, H: BuildHasher> ScopedValidate<S>
for HashMap<K, V, H>
{
fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
let mut keyed = Vec::new();
for (key, value) in self {
if let Err(inner) = value.validate_scoped_with(ctx) {
keyed.push((key.to_string(), inner));
}
}
if keyed.is_empty() {
return Ok(());
}
keyed.sort_by(|a, b| a.0.cmp(&b.0));
let mut issues = Vec::new();
for (key_str, inner) in keyed {
push_keyed_issues(&mut issues, &key_str, inner);
}
Err(issues)
}
}
#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
impl<
R: ?Sized + Sync,
S,
K: std::fmt::Display + Eq + Hash + Sync,
V: AsyncValidate<R, S> + Sync,
H: BuildHasher + Sync,
> AsyncValidate<R, S> for HashMap<K, V, H>
{
async fn validate_async_with(
&self,
ctx: &ValidationContext,
resolver: &R,
) -> Result<(), AsyncValidationError> {
let mut keyed = Vec::new();
for (key, value) in self {
match value.validate_async_with(ctx, resolver).await {
Ok(()) => {}
Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
Err(AsyncValidationError::Issues(inner)) => keyed.push((key.to_string(), inner)),
}
}
if keyed.is_empty() {
return Ok(());
}
keyed.sort_by(|a, b| a.0.cmp(&b.0));
let mut issues = Vec::new();
for (key_str, inner) in keyed {
push_keyed_issues(&mut issues, &key_str, inner);
}
Err(AsyncValidationError::Issues(issues))
}
}