1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
3use std::hash::{BuildHasher, Hash};
4use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5use std::num::{
6 NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
7 NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize,
8};
9use std::rc::Rc;
10use std::sync::Arc;
11
12use crate::context::ValidationContext;
13use crate::error::{AsyncValidationError, FieldIssue, HostError};
14use crate::schema::ModelSchema;
15
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
18pub struct Server;
19
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
22pub struct Client;
23
24pub trait Normalize {
26 fn normalize(&mut self);
27}
28
29pub trait Validate {
31 fn validate(&self) -> Result<(), Vec<FieldIssue>> {
32 self.validate_with(&ValidationContext::default())
33 }
34
35 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
36}
37
38pub trait ScopedValidate<Scope> {
40 fn validate_scoped(&self) -> Result<(), Vec<FieldIssue>> {
41 self.validate_scoped_with(&ValidationContext::default())
42 }
43
44 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>>;
45}
46
47#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum AsyncCheckResult {
50 Issues(Vec<FieldIssue>),
51 Host(HostError),
52}
53
54pub trait IntoSyncError {
56 fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue>;
57}
58
59impl IntoSyncError for &'static str {
60 fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue> {
61 vec![FieldIssue::new(field, code, self)]
62 }
63}
64
65impl IntoSyncError for String {
66 fn into_sync_issues(self, field: &str, code: &str) -> Vec<FieldIssue> {
67 vec![FieldIssue::new(field, code, self)]
68 }
69}
70
71impl IntoSyncError for (&'static str, &'static str) {
72 fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
73 vec![FieldIssue::new(field, self.0, self.1)]
74 }
75}
76
77impl IntoSyncError for (String, String) {
78 fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
79 vec![FieldIssue::new(field, self.0, self.1)]
80 }
81}
82
83impl IntoSyncError for FieldIssue {
84 fn into_sync_issues(mut self, field: &str, _code: &str) -> Vec<FieldIssue> {
85 if self.field.is_empty() {
86 self.field = field.to_string();
87 }
88 vec![self]
89 }
90}
91
92impl IntoSyncError for Vec<FieldIssue> {
93 fn into_sync_issues(self, field: &str, _code: &str) -> Vec<FieldIssue> {
94 self.into_iter()
95 .map(|mut v| {
96 if v.field.is_empty() {
97 v.field = field.to_string();
98 }
99 v
100 })
101 .collect()
102 }
103}
104
105pub trait IntoAsyncError {
107 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult;
108}
109
110impl IntoAsyncError for &'static str {
111 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
112 AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
113 }
114}
115
116impl IntoAsyncError for String {
117 fn into_async_error_result(self, field: &str, code: &str) -> AsyncCheckResult {
118 AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, self)])
119 }
120}
121
122impl IntoAsyncError for (&'static str, &'static str) {
123 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
124 AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
125 }
126}
127
128impl IntoAsyncError for (String, String) {
129 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
130 AsyncCheckResult::Issues(vec![FieldIssue::new(field, self.0, self.1)])
131 }
132}
133
134impl IntoAsyncError for FieldIssue {
135 fn into_async_error_result(mut self, field: &str, _code: &str) -> AsyncCheckResult {
136 if self.field.is_empty() {
137 self.field = field.to_string();
138 }
139 AsyncCheckResult::Issues(vec![self])
140 }
141}
142
143impl IntoAsyncError for Vec<FieldIssue> {
144 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
145 AsyncCheckResult::Issues(
146 self.into_iter()
147 .map(|mut v| {
148 if v.field.is_empty() {
149 v.field = field.to_string();
150 }
151 v
152 })
153 .collect(),
154 )
155 }
156}
157
158impl IntoAsyncError for HostError {
159 fn into_async_error_result(self, _field: &str, _code: &str) -> AsyncCheckResult {
160 AsyncCheckResult::Host(self)
161 }
162}
163
164impl IntoAsyncError for AsyncValidationError {
165 fn into_async_error_result(self, field: &str, _code: &str) -> AsyncCheckResult {
166 match self {
167 Self::Issues(vs) => vs.into_async_error_result(field, ""),
168 Self::Host(err) => AsyncCheckResult::Host(err),
169 }
170 }
171}
172
173pub trait AsyncCheckOutcome {
175 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult;
176}
177
178impl AsyncCheckOutcome for bool {
179 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
180 AsyncCheckResult::Issues(CheckOutcome::into_issues(self, field, code, reason))
181 }
182}
183
184impl<E: IntoAsyncError> AsyncCheckOutcome for Result<(), E> {
185 fn into_async_result(self, field: &str, code: &str, _reason: &str) -> AsyncCheckResult {
186 match self {
187 Ok(()) => AsyncCheckResult::Issues(Vec::new()),
188 Err(err) => err.into_async_error_result(field, code),
189 }
190 }
191}
192
193impl<E: IntoAsyncError> AsyncCheckOutcome for Result<bool, E> {
194 fn into_async_result(self, field: &str, code: &str, reason: &str) -> AsyncCheckResult {
195 match self {
196 Ok(true) => AsyncCheckResult::Issues(Vec::new()),
197 Ok(false) => AsyncCheckResult::Issues(vec![FieldIssue::new(field, code, reason)]),
198 Err(err) => err.into_async_error_result(field, code),
199 }
200 }
201}
202
203#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
205#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
206pub trait AsyncValidate<R: ?Sized + Sync, Scope = ()> {
207 async fn validate_async(&self, resolver: &R) -> Result<(), AsyncValidationError> {
208 self.validate_async_with(&ValidationContext::default(), resolver)
209 .await
210 }
211
212 async fn validate_async_with(
213 &self,
214 ctx: &ValidationContext,
215 resolver: &R,
216 ) -> Result<(), AsyncValidationError>;
217}
218
219pub trait DescribeModel {
221 fn model_schema() -> ModelSchema;
222}
223
224pub trait CheckOutcome {
226 fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue>;
227}
228
229impl CheckOutcome for bool {
230 fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
231 if self {
232 Vec::new()
233 } else {
234 vec![FieldIssue::new(field, code, reason)]
235 }
236 }
237}
238
239impl<E: IntoSyncError> CheckOutcome for Result<(), E> {
240 fn into_issues(self, field: &str, code: &str, _reason: &str) -> Vec<FieldIssue> {
241 match self {
242 Ok(()) => Vec::new(),
243 Err(err) => err.into_sync_issues(field, code),
244 }
245 }
246}
247
248impl<E: IntoSyncError> CheckOutcome for Result<bool, E> {
249 fn into_issues(self, field: &str, code: &str, reason: &str) -> Vec<FieldIssue> {
250 match self {
251 Ok(true) => Vec::new(),
252 Ok(false) => vec![FieldIssue::new(field, code, reason)],
253 Err(err) => err.into_sync_issues(field, code),
254 }
255 }
256}
257
258fn push_indexed_issues(issues: &mut Vec<FieldIssue>, index: usize, inner: Vec<FieldIssue>) {
259 for mut issue in inner {
260 if issue.field.is_empty() || issue.field == "body" {
261 issue.field = format!("[{index}]");
262 } else if issue.field.starts_with('[') {
263 issue.field = format!("[{index}]{}", issue.field);
264 } else {
265 issue.field = format!("[{index}].{}", issue.field);
266 }
267 issues.push(issue);
268 }
269}
270
271fn push_keyed_issues(
272 issues: &mut Vec<FieldIssue>,
273 key: &impl std::fmt::Display,
274 inner: Vec<FieldIssue>,
275) {
276 for mut issue in inner {
277 if issue.field.is_empty() || issue.field == "body" {
278 issue.field = key.to_string();
279 } else if issue.field.starts_with('[') {
280 issue.field = format!("{key}{}", issue.field);
281 } else {
282 issue.field = format!("{key}.{}", issue.field);
283 }
284 issues.push(issue);
285 }
286}
287
288fn sort_issue_groups(groups: &mut [Vec<FieldIssue>]) {
289 groups.sort_by(|a, b| match (a.first(), b.first()) {
290 (Some(fa), Some(fb)) => fa
291 .field
292 .cmp(&fb.field)
293 .then_with(|| fa.code.cmp(&fb.code))
294 .then_with(|| fa.reason.cmp(&fb.reason)),
295 (None, Some(_)) => std::cmp::Ordering::Less,
296 (Some(_), None) => std::cmp::Ordering::Greater,
297 (None, None) => std::cmp::Ordering::Equal,
298 });
299}
300
301macro_rules! impl_noop_model_traits {
302 ($($ty:ty),*) => {
303 $(
304 impl Normalize for $ty {
305 fn normalize(&mut self) {}
306 }
307
308 impl Validate for $ty {
309 fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
310 Ok(())
311 }
312 }
313
314 impl<S> ScopedValidate<S> for $ty {
315 fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
316 Ok(())
317 }
318 }
319
320 #[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
321 #[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
322 impl<R: ?Sized + Sync, S> AsyncValidate<R, S> for $ty {
323 async fn validate_async_with(
324 &self,
325 _ctx: &ValidationContext,
326 _resolver: &R,
327 ) -> Result<(), AsyncValidationError> {
328 Ok(())
329 }
330 }
331 )*
332 };
333}
334
335impl_noop_model_traits!(
336 (),
337 String,
338 bool,
339 char,
340 i8,
341 i16,
342 i32,
343 i64,
344 i128,
345 isize,
346 u8,
347 u16,
348 u32,
349 u64,
350 u128,
351 usize,
352 f32,
353 f64,
354 IpAddr,
355 Ipv4Addr,
356 Ipv6Addr,
357 NonZeroI8,
358 NonZeroI16,
359 NonZeroI32,
360 NonZeroI64,
361 NonZeroI128,
362 NonZeroIsize,
363 NonZeroU8,
364 NonZeroU16,
365 NonZeroU32,
366 NonZeroU64,
367 NonZeroU128,
368 NonZeroUsize
369);
370
371impl Normalize for str {
372 fn normalize(&mut self) {}
373}
374
375impl Validate for str {
376 fn validate_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
377 Ok(())
378 }
379}
380
381impl<S> ScopedValidate<S> for str {
382 fn validate_scoped_with(&self, _ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
383 Ok(())
384 }
385}
386
387impl<'a, T> Normalize for Cow<'a, T>
388where
389 T: ?Sized + ToOwned,
390 T::Owned: Normalize,
391{
392 fn normalize(&mut self) {
393 self.to_mut().normalize();
394 }
395}
396
397impl<'a, T> Validate for Cow<'a, T>
398where
399 T: ?Sized + ToOwned + Validate,
400{
401 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
402 (**self).validate_with(ctx)
403 }
404}
405
406impl<'a, S, T> ScopedValidate<S> for Cow<'a, T>
407where
408 T: ?Sized + ToOwned + ScopedValidate<S>,
409{
410 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
411 (**self).validate_scoped_with(ctx)
412 }
413}
414
415impl<T: Normalize + Clone> Normalize for Arc<T> {
416 fn normalize(&mut self) {
417 Arc::make_mut(self).normalize();
418 }
419}
420
421impl<T: Validate> Validate for Arc<T> {
422 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
423 (**self).validate_with(ctx)
424 }
425}
426
427impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Arc<T> {
428 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
429 (**self).validate_scoped_with(ctx)
430 }
431}
432
433#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
434#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
435impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync + Send> AsyncValidate<R, S> for Arc<T> {
436 async fn validate_async_with(
437 &self,
438 ctx: &ValidationContext,
439 resolver: &R,
440 ) -> Result<(), AsyncValidationError> {
441 (**self).validate_async_with(ctx, resolver).await
442 }
443}
444
445impl<T: Normalize + Clone> Normalize for Rc<T> {
446 fn normalize(&mut self) {
447 Rc::make_mut(self).normalize();
448 }
449}
450
451impl<T: Validate> Validate for Rc<T> {
452 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
453 (**self).validate_with(ctx)
454 }
455}
456
457impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Rc<T> {
458 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
459 (**self).validate_scoped_with(ctx)
460 }
461}
462
463impl<T: Normalize, const N: usize> Normalize for [T; N] {
464 fn normalize(&mut self) {
465 for item in self {
466 item.normalize();
467 }
468 }
469}
470
471impl<T: Validate, const N: usize> Validate for [T; N] {
472 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
473 let mut issues = Vec::new();
474 for (index, item) in self.iter().enumerate() {
475 if let Err(inner) = item.validate_with(ctx) {
476 push_indexed_issues(&mut issues, index, inner);
477 }
478 }
479 if issues.is_empty() {
480 Ok(())
481 } else {
482 Err(issues)
483 }
484 }
485}
486
487impl<S, T: ScopedValidate<S>, const N: usize> ScopedValidate<S> for [T; N] {
488 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
489 let mut issues = Vec::new();
490 for (index, item) in self.iter().enumerate() {
491 if let Err(inner) = item.validate_scoped_with(ctx) {
492 push_indexed_issues(&mut issues, index, inner);
493 }
494 }
495 if issues.is_empty() {
496 Ok(())
497 } else {
498 Err(issues)
499 }
500 }
501}
502
503#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
504#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
505impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync, const N: usize> AsyncValidate<R, S>
506 for [T; N]
507{
508 async fn validate_async_with(
509 &self,
510 ctx: &ValidationContext,
511 resolver: &R,
512 ) -> Result<(), AsyncValidationError> {
513 let mut issues = Vec::new();
514 for (index, item) in self.iter().enumerate() {
515 match item.validate_async_with(ctx, resolver).await {
516 Ok(()) => {}
517 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
518 Err(AsyncValidationError::Issues(inner)) => {
519 push_indexed_issues(&mut issues, index, inner);
520 }
521 }
522 }
523 if issues.is_empty() {
524 Ok(())
525 } else {
526 Err(AsyncValidationError::Issues(issues))
527 }
528 }
529}
530
531impl<T: Normalize> Normalize for Option<T> {
532 fn normalize(&mut self) {
533 if let Some(value) = self {
534 value.normalize();
535 }
536 }
537}
538
539impl<T: Validate> Validate for Option<T> {
540 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
541 match self {
542 Some(value) => value.validate_with(ctx),
543 None => Ok(()),
544 }
545 }
546}
547
548impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Option<T> {
549 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
550 match self {
551 Some(value) => value.validate_scoped_with(ctx),
552 None => Ok(()),
553 }
554 }
555}
556
557#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
558#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
559impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Option<T> {
560 async fn validate_async_with(
561 &self,
562 ctx: &ValidationContext,
563 resolver: &R,
564 ) -> Result<(), AsyncValidationError> {
565 match self {
566 Some(value) => value.validate_async_with(ctx, resolver).await,
567 None => Ok(()),
568 }
569 }
570}
571
572impl<T: Normalize> Normalize for Box<T> {
573 fn normalize(&mut self) {
574 (**self).normalize();
575 }
576}
577
578impl<T: Validate> Validate for Box<T> {
579 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
580 (**self).validate_with(ctx)
581 }
582}
583
584impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Box<T> {
585 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
586 (**self).validate_scoped_with(ctx)
587 }
588}
589
590#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
591#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
592impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Box<T> {
593 async fn validate_async_with(
594 &self,
595 ctx: &ValidationContext,
596 resolver: &R,
597 ) -> Result<(), AsyncValidationError> {
598 (**self).validate_async_with(ctx, resolver).await
599 }
600}
601
602impl<T: Normalize> Normalize for Vec<T> {
603 fn normalize(&mut self) {
604 for item in self {
605 item.normalize();
606 }
607 }
608}
609
610impl<T: Validate> Validate for Vec<T> {
611 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
612 let mut issues = Vec::new();
613 for (index, item) in self.iter().enumerate() {
614 if let Err(inner) = item.validate_with(ctx) {
615 push_indexed_issues(&mut issues, index, inner);
616 }
617 }
618 if issues.is_empty() {
619 Ok(())
620 } else {
621 Err(issues)
622 }
623 }
624}
625
626impl<S, T: ScopedValidate<S>> ScopedValidate<S> for Vec<T> {
627 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
628 let mut issues = Vec::new();
629 for (index, item) in self.iter().enumerate() {
630 if let Err(inner) = item.validate_scoped_with(ctx) {
631 push_indexed_issues(&mut issues, index, inner);
632 }
633 }
634 if issues.is_empty() {
635 Ok(())
636 } else {
637 Err(issues)
638 }
639 }
640}
641
642#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
643#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
644impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for Vec<T> {
645 async fn validate_async_with(
646 &self,
647 ctx: &ValidationContext,
648 resolver: &R,
649 ) -> Result<(), AsyncValidationError> {
650 let mut issues = Vec::new();
651 for (index, item) in self.iter().enumerate() {
652 match item.validate_async_with(ctx, resolver).await {
653 Ok(()) => {}
654 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
655 Err(AsyncValidationError::Issues(inner)) => {
656 push_indexed_issues(&mut issues, index, inner);
657 }
658 }
659 }
660 if issues.is_empty() {
661 Ok(())
662 } else {
663 Err(AsyncValidationError::Issues(issues))
664 }
665 }
666}
667
668impl<T: Normalize> Normalize for VecDeque<T> {
669 fn normalize(&mut self) {
670 for item in self {
671 item.normalize();
672 }
673 }
674}
675
676impl<T: Validate> Validate for VecDeque<T> {
677 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
678 let mut issues = Vec::new();
679 for (index, item) in self.iter().enumerate() {
680 if let Err(inner) = item.validate_with(ctx) {
681 push_indexed_issues(&mut issues, index, inner);
682 }
683 }
684 if issues.is_empty() {
685 Ok(())
686 } else {
687 Err(issues)
688 }
689 }
690}
691
692impl<S, T: ScopedValidate<S>> ScopedValidate<S> for VecDeque<T> {
693 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
694 let mut issues = Vec::new();
695 for (index, item) in self.iter().enumerate() {
696 if let Err(inner) = item.validate_scoped_with(ctx) {
697 push_indexed_issues(&mut issues, index, inner);
698 }
699 }
700 if issues.is_empty() {
701 Ok(())
702 } else {
703 Err(issues)
704 }
705 }
706}
707
708#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
709#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
710impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for VecDeque<T> {
711 async fn validate_async_with(
712 &self,
713 ctx: &ValidationContext,
714 resolver: &R,
715 ) -> Result<(), AsyncValidationError> {
716 let mut issues = Vec::new();
717 for (index, item) in self.iter().enumerate() {
718 match item.validate_async_with(ctx, resolver).await {
719 Ok(()) => {}
720 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
721 Err(AsyncValidationError::Issues(inner)) => {
722 push_indexed_issues(&mut issues, index, inner);
723 }
724 }
725 }
726 if issues.is_empty() {
727 Ok(())
728 } else {
729 Err(AsyncValidationError::Issues(issues))
730 }
731 }
732}
733
734impl<T: Normalize + Ord> Normalize for BTreeSet<T> {
735 fn normalize(&mut self) {
736 if self.is_empty() {
737 return;
738 }
739 let items = std::mem::take(self);
740 for mut item in items {
741 item.normalize();
742 self.insert(item);
743 }
744 }
745}
746
747impl<T: Validate> Validate for BTreeSet<T> {
748 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
749 let mut issues = Vec::new();
750 for (index, item) in self.iter().enumerate() {
751 if let Err(inner) = item.validate_with(ctx) {
752 push_indexed_issues(&mut issues, index, inner);
753 }
754 }
755 if issues.is_empty() {
756 Ok(())
757 } else {
758 Err(issues)
759 }
760 }
761}
762
763impl<S, T: ScopedValidate<S>> ScopedValidate<S> for BTreeSet<T> {
764 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
765 let mut issues = Vec::new();
766 for (index, item) in self.iter().enumerate() {
767 if let Err(inner) = item.validate_scoped_with(ctx) {
768 push_indexed_issues(&mut issues, index, inner);
769 }
770 }
771 if issues.is_empty() {
772 Ok(())
773 } else {
774 Err(issues)
775 }
776 }
777}
778
779#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
780#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
781impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync> AsyncValidate<R, S> for BTreeSet<T> {
782 async fn validate_async_with(
783 &self,
784 ctx: &ValidationContext,
785 resolver: &R,
786 ) -> Result<(), AsyncValidationError> {
787 let mut issues = Vec::new();
788 for (index, item) in self.iter().enumerate() {
789 match item.validate_async_with(ctx, resolver).await {
790 Ok(()) => {}
791 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
792 Err(AsyncValidationError::Issues(inner)) => {
793 push_indexed_issues(&mut issues, index, inner);
794 }
795 }
796 }
797 if issues.is_empty() {
798 Ok(())
799 } else {
800 Err(AsyncValidationError::Issues(issues))
801 }
802 }
803}
804
805impl<T: Normalize + Eq + Hash, H: BuildHasher + Default> Normalize for HashSet<T, H> {
806 fn normalize(&mut self) {
807 if self.is_empty() {
808 return;
809 }
810 let items = std::mem::take(self);
811 for mut item in items {
812 item.normalize();
813 self.insert(item);
814 }
815 }
816}
817
818impl<T: Validate, H: BuildHasher> Validate for HashSet<T, H> {
819 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
820 let mut groups = Vec::new();
821 for item in self {
822 if let Err(inner) = item.validate_with(ctx) {
823 groups.push(inner);
824 }
825 }
826 if groups.is_empty() {
827 return Ok(());
828 }
829 sort_issue_groups(&mut groups);
830 let mut issues = Vec::new();
831 for (index, inner) in groups.into_iter().enumerate() {
832 push_indexed_issues(&mut issues, index, inner);
833 }
834 Err(issues)
835 }
836}
837
838impl<S, T: ScopedValidate<S>, H: BuildHasher> ScopedValidate<S> for HashSet<T, H> {
839 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
840 let mut groups = Vec::new();
841 for item in self {
842 if let Err(inner) = item.validate_scoped_with(ctx) {
843 groups.push(inner);
844 }
845 }
846 if groups.is_empty() {
847 return Ok(());
848 }
849 sort_issue_groups(&mut groups);
850 let mut issues = Vec::new();
851 for (index, inner) in groups.into_iter().enumerate() {
852 push_indexed_issues(&mut issues, index, inner);
853 }
854 Err(issues)
855 }
856}
857
858#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
859#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
860impl<R: ?Sized + Sync, S, T: AsyncValidate<R, S> + Sync, H: BuildHasher + Sync> AsyncValidate<R, S>
861 for HashSet<T, H>
862{
863 async fn validate_async_with(
864 &self,
865 ctx: &ValidationContext,
866 resolver: &R,
867 ) -> Result<(), AsyncValidationError> {
868 let mut groups = Vec::new();
869 for item in self {
870 match item.validate_async_with(ctx, resolver).await {
871 Ok(()) => {}
872 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
873 Err(AsyncValidationError::Issues(inner)) => groups.push(inner),
874 }
875 }
876 if groups.is_empty() {
877 return Ok(());
878 }
879 sort_issue_groups(&mut groups);
880 let mut issues = Vec::new();
881 for (index, inner) in groups.into_iter().enumerate() {
882 push_indexed_issues(&mut issues, index, inner);
883 }
884 Err(AsyncValidationError::Issues(issues))
885 }
886}
887
888impl<K, V: Normalize> Normalize for BTreeMap<K, V> {
889 fn normalize(&mut self) {
890 for value in self.values_mut() {
891 value.normalize();
892 }
893 }
894}
895
896impl<K: std::fmt::Display, V: Validate> Validate for BTreeMap<K, V> {
897 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
898 let mut issues = Vec::new();
899 for (key, value) in self {
900 if let Err(inner) = value.validate_with(ctx) {
901 push_keyed_issues(&mut issues, key, inner);
902 }
903 }
904 if issues.is_empty() {
905 Ok(())
906 } else {
907 Err(issues)
908 }
909 }
910}
911
912impl<S, K: std::fmt::Display, V: ScopedValidate<S>> ScopedValidate<S> for BTreeMap<K, V> {
913 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
914 let mut issues = Vec::new();
915 for (key, value) in self {
916 if let Err(inner) = value.validate_scoped_with(ctx) {
917 push_keyed_issues(&mut issues, key, inner);
918 }
919 }
920 if issues.is_empty() {
921 Ok(())
922 } else {
923 Err(issues)
924 }
925 }
926}
927
928#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
929#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
930impl<R: ?Sized + Sync, S, K: std::fmt::Display + Sync, V: AsyncValidate<R, S> + Sync>
931 AsyncValidate<R, S> for BTreeMap<K, V>
932{
933 async fn validate_async_with(
934 &self,
935 ctx: &ValidationContext,
936 resolver: &R,
937 ) -> Result<(), AsyncValidationError> {
938 let mut issues = Vec::new();
939 for (key, value) in self {
940 match value.validate_async_with(ctx, resolver).await {
941 Ok(()) => {}
942 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
943 Err(AsyncValidationError::Issues(inner)) => {
944 push_keyed_issues(&mut issues, key, inner);
945 }
946 }
947 }
948 if issues.is_empty() {
949 Ok(())
950 } else {
951 Err(AsyncValidationError::Issues(issues))
952 }
953 }
954}
955
956impl<K: Eq + Hash, V: Normalize, H: BuildHasher> Normalize for HashMap<K, V, H> {
957 fn normalize(&mut self) {
958 for value in self.values_mut() {
959 value.normalize();
960 }
961 }
962}
963
964impl<K: std::fmt::Display + Eq + Hash, V: Validate, H: BuildHasher> Validate for HashMap<K, V, H> {
965 fn validate_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
966 let mut keyed = Vec::new();
967 for (key, value) in self {
968 if let Err(inner) = value.validate_with(ctx) {
969 keyed.push((key.to_string(), inner));
970 }
971 }
972 if keyed.is_empty() {
973 return Ok(());
974 }
975 keyed.sort_by(|a, b| a.0.cmp(&b.0));
976 let mut issues = Vec::new();
977 for (key_str, inner) in keyed {
978 push_keyed_issues(&mut issues, &key_str, inner);
979 }
980 Err(issues)
981 }
982}
983
984impl<S, K: std::fmt::Display + Eq + Hash, V: ScopedValidate<S>, H: BuildHasher> ScopedValidate<S>
985 for HashMap<K, V, H>
986{
987 fn validate_scoped_with(&self, ctx: &ValidationContext) -> Result<(), Vec<FieldIssue>> {
988 let mut keyed = Vec::new();
989 for (key, value) in self {
990 if let Err(inner) = value.validate_scoped_with(ctx) {
991 keyed.push((key.to_string(), inner));
992 }
993 }
994 if keyed.is_empty() {
995 return Ok(());
996 }
997 keyed.sort_by(|a, b| a.0.cmp(&b.0));
998 let mut issues = Vec::new();
999 for (key_str, inner) in keyed {
1000 push_keyed_issues(&mut issues, &key_str, inner);
1001 }
1002 Err(issues)
1003 }
1004}
1005
1006#[cfg_attr(not(target_arch = "wasm32"), ::async_trait::async_trait)]
1007#[cfg_attr(target_arch = "wasm32", ::async_trait::async_trait(?Send))]
1008impl<
1009 R: ?Sized + Sync,
1010 S,
1011 K: std::fmt::Display + Eq + Hash + Sync,
1012 V: AsyncValidate<R, S> + Sync,
1013 H: BuildHasher + Sync,
1014 > AsyncValidate<R, S> for HashMap<K, V, H>
1015{
1016 async fn validate_async_with(
1017 &self,
1018 ctx: &ValidationContext,
1019 resolver: &R,
1020 ) -> Result<(), AsyncValidationError> {
1021 let mut keyed = Vec::new();
1022 for (key, value) in self {
1023 match value.validate_async_with(ctx, resolver).await {
1024 Ok(()) => {}
1025 Err(AsyncValidationError::Host(err)) => return Err(AsyncValidationError::Host(err)),
1026 Err(AsyncValidationError::Issues(inner)) => keyed.push((key.to_string(), inner)),
1027 }
1028 }
1029 if keyed.is_empty() {
1030 return Ok(());
1031 }
1032 keyed.sort_by(|a, b| a.0.cmp(&b.0));
1033 let mut issues = Vec::new();
1034 for (key_str, inner) in keyed {
1035 push_keyed_issues(&mut issues, &key_str, inner);
1036 }
1037 Err(AsyncValidationError::Issues(issues))
1038 }
1039}