validatable 0.1.0

Define validated data types once and share them between the frontend and backend of isomorphic Rust web applications, with plain, input, and form representations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! Composable, type-level validators used by [`Validated`] /
//! [`ValidatedValue`].
//!
//! A validator is a zero-sized type implementing [`Validator`]. Validators
//! are combined with the logical combinators [`And`], [`Or`], [`Not`], and
//! the ordering-emphasizing alias [`Chain`], and are attached to a value type
//! via [`Validated`].
//!
//! Validators may also *transform* the value (e.g. [`Trim`],
//! [`RemoveChars`]); when combining transforming validators, order matters.

use std::collections::BTreeSet;

use super::validated::Marker;
use super::*;

/// Validates (and possibly transforms) a value of type `T`.
///
/// Implement this trait to plug custom rules into
/// [`Validated`]:
///
/// ```
/// use validatable::*;
///
/// struct EmailValidator;
/// impl Validator<String> for EmailValidator {
///     fn validate(s: String) -> Result<String, Message> {
///         if s.contains('@') {
///             Ok(s)
///         } else {
///             Err(Message::Text("must contain @".to_string()))
///         }
///     }
/// }
///
/// type Email = Validated<String, Chain<Trim, LengthRange<3, 100>, EmailValidator>>;
///
/// assert!(Email::from_input(&" a@b ".to_string()).is_ok());
/// assert_eq!(
///     Email::from_input(&"nope".to_string()),
///     Err(Message::Text("must contain @".to_string()))
/// );
/// ```
pub trait Validator<T> {
    /// Returns the (possibly transformed) value on success, or the first
    /// validation error.
    fn validate(i: T) -> Result<T, Message>;
}

/// Always succeeds. The identity validator and the default for unused
/// combinator slots.
///
/// ```
/// # use validatable::*;
/// type Age = Validated<u8, True, UnsignedValueMax<130>>; // no input validation before parsing
/// ```
pub struct True;
/// Always fails with [`Message::Empty`]. The absorbing element for [`Or`].
///
/// ```
/// # use validatable::*;
/// type NoInput = Validated<String, False>; // rejects every input
/// ```
pub struct False;
/// Succeeds when both `A` and `B` succeed, applying `A` first and feeding
/// its output into `B`. Fails with the first error.
///
/// ```
/// # use validatable::*;
/// type Pin = Validated<String, And2<LengthRange<4, 4>, AllChars<CharClassAsciiDigit>>>;
/// ```
pub struct And2<A, B>(Marker<(A, B)>);
/// Succeeds when `A` or `B` succeeds.
///
/// `A` is tried first on a clone of the value; if it fails, `B` is tried on
/// the original value. When both fail, the error of `A` is reported.
///
/// ```
/// # use validatable::*;
/// type OptionalPhone = Validated<String, Or2<LengthMax<0>, AllChars<CharClassAsciiDigit>>>;
/// ```
pub struct Or2<A, B>(Marker<(A, B)>);
/// Succeeds (with the unmodified value) when `A` fails, and fails with
/// [`Message::ContentProblem`] when `A` succeeds.
///
/// ```
/// # use validatable::*;
/// type NotBlank = Validated<String, Not<AllChars<CharClassWhitespace>>>;
/// ```
///
/// `A` must be able to fail for `Not<A>` to accept anything. Transforming
/// validators such as [`Trim`], [`TrimChars`], and [`RemoveChars`] never
/// return `Err` (see their docs), so wrapping one in `Not` yields a
/// validator that rejects every input:
///
/// ```
/// # use validatable::*;
/// type NotTrim = Validated<String, Not<Trim>>;
/// assert_eq!(
///     NotTrim::from_input(&"abc".to_string()),
///     Err(Message::ContentProblem)
/// );
/// ```
pub struct Not<A>(Marker<A>);
/// Alias for [`And2`], emphasizing sequential application of transforming
/// validators.
///
/// ```
/// # use validatable::*;
/// type TrimmedName = Validated<String, Chain2<Trim, LengthMin<1>>>;
/// ```
pub type Chain2<A, B> = And2<A, B>;

/// Chains three validators, left to right. See [`Chain`].
pub type Chain3<A, B, C> = Chain2<Chain2<A, B>, C>;
/// Chains four validators, left to right. See [`Chain`].
pub type Chain4<A, B, C, D> = Chain2<Chain3<A, B, C>, D>;
/// Chains five validators, left to right. See [`Chain`].
pub type Chain5<A, B, C, D, E> = Chain2<Chain4<A, B, C, D>, E>;
/// Chains six validators, left to right. See [`Chain`].
pub type Chain6<A, B, C, D, E, F> = Chain2<Chain5<A, B, C, D, E>, F>;
/// Chains seven validators, left to right. See [`Chain`].
pub type Chain7<A, B, C, D, E, F, G> = Chain2<Chain6<A, B, C, D, E, F>, G>;
/// Chains eight validators, left to right. See [`Chain`].
pub type Chain8<A, B, C, D, E, F, G, H> = Chain2<Chain7<A, B, C, D, E, F, G>, H>;
/// Applies up to eight validators in sequence, left to right.
///
/// Unused slots default to [`True`]. Because validators may transform the
/// value (e.g. [`Trim`]), the order is significant:
/// `Chain<Trim, LengthMin<1>>` trims before counting characters, while
/// `Chain<LengthMin<1>, Trim>` counts first.
///
/// ```
/// # use validatable::*;
/// type Bio = Validated<String, Chain<Trim, RemoveChars<CharClassControl>, LengthMax<200>>>;
/// ```
pub type Chain<A, B = True, C = True, D = True, E = True, F = True, G = True, H = True> =
    Chain8<A, B, C, D, E, F, G, H>;

/// Succeeds when all of three validators succeed, left to right. See
/// [`And`].
pub type And3<A, B, C> = And2<And2<A, B>, C>;
/// Succeeds when all of four validators succeed, left to right. See
/// [`And`].
pub type And4<A, B, C, D> = And2<And3<A, B, C>, D>;
/// Succeeds when all of five validators succeed, left to right. See
/// [`And`].
pub type And5<A, B, C, D, E> = And2<And4<A, B, C, D>, E>;
/// Succeeds when all of six validators succeed, left to right. See
/// [`And`].
pub type And6<A, B, C, D, E, F> = And2<And5<A, B, C, D, E>, F>;
/// Succeeds when all of seven validators succeed, left to right. See
/// [`And`].
pub type And7<A, B, C, D, E, F, G> = And2<And6<A, B, C, D, E, F>, G>;
/// Succeeds when all of eight validators succeed, left to right. See
/// [`And`].
pub type And8<A, B, C, D, E, F, G, H> = And2<And7<A, B, C, D, E, F, G>, H>;
/// Succeeds when all of up to eight validators succeed (left to right,
/// short-circuiting on the first error). Unused slots default to [`True`].
///
/// Identical to [`Chain`]; use whichever name reads better.
///
/// ```
/// # use validatable::*;
/// type Token = Validated<String, And<LengthRange<8, 64>, AllChars<CharClassAsciiGraphic>>>;
/// ```
pub type And<A, B = True, C = True, D = True, E = True, F = True, G = True, H = True> =
    And8<A, B, C, D, E, F, G, H>;

/// Succeeds when any of three validators succeeds, tried left to right. See
/// [`Or`].
pub type Or3<A, B, C> = Or2<A, Or2<B, C>>;
/// Succeeds when any of four validators succeeds, tried left to right. See
/// [`Or`].
pub type Or4<A, B, C, D> = Or2<A, Or3<B, C, D>>;
/// Succeeds when any of five validators succeeds, tried left to right. See
/// [`Or`].
pub type Or5<A, B, C, D, E> = Or2<A, Or4<B, C, D, E>>;
/// Succeeds when any of six validators succeeds, tried left to right. See
/// [`Or`].
pub type Or6<A, B, C, D, E, F> = Or2<A, Or5<B, C, D, E, F>>;
/// Succeeds when any of seven validators succeeds, tried left to right. See
/// [`Or`].
pub type Or7<A, B, C, D, E, F, G> = Or2<A, Or6<B, C, D, E, F, G>>;
/// Succeeds when any of eight validators succeeds, tried left to right. See
/// [`Or`].
pub type Or8<A, B, C, D, E, F, G, H> = Or2<A, Or7<B, C, D, E, F, G, H>>;
/// Succeeds when any of up to eight validators succeeds (tried left to
/// right). Unused slots default to [`False`]. When all fail, the error of
/// the leftmost validator is reported.
///
/// ```
/// # use validatable::*;
/// type Cased = Validated<NonEmptyString, Or<AllChars<CharClassAsciiLowercase>, AllChars<CharClassAsciiUppercase>, AllChars<CharClassAsciiDigit>>>;
/// ```
pub type Or<A, B = False, C = False, D = False, E = False, F = False, G = False, H = False> =
    Or8<A, B, C, D, E, F, G, H>;

/// A no-op marker validator that makes otherwise identical types distinct.
///
/// Two [`Validated`] types with the same validators are the
/// same type. Add a `Variant<N>` with a different `N` to each chain to keep
/// them apart:
///
/// ```
/// use validatable::*;
///
/// type Name = Validated<NonEmptyString, Chain<AllChars<CharClassAscii>, Variant<1>>>;
/// type Id = Validated<NonEmptyString, Chain<AllChars<CharClassAscii>, Variant<2>>>;
///
/// fn takes_name(_: Name) {}
///
/// let name = Name::from_input(&"alice".to_string()).unwrap();
/// takes_name(name);
/// // A value of type `Id` would be rejected at compile time.
/// ```
pub struct Variant<const N: usize>;

/// Fails with [`Message::ValueExceedMin`] when the value is less than `MIN`.
/// Works with `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, and `u64` — the
/// only integer types with a built-in [`Validated`] field implementation;
/// `i128`/`u128` are not supported as field types.
///
/// `MIN` must be within the range the target type can represent, or the
/// check would silently degenerate (e.g. `SignedValueMin<-200>` applied to
/// `i8` could never reject anything). This is enforced with a compile-time
/// assertion, so such a mismatch is a compile error once the offending type
/// is actually validated (merely naming the type, e.g. in a field
/// declaration that is never validated, does not trigger it).
///
/// ```
/// # use validatable::*;
/// type Celsius = Validated<i32, True, SignedValueMin<-273>>;
/// ```
pub struct SignedValueMin<const MIN: i64>;
/// Fails with [`Message::ValueExceedMax`] when the value is greater than
/// `MAX`. Works with `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, and
/// `u64` — the only integer types with a built-in [`Validated`] field
/// implementation; `i128`/`u128` are not supported as field types.
///
/// `MAX` must be within the range the target type can represent — see
/// [`SignedValueMin`] for why and how this is enforced.
///
/// ```
/// # use validatable::*;
/// type Priority = Validated<i32, True, SignedValueMax<9>>;
/// ```
pub struct SignedValueMax<const MAX: i64>;
/// Requires `MIN <= value <= MAX` for signed integers.
///
/// See [`SignedValueMin`] and [`SignedValueMax`] for how a bound outside the
/// target type's range degenerates this check.
///
/// ```
/// # use validatable::*;
/// type TimezoneOffset = Validated<i32, True, SignedValueRange<-12, 14>>;
/// ```
pub type SignedValueRange<const MIN: i64, const MAX: i64> =
    Chain2<SignedValueMin<MIN>, SignedValueMax<MAX>>;

/// Fails with [`Message::ValueExceedMin`] when the value is less than `MIN`.
///
/// Works with `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, and `u64` — the
/// only integer types with a built-in [`Validated`] field implementation;
/// `i128`/`u128` are not supported as field types. Negative values (when
/// applied to a signed type) also fail with `Message::ValueExceedMin`,
/// reporting `MIN` itself, since the validator assumes a non-negative
/// domain.
///
/// `MIN` must not exceed the range the target type can represent (e.g.
/// `UnsignedValueMin<1_000>` applied to `u8`, where no value could ever
/// satisfy the check) — enforced with a compile-time assertion the same way
/// as [`SignedValueMin`].
///
/// ```
/// # use validatable::*;
/// type Port = Validated<u16, True, UnsignedValueMin<1024>>;
/// ```
pub struct UnsignedValueMin<const MIN: u64>;
/// Fails with [`Message::ValueExceedMax`] when the value is greater than
/// `MAX`.
///
/// Works with `i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, and `u64` — the
/// only integer types with a built-in [`Validated`] field implementation;
/// `i128`/`u128` are not supported as field types. Negative values (when
/// applied to a signed type) fail with `Message::ValueExceedMin("0")` — not
/// `ValueExceedMax` — since the validator assumes a non-negative domain.
///
/// `MAX` must not be at or beyond the range the target type can represent
/// (e.g. `UnsignedValueMax<100_000>` applied to `u8`, where every value
/// would silently satisfy the check) — enforced with a compile-time
/// assertion the same way as [`SignedValueMin`].
///
/// ```
/// # use validatable::*;
/// type Percentage = Validated<u8, True, UnsignedValueMax<100>>;
/// ```
pub struct UnsignedValueMax<const MAX: u64>;
/// Requires `MIN <= value <= MAX` for non-negative integers.
///
/// See [`UnsignedValueMin`] and [`UnsignedValueMax`] for how a bound outside
/// the target type's range degenerates this check.
///
/// ```
/// # use validatable::*;
/// type Month = Validated<u8, True, UnsignedValueRange<1, 12>>;
/// ```
pub type UnsignedValueRange<const MIN: u64, const MAX: u64> =
    Chain2<UnsignedValueMin<MIN>, UnsignedValueMax<MAX>>;

/// Fails when the value is less than `MIN / 1000`.
///
/// Const generics cannot be floats, so the bound is given as an integer
/// scaled by 1000: `FloatValueMinX1000<1_500>` means "at least 1.5". The
/// bound `MIN / 1000` is computed at `f64` precision before being rounded
/// once to the target float type, so for `f32` it is closer to the intended
/// value than rounding `MIN` itself to `f32` first would be — though `f32`'s
/// own precision (about 2^-24 relative) still applies, so bounds near or
/// above 2^24 cannot be represented exactly. `NaN` always fails with
/// [`Message::BadFormat`]; `±∞` are compared like any other value (so `+∞`
/// passes and `-∞` fails with [`Message::ValueExceedMin`]), matching how
/// [`Parsable`] treats `"inf"` / `"-inf"` input strings.
///
/// ```
/// use validatable::*;
///
/// type Rating = Validated<f64, True, FloatValueRangeX1000<0, 5_000>>;
/// assert!(Rating::from_raw(4.5).is_ok());
/// assert!(Rating::from_raw(5.1).is_err());
/// assert!(Rating::from_raw(f64::NAN).is_err());
/// ```
pub struct FloatValueMinX1000<const MIN: i64>;
/// Fails when the value is greater than `MAX / 1000`.
///
/// See [`FloatValueMinX1000`] for the scaling scheme, precision, and
/// non-finite value handling.
///
/// ```
/// # use validatable::*;
/// type Probability = Validated<f64, True, FloatValueMaxX1000<1_000>>; // at most 1.0
/// ```
pub struct FloatValueMaxX1000<const MAX: i64>;
/// Requires `MIN / 1000 <= value <= MAX / 1000` for floats.
///
/// ```
/// # use validatable::*;
/// type Longitude = Validated<f64, True, FloatValueRangeX1000<-180_000, 180_000>>;
/// ```
pub type FloatValueRangeX1000<const MIN: i64, const MAX: i64> =
    Chain2<FloatValueMinX1000<MIN>, FloatValueMaxX1000<MAX>>;

/// Fails when the string is shorter than `MIN` characters.
///
/// Length is measured in Unicode scalar values (`chars().count()`), not
/// bytes or grapheme clusters. An empty string fails with
/// [`Message::Empty`]; other violations fail with
/// [`Message::LengthExceedMin`].
///
/// ```
/// # use validatable::*;
/// type Password = Validated<String, LengthMin<8>>;
/// ```
pub struct LengthMin<const MIN: usize>;
/// Fails with [`Message::LengthExceedMax`] when the string is longer than
/// `MAX` characters (`chars().count()`, not bytes).
///
/// ```
/// # use validatable::*;
/// type Tweet = Validated<NonEmptyString, LengthMax<280>>;
/// ```
pub struct LengthMax<const MAX: usize>;
/// Requires `MIN <= chars().count() <= MAX`.
///
/// ```
/// # use validatable::*;
/// type UserName = Validated<String, LengthRange<3, 16>>;
/// ```
pub struct LengthRange<const MIN: usize, const MAX: usize>;

/// Fails with [`Message::InvalidChars`] (listing the offending characters)
/// unless every character belongs to the [`CharClass`] `C`. At most 10
/// distinct characters are reported: the first 10 unique offenders
/// encountered while scanning the input from the start, sorted for display.
///
/// An **empty string passes**: every character of `""` vacuously belongs to
/// any class. When the value must not be empty, use
/// [`NonEmptyString`] as the plain type (as below) or
/// add a [`LengthMin`] check.
///
/// ```
/// use validatable::*;
///
/// type Hex = Validated<NonEmptyString, AllChars<CharClassAsciiHexdigit>>;
/// assert!(Hex::from_input(&"C0FFEE".to_string()).is_ok());
/// assert_eq!(
///     Hex::from_input(&"0xG".to_string()),
///     Err(Message::InvalidChars(vec!['G', 'x']))
/// );
/// assert_eq!(Hex::from_input(&"".to_string()), Err(Message::Empty));
/// ```
pub struct AllChars<C: CharClass>(Marker<C>);
/// **Transforms** the string by trimming leading and trailing characters
/// belonging to the [`CharClass`] `C`. Never fails, for any input or `C` —
/// so [`Not<TrimChars<C>>`](Not) always fails.
///
/// ```
/// # use validatable::*;
/// type CleanPath = Validated<String, TrimChars<CharClassJust<'/'>>>;
/// ```
pub struct TrimChars<C: CharClass>(Marker<C>);
/// **Transforms** the string by removing every character belonging to the
/// [`CharClass`] `C`. Never fails, for any input or `C` — so
/// [`Not<RemoveChars<C>>`](Not) always fails.
///
/// ```
/// # use validatable::*;
/// type CardNumber = Validated<String, RemoveChars<CharClassJust<' '>>>;
/// ```
pub struct RemoveChars<C: CharClass>(Marker<C>);
/// **Transforms** the string by trimming leading and trailing whitespace.
/// Never fails — see [`TrimChars`] — so [`Not<Trim>`](Not) always fails.
///
/// Note that this changes the value: the validated result may differ from
/// the original input. Place it before length or character checks in a
/// [`Chain`] so they see the trimmed value.
///
/// ```
/// # use validatable::*;
/// type Comment = Validated<String, Chain<Trim, LengthMax<500>>>;
/// ```
pub type Trim = TrimChars<CharClassWhitespace>;

// common

impl<A: Validator<T>, B: Validator<T>, T: Clone> Validator<T> for Or2<A, B> {
    fn validate(s: T) -> Result<T, Message> {
        match A::validate(s.clone()) {
            Ok(v) => Ok(v),
            Err(e) => B::validate(s).map_err(|_| e),
        }
    }
}

impl<A: Validator<T>, B: Validator<T>, T> Validator<T> for And2<A, B> {
    fn validate(s: T) -> Result<T, Message> {
        A::validate(s).and_then(|s| B::validate(s))
    }
}

impl<A: Validator<T>, T: Clone> Validator<T> for Not<A> {
    fn validate(s: T) -> Result<T, Message> {
        match A::validate(s.clone()) {
            Ok(_) => Err(Message::ContentProblem),
            Err(_) => Ok(s),
        }
    }
}

impl<T> Validator<T> for True {
    fn validate(i: T) -> Result<T, Message> {
        Ok(i)
    }
}

impl<T> Validator<T> for False {
    fn validate(_: T) -> Result<T, Message> {
        Err(Message::Empty)
    }
}

impl<T, const N: usize> Validator<T> for Variant<N> {
    fn validate(i: T) -> Result<T, Message> {
        Ok(i)
    }
}

// Integer

macro_rules! impl_signed_value_min_max {
    ($t: ty) => {
        impl<const MIN: i64> Validator<$t> for SignedValueMin<MIN> {
            fn validate(i: $t) -> Result<$t, Message> {
                const {
                    assert!(
                        MIN as i128 >= <$t>::MIN as i128 && MIN as i128 <= <$t>::MAX as i128,
                        concat!(
                            "SignedValueMin<MIN>: MIN is outside the range representable by ",
                            stringify!($t)
                        )
                    );
                }
                if (i as i128) < (MIN as i128) {
                    Err(Message::ValueExceedMin(MIN.to_string()))
                } else {
                    Ok(i)
                }
            }
        }

        impl<const MAX: i64> Validator<$t> for SignedValueMax<MAX> {
            fn validate(i: $t) -> Result<$t, Message> {
                const {
                    assert!(
                        MAX as i128 >= <$t>::MIN as i128 && MAX as i128 <= <$t>::MAX as i128,
                        concat!(
                            "SignedValueMax<MAX>: MAX is outside the range representable by ",
                            stringify!($t)
                        )
                    );
                }
                if (i as i128) > (MAX as i128) {
                    Err(Message::ValueExceedMax(MAX.to_string()))
                } else {
                    Ok(i)
                }
            }
        }
    };
}

impl_signed_value_min_max!(i8);
impl_signed_value_min_max!(i16);
impl_signed_value_min_max!(i32);
impl_signed_value_min_max!(i64);
impl_signed_value_min_max!(u8);
impl_signed_value_min_max!(u16);
impl_signed_value_min_max!(u32);
impl_signed_value_min_max!(u64);

macro_rules! impl_unsigned_value_min_max {
    ($t: ty) => {
        impl<const MIN: u64> Validator<$t> for UnsignedValueMin<MIN> {
            fn validate(i: $t) -> Result<$t, Message> {
                const {
                    assert!(
                        MIN as u128 <= <$t>::MAX as u128,
                        concat!(
                            "UnsignedValueMin<MIN>: MIN is outside the range representable by ",
                            stringify!($t)
                        )
                    );
                }
                match TryInto::<u128>::try_into(i) {
                    Ok(v) if v >= MIN as u128 => Ok(i),
                    _ => Err(Message::ValueExceedMin(MIN.to_string())),
                }
            }
        }

        impl<const MAX: u64> Validator<$t> for UnsignedValueMax<MAX> {
            fn validate(i: $t) -> Result<$t, Message> {
                const {
                    assert!(
                        MAX as u128 <= <$t>::MAX as u128,
                        concat!(
                            "UnsignedValueMax<MAX>: MAX is outside the range representable by ",
                            stringify!($t)
                        )
                    );
                }
                match TryInto::<u128>::try_into(i) {
                    Ok(v) if v <= MAX as u128 => Ok(i),
                    Ok(_) => Err(Message::ValueExceedMax(MAX.to_string())),
                    Err(_) => Err(Message::ValueExceedMin(0.to_string())),
                }
            }
        }
    };
}

impl_unsigned_value_min_max!(i8);
impl_unsigned_value_min_max!(i16);
impl_unsigned_value_min_max!(i32);
impl_unsigned_value_min_max!(i64);
impl_unsigned_value_min_max!(u8);
impl_unsigned_value_min_max!(u16);
impl_unsigned_value_min_max!(u32);
impl_unsigned_value_min_max!(u64);

// Float

macro_rules! impl_float_value_x1000 {
    ($t: ty) => {
        impl<const MIN: i64> Validator<$t> for FloatValueMinX1000<MIN> {
            fn validate(i: $t) -> Result<$t, Message> {
                if i.is_nan() {
                    return Err(Message::BadFormat(Format::Float));
                }
                let t = ((MIN as f64) / 1000.0) as $t;
                if i < t {
                    Err(Message::ValueExceedMin(t.to_string()))
                } else {
                    Ok(i)
                }
            }
        }

        impl<const MAX: i64> Validator<$t> for FloatValueMaxX1000<MAX> {
            fn validate(i: $t) -> Result<$t, Message> {
                if i.is_nan() {
                    return Err(Message::BadFormat(Format::Float));
                }
                let t = ((MAX as f64) / 1000.0) as $t;
                if i > t {
                    Err(Message::ValueExceedMax(t.to_string()))
                } else {
                    Ok(i)
                }
            }
        }
    };
}

impl_float_value_x1000!(f32);
impl_float_value_x1000!(f64);

// String

impl<const MIN: usize> Validator<String> for LengthMin<MIN> {
    fn validate(s: String) -> Result<String, Message> {
        let len = s.chars().count();
        if len < MIN {
            Err(if len == 0 {
                Message::Empty
            } else {
                Message::LengthExceedMin(MIN.to_string())
            })
        } else {
            Ok(s)
        }
    }
}

impl<const MAX: usize> Validator<String> for LengthMax<MAX> {
    fn validate(s: String) -> Result<String, Message> {
        let len = s.chars().count();
        if len > MAX {
            Err(Message::LengthExceedMax(MAX.to_string()))
        } else {
            Ok(s)
        }
    }
}

impl<const MIN: usize, const MAX: usize> Validator<String> for LengthRange<MIN, MAX> {
    fn validate(s: String) -> Result<String, Message> {
        let len = s.chars().count();
        if len < MIN {
            Err(if len == 0 {
                Message::Empty
            } else {
                Message::LengthExceedMin(MIN.to_string())
            })
        } else if len > MAX {
            Err(Message::LengthExceedMax(MAX.to_string()))
        } else {
            Ok(s)
        }
    }
}

impl<C: CharClass> Validator<String> for TrimChars<C> {
    fn validate(s: String) -> Result<String, Message> {
        Ok(s.trim_matches(C::is_a).to_string())
    }
}

impl<C: CharClass> Validator<String> for RemoveChars<C> {
    fn validate(s: String) -> Result<String, Message> {
        Ok(s.chars().filter(|c| !C::is_a(*c)).collect())
    }
}

// CharClass

/// A set of characters, described at the type level.
///
/// Character classes are consumed by [`AllChars`], [`TrimChars`], and
/// [`RemoveChars`], and can be combined with the same [`And`]/[`Or`]/[`Not`]
/// combinators used for validators ([`True`] matches every character,
/// [`False`] none).
///
/// ```
/// # use validatable::*;
/// type KebabCase = Validated<NonEmptyString, AllChars<Or<CharClassAsciiLowercase, CharClassJust<'-'>>>>;
/// ```
///
/// The built-in classes (e.g. [`CharClassAlphabetic`]) follow the
/// behavior of the corresponding [`char`] method in the standard
/// library, so they perform no Unicode normalization and no
/// confusable-character detection.
pub trait CharClass {
    /// Returns `true` when `c` belongs to this class.
    fn is_a(c: char) -> bool;
}

impl CharClass for True {
    fn is_a(_: char) -> bool {
        true
    }
}

impl CharClass for False {
    fn is_a(_: char) -> bool {
        false
    }
}

impl<A: CharClass, B: CharClass> CharClass for And2<A, B> {
    fn is_a(c: char) -> bool {
        A::is_a(c) && B::is_a(c)
    }
}

impl<A: CharClass, B: CharClass> CharClass for Or2<A, B> {
    fn is_a(c: char) -> bool {
        A::is_a(c) || B::is_a(c)
    }
}

impl<A: CharClass> CharClass for Not<A> {
    fn is_a(c: char) -> bool {
        !A::is_a(c)
    }
}

/// The [`CharClass`] containing exactly the character `C`.
///
/// ```
/// use validatable::*;
///
/// type Digits = Validated<NonEmptyString, Chain<RemoveChars<CharClassJust<'-'>>, AllChars<CharClassAsciiDigit>>>;
/// let d = Digits::from_input(&"012-3456".to_string()).unwrap();
/// assert_eq!(d.to_string(), "0123456");
/// ```
pub struct CharClassJust<const C: char>;
impl<const C: char> CharClass for CharClassJust<C> {
    fn is_a(c: char) -> bool {
        c == C
    }
}

/// Maximum number of distinct offending characters reported by
/// [`Message::InvalidChars`]. Bounds the size of the error regardless of
/// how many invalid characters the input contains.
const MAX_REPORTED_INVALID_CHARS: usize = 10;

impl<C: CharClass> Validator<String> for AllChars<C> {
    fn validate(i: String) -> Result<String, Message> {
        let mut invalid = BTreeSet::new();
        for c in i.chars() {
            if !C::is_a(c) {
                invalid.insert(c);
                if invalid.len() >= MAX_REPORTED_INVALID_CHARS {
                    break;
                }
            }
        }
        if invalid.is_empty() {
            Ok(i)
        } else {
            Err(Message::InvalidChars(invalid.into_iter().collect()))
        }
    }
}

macro_rules! impl_char_class {
    ($t: ident, $m: ident, $e: literal $(, homoglyph_note: $ascii: ident)?) => {
        #[doc = concat!("The [`CharClass`] of characters for which [`char::", stringify!($m), "`] returns `true`.")]
        ///
        /// ```
        /// # use validatable::*;
        #[doc = $e]
        /// ```
        $(
            #[doc = ""]
            #[doc = concat!(
                "This matches on the full Unicode category and performs no confusable-character ",
                "detection: visually similar characters from different scripts (e.g. Cyrillic `а` ",
                "next to Latin `a`) are treated as distinct and may both pass. Where visual spoofing ",
                "(e.g. usernames, handles) must be prevented, prefer [`", stringify!($ascii), "`] instead."
            )]
        )?
        pub struct $t;
        impl CharClass for $t {
            fn is_a(c: char) -> bool {
                c.$m()
            }
        }
    };
    ($t: ident, $m: ident, $a: expr, $e: literal $(, homoglyph_note: $ascii: ident)?) => {
        #[doc = concat!("The [`CharClass`] of characters for which [`char::", stringify!($m), "`] (with argument `", stringify!($a), "`) returns `true`.")]
        ///
        /// ```
        /// # use validatable::*;
        #[doc = $e]
        /// ```
        $(
            #[doc = ""]
            #[doc = concat!(
                "This matches on the full Unicode category and performs no confusable-character ",
                "detection: visually similar characters from different scripts (e.g. Cyrillic `а` ",
                "next to Latin `a`) are treated as distinct and may both pass. Where visual spoofing ",
                "(e.g. usernames, handles) must be prevented, prefer [`", stringify!($ascii), "`] instead."
            )]
        )?
        pub struct $t;
        impl CharClass for $t {
            fn is_a(c: char) -> bool {
                c.$m($a)
            }
        }
    };
}

impl_char_class!(
    CharClassAlphabetic,
    is_alphabetic,
    "type Name = Validated<NonEmptyString, AllChars<CharClassAlphabetic>>;",
    homoglyph_note: CharClassAsciiAlphabetic
);
impl_char_class!(
    CharClassAlphanumeric,
    is_alphanumeric,
    "type FileStem = Validated<NonEmptyString, AllChars<CharClassAlphanumeric>>;",
    homoglyph_note: CharClassAsciiAlphanumeric
);
impl_char_class!(
    CharClassAscii,
    is_ascii,
    "type AsciiText = Validated<NonEmptyString, AllChars<CharClassAscii>>;"
);
impl_char_class!(
    CharClassAsciiAlphabetic,
    is_ascii_alphabetic,
    "type RomanName = Validated<NonEmptyString, AllChars<CharClassAsciiAlphabetic>>;"
);
impl_char_class!(
    CharClassAsciiAlphanumeric,
    is_ascii_alphanumeric,
    "type ProductCode = Validated<NonEmptyString, AllChars<CharClassAsciiAlphanumeric>>;"
);
impl_char_class!(
    CharClassAsciiControl,
    is_ascii_control,
    "type PlainLine = Validated<String, RemoveChars<CharClassAsciiControl>>;"
);
impl_char_class!(
    CharClassAsciiDigit,
    is_ascii_digit,
    "type ZipCode = Validated<NonEmptyString, AllChars<CharClassAsciiDigit>>;"
);
impl_char_class!(
    CharClassAsciiGraphic,
    is_ascii_graphic,
    "type Password = Validated<NonEmptyString, AllChars<CharClassAsciiGraphic>>;"
);
impl_char_class!(
    CharClassAsciiHexdigit,
    is_ascii_hexdigit,
    "type ColorCode = Validated<NonEmptyString, AllChars<CharClassAsciiHexdigit>>;"
);
impl_char_class!(
    CharClassAsciiLowercase,
    is_ascii_lowercase,
    "type Subdomain = Validated<NonEmptyString, AllChars<CharClassAsciiLowercase>>;"
);
impl_char_class!(
    CharClassAsciiPunctuation,
    is_ascii_punctuation,
    "type SearchWord = Validated<String, RemoveChars<CharClassAsciiPunctuation>>;"
);
impl_char_class!(
    CharClassAsciiUppercase,
    is_ascii_uppercase,
    "type CountryCode = Validated<NonEmptyString, AllChars<CharClassAsciiUppercase>>;"
);
impl_char_class!(
    CharClassAsciiWhitespace,
    is_ascii_whitespace,
    "type Joined = Validated<String, RemoveChars<CharClassAsciiWhitespace>>;"
);
impl_char_class!(
    CharClassControl,
    is_control,
    "type SafeText = Validated<String, RemoveChars<CharClassControl>>;"
);
impl_char_class!(
    CharClassDigit,
    is_digit,
    10,
    "type PhoneNumber = Validated<NonEmptyString, AllChars<CharClassDigit>>;"
);
impl_char_class!(
    CharClassLowercase,
    is_lowercase,
    "type Tag = Validated<NonEmptyString, AllChars<CharClassLowercase>>;",
    homoglyph_note: CharClassAsciiLowercase
);
impl_char_class!(
    CharClassNumeric,
    is_numeric,
    "type NumeralText = Validated<NonEmptyString, AllChars<CharClassNumeric>>;",
    homoglyph_note: CharClassAsciiDigit
);
impl_char_class!(
    CharClassUppercase,
    is_uppercase,
    "type Acronym = Validated<NonEmptyString, AllChars<CharClassUppercase>>;",
    homoglyph_note: CharClassAsciiUppercase
);
impl_char_class!(
    CharClassWhitespace,
    is_whitespace,
    "type Trimmed = Validated<String, TrimChars<CharClassWhitespace>>;"
);