valid 0.3.1

Validate custom types by composing primitive validation functions. Use one common API for validating all kind of business rules including aspects of the application state. One common error type for all kind of constraint violations. It is designed to help with error messages that are meaningful to the user of an application.
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! The core API of the `valid` crate

#[cfg(feature = "bigdecimal")]
use bigdecimal::BigDecimal;
#[cfg(feature = "chrono")]
use chrono::{DateTime, NaiveDate, TimeZone, Utc};
#[cfg(feature = "num-bigint")]
use num_bigint::BigInt;
#[cfg(feature = "serde1")]
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt;
use std::fmt::{Debug, Display, Write};
use std::iter::FromIterator;
use std::marker::PhantomData;
use std::ops::Deref;

/// A wrapper type to express that the value of type `T` has been validated by
/// the constraint `C`.
///
/// The idea is that an instance of `Validated<C, T>` can only be obtained by
/// validating a value of type `T` using the constraint `C`. There is no way to
/// construct an instance of `Validated` directly.[^1]
///
/// It follows the new type pattern and can be de-referenced to a immutable
/// reference to its inner value or unwrapped to get the owned inner value.
///
/// In an application we can make use of the type system to assure that only
/// valid values of some type can be input to some function performing some
/// domain related things.
///
/// For example, lets assume we have a function that expects a valid email
/// address as input. We could write the function like:
///
/// ```
/// fn send_email(to: String, message: String) {
///     unimplemented!()
/// }
/// ```
///
/// The problem with this approach is, that we can never be sure that the string
/// input for the `to` argument is a valid email address.
///
/// Lets rewrite the same function using `Validated<Email, String>`.
///
/// ```ignore //TODO remove ignore when Email constraint is implemented
/// use valid::Validated;
///
/// fn send_email(to: Validated<Email, String>, message: String) {
///     unimplemented!()
/// }
/// ```
///
/// Due to we can not instantiate `Validated` directly using some constructor
/// function like `Validated(email)` or `Validated::new(email)` we need to use
/// a validation function like:
///
/// ```ignore //TODO remove ignore when Email constraint is implemented
/// # fn send_email(to: Validated<Email, String>, message: String) {
/// #     unimplemented!()
/// # }
/// use valid::{Validated, Validate};
///
/// let to_addr = "jane.doe@email.net".to_string().validate("email", Email).result()
///         .expect("valid email address");
///
/// send_email(to_addr, "some message".into());
/// ```
///
/// Now we can be sure that the variable `to_addr` contains a valid email
/// address.
///
/// To further make use of meaningful new types we might define a custom new
/// type for email addresses, that can only be constructed from a validated
/// value like so:
///
/// ```ignore //TODO remove ignore when Email constraint is implemented
/// # fn send_email(to: EmailAddress, message: String) {
/// #     unimplemented!()
/// # }
/// use valid::{Validate, Validated};
///
/// mod domain_model {
///     use valid::Validated;
///     pub struct EmailAddress(String);
///
///     impl From<Validated<Email, String>> for EmailAddress {
///         fn from(value: Validated<String>) -> Self {
///             EmailAddress(value.unwrap())
///         }
///     }
/// }
///
/// let validated = "jane.doe@email.net".to_string().validate("email", Email).result(None)
///         .expect("valid email address");
///
/// let to_addr = EmailAddress::from(validated);
///
/// send_email(to_addr, "some message".into());
/// ```
///
/// Due to the type `EmailAddress` is defined in another module it can only be
/// constructed from a `Validated<Email, String>`.
///
/// [^1]: Actually there is a way to construct an instance of `Validated`
///       without actually doing any validation: we can use the
///       `Validation::success` method (see unit tests on how it can be done)
///       We need this method for custom implementations of the `Validate`
///       trait. Unfortunately I have no idea how to prevent this.
///       Fortunately such code can be found by (automated) code review.
pub struct Validated<C, T>(PhantomData<C>, T);

impl<C, T> Validated<C, T> {
    /// Unwraps the original value that has been validated
    pub fn unwrap(self) -> T {
        self.1
    }
}

impl<C, T> Debug for Validated<C, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Validated")
            .field(&format_args!("_"))
            .field(&self.1)
            .finish()
    }
}

impl<C, T> PartialEq for Validated<C, T>
where
    T: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.1.eq(&other.1)
    }
}

impl<C, T> Eq for Validated<C, T> where T: Eq {}

impl<C, T> Clone for Validated<C, T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        Self(PhantomData, self.1.clone())
    }
}

impl<C, T> Copy for Validated<C, T> where T: Copy {}

impl<C, T> Deref for Validated<C, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.1
    }
}

/// The validation function validates whether the given value complies to the
/// specified constraint.
///
/// It returns a `Validation` value that may be used to perform further
/// validations using its combinator methods `and` or `and_then` or get the
/// final result by calling the `result` method.
///
/// The context provides additional information to perform the validation,
/// for example a lookup table or some state information. It may also hold
/// parameters needed to provide additional parameters to the error in case
/// of a constraint violation. (see the crate level documentation for more
/// details on how to use the context)
///
/// see the crate level documentation for details about how to implement a the
/// `Validate` trait for custom constraints and custom types.
pub trait Validate<C, S>
where
    S: Context,
    Self: Sized,
{
    /// Validates this value for being compliant to the specified constraint
    /// `C` in the given context `S`.
    fn validate(self, context: impl Into<S>, constraint: &C) -> Validation<C, Self>;
}

mod private {
    pub trait Sealed {}

    impl<T> Sealed for T where T: super::Context {}
}

/// Trait to mark structs as context for validation functions.
///
/// This trait is sealed and can not be implemented for types outside this
/// crate.
pub trait Context: private::Sealed {}

/// Represents the field level context for validation functions. Its value is
/// the name of the field to be validated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldName(pub Cow<'static, str>);

impl Context for FieldName {}

impl<A> From<A> for FieldName
where
    A: Into<Cow<'static, str>>,
{
    fn from(value: A) -> Self {
        FieldName(value.into())
    }
}

impl Deref for FieldName {
    type Target = Cow<'static, str>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FieldName {
    /// Unwraps this field name context and returns the field name itself
    pub fn unwrap(self) -> Cow<'static, str> {
        self.0
    }
}

/// Represents a pair of related fields as context for validation functions.
/// It holds the names of the two related fields that are validated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelatedFields(pub Cow<'static, str>, pub Cow<'static, str>);

impl Context for RelatedFields {}

impl<A, B> From<(A, B)> for RelatedFields
where
    A: Into<Cow<'static, str>>,
    B: Into<Cow<'static, str>>,
{
    fn from((value1, value2): (A, B)) -> Self {
        RelatedFields(value1.into(), value2.into())
    }
}

impl RelatedFields {
    /// Unwraps this related fields context and returns the 2 field names
    pub fn unwrap(self) -> (Cow<'static, str>, Cow<'static, str>) {
        (self.0, self.1)
    }

    /// Returns a reference to the name of the first field
    pub fn first(&self) -> &str {
        &self.0
    }

    /// Returns a reference to the name of the second field
    pub fn second(&self) -> &str {
        &self.1
    }
}

/// Represents the state context for validation functions. Its value is the
/// state information needed to execute the validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct State<S>(pub S);

impl<S> Context for State<S> {}

impl<S> From<S> for State<S> {
    fn from(value: S) -> Self {
        State(value)
    }
}

impl<S> Deref for State<S> {
    type Target = S;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<S> State<S> {
    /// Unwraps this state context and returns the state information itself
    pub fn unwrap(self) -> S {
        self.0
    }
}

#[derive(PartialEq)]
enum InnerValidation<C, T> {
    Success(PhantomData<C>, T),
    Failure(Vec<ConstraintViolation>),
}

/// State of an ongoing validation.
///
/// It provides combinator methods like [`and`] and [`and_then`] to combine
/// validation steps to complex validations and accumulates all constraint
/// violations found by the executed validations.
///
/// The result of a validation can be obtained by calling the [`result`] method.
///
/// see the crate level documentation for details and examples on how to use
/// the methods provided by this struct.
///
/// [`and`]: #method.and
/// [`and_then`]: #method.and_then
/// [`result`]: #method.result
#[derive(PartialEq)]
pub struct Validation<C, T>(InnerValidation<C, T>);

impl<C, T> Debug for Validation<C, T>
where
    C: Debug,
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            InnerValidation::Success(constraint, value) => {
                write!(f, "Validation(Success({:?}, {:?}))", constraint, value)
            }
            InnerValidation::Failure(violations) => {
                write!(f, "Validation(Failure({:?}))", violations)
            }
        }
    }
}

impl<C, T> Validation<C, T> {
    /// Constructs a `Validation` for a successful validation step.
    ///
    /// This method is provided to enable users of this crate to implement
    /// custom validation functions.
    pub fn success(valid: T) -> Self {
        Validation(InnerValidation::Success(PhantomData, valid))
    }

    /// Constructs a `Validation` for a failed validation step.
    ///
    /// This method is provided to enable users of this crate to implement
    /// custom validation functions.
    pub fn failure(constraint_violations: impl IntoIterator<Item = ConstraintViolation>) -> Self {
        Validation(InnerValidation::Failure(Vec::from_iter(
            constraint_violations.into_iter(),
        )))
    }

    /// Finishes a validation and returns the result of the validation.
    ///
    /// A validation may comprise multiple validation steps that are combined
    /// using the combinator methods of this struct. After all steps are
    /// executed this method can be called to get the [`ValidationResult`]
    ///
    /// [`ValidationResult`]: type.ValidationResult.html
    pub fn result(self) -> ValidationResult<C, T> {
        match self.0 {
            InnerValidation::Success(_c, entity) => Ok(Validated(_c, entity)),
            InnerValidation::Failure(violations) => Err(ValidationError {
                message: None,
                violations,
            }),
        }
    }

    /// Finishes a validation providing a message and returns the result.
    ///
    /// A validation may comprise multiple validation steps that are combined
    /// using the combinator methods of this struct. After all steps are
    /// executed this method can be called to get the [`ValidationResult`]
    ///
    /// In case of an error the [`ValidationError`] will contain the given
    /// message. It is meant to describe the context in which the validation has
    /// been executed. E.g when validating a struct that represents an input
    /// form the message would be something like "validating registration form"
    /// or when validating a struct that represents a REST command the message
    /// would be something like "invalid post entry command".
    ///
    /// [`ValidationResult`]: type.ValidationResult.html
    /// [`ValidationError`]: struct.ValidationError.html
    pub fn with_message(self, message: impl Into<Cow<'static, str>>) -> ValidationResult<C, T> {
        match self.0 {
            InnerValidation::Success(_c, entity) => Ok(Validated(_c, entity)),
            InnerValidation::Failure(violations) => Err(ValidationError {
                message: Some(message.into()),
                violations,
            }),
        }
    }

    /// Combines a value that needs no further validation with the validation
    /// result.
    ///
    /// This method may be especially useful in combination with the
    /// [`and_then`] combinator method. See the crate level documentation for
    /// an example.
    ///
    /// [`and_then`]: #method.and_then
    pub fn combine<U>(self, value: U) -> Validation<C, (U, T)> {
        match self.0 {
            InnerValidation::Success(_, entity) => Validation::success((value, entity)),
            InnerValidation::Failure(violations) => Validation::failure(violations),
        }
    }

    /// Maps the validated values into another type.
    ///
    /// This method is used for complex validations that validate multiple
    /// fields of a struct and the result should be mapped back into this
    /// struct. See the crate level documentation for an example.
    pub fn map<D, U>(self, convert: impl Fn(T) -> U) -> Validation<D, U> {
        match self.0 {
            InnerValidation::Success(_, entity) => Validation::success(convert(entity)),
            InnerValidation::Failure(violations) => Validation::failure(violations),
        }
    }

    /// Combines this validation with another validation unconditionally.
    ///
    /// The other validation is executed regardless whether this validation has
    /// been successful or not.
    ///
    /// The resulting validation is only successful if itself was successful
    /// and the other validation is also successful. Any constraint violations
    /// found either by this validation or the other validation are accumulated.
    ///
    /// See the crate level documentation for an example.
    pub fn and<D, U>(self, other: Validation<D, U>) -> Validation<D, (T, U)> {
        match (self.0, other.0) {
            (InnerValidation::Success(_, value1), InnerValidation::Success(_, value2)) => {
                Validation::success((value1, value2))
            }
            (InnerValidation::Failure(violations), InnerValidation::Success(_, _)) => {
                Validation::failure(violations)
            }
            (InnerValidation::Success(_, _), InnerValidation::Failure(violations)) => {
                Validation::failure(violations)
            }
            (InnerValidation::Failure(mut violations), InnerValidation::Failure(violations2)) => {
                violations.extend(violations2);
                Validation::failure(violations)
            }
        }
    }

    /// Combines this validation with another validation conditionally.
    ///
    /// The other validation is only executed if this validation has been
    /// successful. It has access to the values that have been validated so far.
    ///
    /// Those values are provided in a tuple as an argument to the given
    /// closure. If there is one value that has been validated so far the
    /// argument `T` to the closure is simple the type of the value. In case of
    /// two values `T` is a tuple of type `(A, B)`, in case of 3 values the type
    /// of `T` is a tuple of a tuple and the 3rd value like `((A, B), C)` and
    /// so on.
    ///
    /// Values that are given as argument to the closure but not used for the
    /// other validation are not part of the final result of the validation.
    /// To add unused values to the result of the validation we can use the
    /// [`combine`] method.
    ///
    /// See the crate level documentation for an example.
    ///
    /// [`combine`]: #method.combine
    pub fn and_then<D, U>(self, next: impl FnOnce(T) -> Validation<D, U>) -> Validation<D, U> {
        match self.0 {
            InnerValidation::Success(_, value1) => next(value1),
            InnerValidation::Failure(violations) => Validation::failure(violations),
        }
    }
}

/// A `Value` represents a value of certain type.
///
/// The purpose of a `Value` is to include field values or parameters in
/// [`ConstraintViolation`]s in a type that allows to display the value in a
/// localized format as part of a user facing error message.
///
/// It has variants for the basic types that are used in most applications.
///
/// Important types of 3rd party crates are supported through optional crate
/// features:
///
/// | supported type | crate feature | 3rd party crate |
/// |----------------|---------------|-----------------|
/// | `BigInt`       | `num-bigint`  | [`num-bigint`]  |
/// | `BigDecimal`   | `bigdecimal`  | [`bigdecimal`]  |
/// | `NaiveDate`    | `chrono`      | [`chrono`]      |
/// | `DateTime`     | `chrono`      | [`chrono`]      |
///
/// The `From` trait is implemented for the underlying types. Additionally
/// there are implementations of the `From` trait for the primitive types `i8`,
/// `i16`, `i64`, `u8`, `u16`, `u32`, `u64`.
///
/// `u32` values greater than `i32::max_value()` are converted to `Long(i64)`.
///
/// # Panics
///
/// Converting `u64` values greater than `i64::max_value()` has an unreliable
/// behavior and might panic.
///
/// # Notes
///
/// The list of supported types is very opinionated and may not fit all kind of
/// applications. Please file and issue if you feel that support for another
/// type may be useful!
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
/// [`bigdecimal`]: https://crates.io/crates/bigdecimal
/// [`chrono`]: https://crates.io/crates/chrono
/// [`num-bigint`]: https://crates.io/crates/num-bigint
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// a string value
    String(String),
    /// a 32bit signed integer value
    Integer(i32),
    /// a 64bit signed integer value
    Long(i64),
    /// a 32bit float value
    Float(f32),
    /// a 64bit float value
    Double(f64),
    /// a boolean value
    Boolean(bool),
    /// a decimal value
    #[cfg(feature = "bigdecimal")]
    Decimal(BigDecimal),
    /// a date value
    #[cfg(feature = "chrono")]
    Date(NaiveDate),
    /// a value with date, time and timezone
    #[cfg(feature = "chrono")]
    DateTime(DateTime<Utc>),
    /// a big integer value
    #[cfg(feature = "num-bigint")]
    BigInteger(BigInt),
}

impl Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::String(value) => write!(f, "{}", value),
            Value::Integer(value) => write!(f, "{}", value),
            Value::Long(value) => write!(f, "{}", value),
            Value::Float(value) => write!(f, "{}", value),
            Value::Double(value) => write!(f, "{}", value),
            Value::Boolean(value) => write!(f, "{}", value),
            #[cfg(feature = "bigdecimal")]
            Value::Decimal(value) => write!(f, "{}", value),
            #[cfg(feature = "chrono")]
            Value::Date(value) => write!(f, "{}", value),
            #[cfg(feature = "chrono")]
            Value::DateTime(value) => write!(f, "{}", value),
            #[cfg(feature = "num-bigint")]
            Value::BigInteger(value) => write!(f, "{}", value),
        }
    }
}

impl From<String> for Value {
    fn from(value: String) -> Self {
        Value::String(value)
    }
}

impl From<i32> for Value {
    fn from(value: i32) -> Self {
        Value::Integer(value)
    }
}

impl From<i16> for Value {
    fn from(value: i16) -> Self {
        Value::Integer(i32::from(value))
    }
}

impl From<u16> for Value {
    fn from(value: u16) -> Self {
        Value::Integer(i32::from(value))
    }
}

impl From<i8> for Value {
    fn from(value: i8) -> Self {
        Value::Integer(i32::from(value))
    }
}

impl From<u8> for Value {
    fn from(value: u8) -> Self {
        Value::Integer(i32::from(value))
    }
}

impl From<u32> for Value {
    fn from(value: u32) -> Self {
        if value > i32::max_value() as u32 {
            Value::Long(i64::from(value))
        } else {
            Value::Integer(value as i32)
        }
    }
}

impl From<i64> for Value {
    fn from(value: i64) -> Self {
        Value::Long(value)
    }
}

//TODO unreliable conversion - should be removed!
impl From<u64> for Value {
    fn from(value: u64) -> Self {
        assert!(
            value <= i64::max_value() as u64,
            "u64 value too big to be converted to i64"
        );
        Value::Long(value as i64)
    }
}

impl From<f32> for Value {
    fn from(value: f32) -> Self {
        Value::Float(value)
    }
}

impl From<f64> for Value {
    fn from(value: f64) -> Self {
        Value::Double(value)
    }
}

impl From<bool> for Value {
    fn from(value: bool) -> Self {
        Value::Boolean(value)
    }
}

#[cfg(feature = "bigdecimal")]
impl From<BigDecimal> for Value {
    fn from(value: BigDecimal) -> Self {
        Value::Decimal(value)
    }
}

#[cfg(feature = "chrono")]
impl From<NaiveDate> for Value {
    fn from(value: NaiveDate) -> Self {
        Value::Date(value)
    }
}

#[cfg(feature = "chrono")]
impl<Z> From<DateTime<Z>> for Value
where
    Z: TimeZone,
{
    fn from(value: DateTime<Z>) -> Self {
        Value::DateTime(value.with_timezone(&Utc))
    }
}

#[cfg(feature = "num-bigint")]
impl From<BigInt> for Value {
    fn from(value: BigInt) -> Self {
        Value::BigInteger(value)
    }
}

#[cfg(target_pointer_width = "32")]
impl TryFrom<usize> for Value {
    type Error = &'static str;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value <= i32::max_value() as usize {
            Ok(Value::Integer(value as i32))
        } else if value as u64 <= i64::max_value() as u64 {
            Ok(Value::Long(value as i64))
        } else {
            Err("usize value too big to be converted to i64")
        }
    }
}

#[cfg(target_pointer_width = "64")]
impl TryFrom<usize> for Value {
    type Error = &'static str;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        if value <= i32::max_value() as usize {
            Ok(Value::Integer(value as i32))
        } else if value <= i64::max_value() as usize {
            Ok(Value::Long(value as i64))
        } else {
            Err("usize value too big to be converted to i64")
        }
    }
}

fn option_to_string<T: Display>(optional_value: Option<&T>) -> String {
    match optional_value {
        Some(value) => value.to_string(),
        None => "(n.a.)".to_string(),
    }
}

fn array_to_string<T: Display>(array: &[T]) -> String {
    let separator = " / ";
    let len = array.len();
    let mut iter = array.iter();
    match iter.next() {
        None => "[]".into(),
        Some(first_elem) => {
            let mut result = String::with_capacity(len * separator.len() + 4);
            result.push_str("[ ");
            write!(&mut result, "{}", first_elem).unwrap();
            for elem in iter {
                result.push_str(separator);
                write!(&mut result, "{}", elem).unwrap();
            }
            result.push_str(" ]");
            result
        }
    }
}

/// A key/value pair used as parameter.
///
/// This struct is used to provide more details in [`ConstraintViolation`]s.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Parameter {
    /// The name of the parameter
    pub name: Cow<'static, str>,

    /// The value of the parameter
    pub value: Value,
}

impl Display for Parameter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}={}", self.name, self.value)
    }
}

impl Parameter {
    /// Construct a new `Parameter` with given name and value.
    pub fn new(name: impl Into<Cow<'static, str>>, value: impl Into<Value>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }
}

/// Details about a field.
///
/// This struct is used to provide more details in [`ConstraintViolation`]s.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct Field {
    /// The name of the field
    pub name: Cow<'static, str>,

    /// The actual value of the field
    pub actual: Option<Value>,

    /// An example for an expected value
    pub expected: Option<Value>,
}

impl Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "field: {}, actual: {}, expected: {}",
            self.name,
            option_to_string(self.actual.as_ref()),
            option_to_string(self.expected.as_ref())
        )
    }
}

/// Holds details about a constraint violation found by validating a constraint
/// in the [`FieldName`] context.
///
/// [`FieldName`]: struct.FieldName.html
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct InvalidValue {
    /// Error code that identifies the exact error.
    ///
    /// A client that receives the constraint violation should be able to
    /// interpret this error code.
    pub code: Cow<'static, str>,

    /// Details about the field having a value that violates a constraint.
    pub field: Field,
}

impl Display for InvalidValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} of {} which is {}, expected to be {}",
            self.code,
            self.field.name,
            option_to_string(self.field.actual.as_ref()),
            option_to_string(self.field.expected.as_ref())
        )
    }
}

/// Holds details about a constraint violation found by validating a constraint
/// in the [`RelatedFields`] context.
///
/// [`RelatedFields`]: struct.RelatedFields.html
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct InvalidRelation {
    /// Error code that identifies the exact error.
    ///
    /// A client that receives the constraint violation should be able to
    /// interpret this error code.
    pub code: Cow<'static, str>,

    /// Details about the first of the pair of related fields
    pub field1: Field,

    /// Details about the second of the pair of related fields
    pub field2: Field,
}

impl Display for InvalidRelation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} of {} which is {} and {} which is {}",
            self.code,
            self.field1.name,
            option_to_string(self.field1.actual.as_ref()),
            self.field2.name,
            option_to_string(self.field2.actual.as_ref())
        )
    }
}

/// Holds details about a constraint violation found by validating a constraint
/// in the [`State`] context.
///
/// [`State`]: struct.State.html
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct InvalidState {
    /// Error code that identifies the exact error.
    ///
    /// A client that receives the constraint violation should be able to
    /// interpret this error code.
    pub code: Cow<'static, str>,

    /// A list of parameters that may be used to provide more meaningful error
    /// messages to the user of an application
    pub params: Vec<Parameter>,
}

impl Display for InvalidState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} for parameters: {}",
            self.code,
            array_to_string(&self.params)
        )
    }
}

/// Represents a constraint violation found by some validation function.
///
/// The variants provide different details about a constraint violation. As
/// described in the crate level documentation this crate considers 3 categories
/// of business rules or constraints. Violations of constraints of the different
/// categories might provide different details about the validation.
///
/// For example a field validation might provide the field name, the actual value
/// and an example for the expected value. A constraint on the relation of a
/// pair of fields might provide the names of the 2 fields. Stateful constraints
/// may provide a list of parameters that might be useful to describe the
/// reason of the constraint violation.
///
/// An implementation of a constraint should choose the most appropriate
/// context for the kind of business rule it is implementing. Here is a table
/// that shows the relation of the implemented context and the variant of the
/// constraint violation type.
///
/// | Context            | Constraint Violation | Construction Method      |
/// |--------------------|----------------------|--------------------------|
/// | [`FieldName`]      | `Field`              | [`invalid_value`]<br/>[`invalid_optional_value`] |
/// | [`RelatedFields`]  | `Relation`           | [`invalid_relation`]     |
/// | [`State<S>`]       | `State`              | [`invalid_state`]        |
///
/// The construction methods are a convenient way to construct
/// `ConstraintViolation`s.
///
/// `ConstraintViolation` can be serialized and deserialized using the [`serde`]
/// crate. To use the `serde` support the optional crate feature `serde1` must
/// be enabled.
///
/// [`FieldName`]: struct.FieldName.html
/// [`RelatedFields`]: struct.RelatedFields.html
/// [`State<S>`]: struct.State.html
/// [`invalid_value`]: fn.invalid_value.html
/// [`invalid_optional_value`]: fn.invalid_optional_value.html
/// [`invalid_relation`]: fn.invalid_relation.html
/// [`invalid_state`]: fn.invalid_state.html
/// [`serde`]: https://crates.io/crates/serde
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum ConstraintViolation {
    /// Violation of a constraint validated in the `FieldName` context
    Field(InvalidValue),
    /// Violation of a constraint validated in the `RelatedField` context
    Relation(InvalidRelation),
    /// Violation of a constraint validated in the `State` context
    State(InvalidState),
}

impl Display for ConstraintViolation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConstraintViolation::Field(value) => write!(f, "{}", value),
            ConstraintViolation::Relation(value) => write!(f, "{}", value),
            ConstraintViolation::State(value) => write!(f, "{}", value),
        }
    }
}

impl From<InvalidValue> for ConstraintViolation {
    fn from(invalid_value: InvalidValue) -> Self {
        ConstraintViolation::Field(invalid_value)
    }
}

impl From<InvalidRelation> for ConstraintViolation {
    fn from(invalid_relation: InvalidRelation) -> Self {
        ConstraintViolation::Relation(invalid_relation)
    }
}

impl From<InvalidState> for ConstraintViolation {
    fn from(invalid_state: InvalidState) -> Self {
        ConstraintViolation::State(invalid_state)
    }
}

/// The error type returned if the validation finds any constraint violation.
///
/// It holds a list of constraint violations and an optional message. The
/// message is meant to describe the context in which the validation has been
/// performed. It is helpful when validating a struct that represents an input
/// form or a REST command. In such cases the message would be something like
/// "validating registration form" or "invalid post entry command".
///
/// The `Display` and `Error` traits are implemented to be compatible with most
/// error management concepts. It can be converted into `failure::Error` using
/// `From` or `Into` conversion traits.
///
/// It can be serialized and deserialized using the [`serde`] crate. To enable
/// `serde` support the optional crate feature `serde1` must be enabled.
///
/// [`serde`]: https://crates.io/crates/serde
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ValidationError {
    /// Message that describes the context in which the validation has been
    /// executed
    pub message: Option<Cow<'static, str>>,

    /// A list of constraint violations found during validation
    pub violations: Vec<ConstraintViolation>,
}

impl Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.message {
            Some(message) => write!(f, "{}: {}", message, array_to_string(&self.violations)),
            None => write!(f, "{}", array_to_string(&self.violations)),
        }
    }
}

impl Error for ValidationError {}

impl ValidationError {
    /// Merges this validation error with another validation error and returns
    /// a new validation error that contains all constraint violations from
    /// both errors merged into one list.
    ///
    /// If both of the validation errors contain a message than the messages
    /// are concatenated separated by the string `' / '`. If only one of the
    /// two errors contain a message than this message becomes the message of
    /// the resulting error.
    ///
    /// # Examples
    ///
    /// ```
    /// use valid::{ValidationError, invalid_value};
    ///
    /// let validation_error1 = ValidationError {
    ///     message: Some("validating a user's age".into()),
    ///     violations: vec![invalid_value("invalid-bound-min", "age", 12, 13)],
    /// };
    /// let validation_error2 = ValidationError {
    ///     message: Some("validating a user registration command".into()),
    ///     violations: vec![invalid_value("invalid-length-min", "username", 3, 4)],
    /// };
    ///
    /// let merged_error = validation_error2.merge(validation_error1);
    ///
    /// assert_eq!(
    ///     merged_error,
    ///     ValidationError {
    ///         message: Some(
    ///             "validating a user registration command / validating a user's age".into()
    ///         ),
    ///         violations: vec![
    ///             invalid_value("invalid-length-min", "username", 3, 4),
    ///             invalid_value("invalid-bound-min", "age", 12, 13),
    ///         ]
    ///     }
    /// );
    /// ```
    pub fn merge(mut self, other: ValidationError) -> Self {
        self.message = match (self.message, other.message) {
            (Some(msg1), Some(msg2)) => Some(msg1 + " / " + msg2),
            (None, Some(msg2)) => Some(msg2),
            (Some(msg1), None) => Some(msg1),
            (None, None) => None,
        };
        self.violations.extend(other.violations);
        self
    }
}

/// Type alias for the validation result for shorter type annotations.
pub type ValidationResult<C, T> = Result<Validated<C, T>, ValidationError>;

/// Convenience function to construct a [`ConstraintViolation`] for a validation
/// performed in the [`FieldName`] context.
///
/// Use this method if the field value is mandatory. If the field is of type
/// `Option<T>` consider using the [`invalid_optional_value`] method instead.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
/// [`FieldName`]: struct.FieldName.html
/// [`invalid_optional_value`]: fn.invalid_optional_value.html
pub fn invalid_value(
    code: impl Into<Cow<'static, str>>,
    field_name: impl Into<FieldName>,
    actual_value: impl Into<Value>,
    expected_value: impl Into<Value>,
) -> ConstraintViolation {
    ConstraintViolation::Field(InvalidValue {
        code: code.into(),
        field: Field {
            name: field_name.into().unwrap(),
            actual: Some(actual_value.into()),
            expected: Some(expected_value.into()),
        },
    })
}

/// Convenience function to construct a [`ConstraintViolation`] for a validation
/// performed in the [`FieldName`] context.
///
/// Use this method if the field value is optional. If the field is not of type
/// `Option<T>` consider using the [`invalid_value`] method instead.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
/// [`FieldName`]: struct.FieldName.html
/// [`invalid_value`]: fn.invalid_value.html
pub fn invalid_optional_value(
    code: impl Into<Cow<'static, str>>,
    field_name: impl Into<FieldName>,
    actual: Option<Value>,
    expected: Option<Value>,
) -> ConstraintViolation {
    ConstraintViolation::Field(InvalidValue {
        code: code.into(),
        field: Field {
            name: field_name.into().unwrap(),
            actual,
            expected,
        },
    })
}

/// Convenience function to construct a [`ConstraintViolation`] for a validation
/// performed in the [`RelatedFields`] context.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
/// [`RelatedFields`]: struct.RelatedFields.html
pub fn invalid_relation(
    code: impl Into<Cow<'static, str>>,
    field_name1: impl Into<Cow<'static, str>>,
    field_value1: impl Into<Value>,
    field_name2: impl Into<Cow<'static, str>>,
    field_value2: impl Into<Value>,
) -> ConstraintViolation {
    ConstraintViolation::Relation(InvalidRelation {
        code: code.into(),
        field1: Field {
            name: field_name1.into(),
            actual: Some(field_value1.into()),
            expected: None,
        },
        field2: Field {
            name: field_name2.into(),
            actual: Some(field_value2.into()),
            expected: None,
        },
    })
}

/// Convenience function to construct a [`ConstraintViolation`] for a validation
/// performed in the [`State`] context.
///
/// [`ConstraintViolation`]: enum.ConstraintViolation.html
/// [`State`]: struct.State.html
pub fn invalid_state(
    code: impl Into<Cow<'static, str>>,
    params: impl IntoIterator<Item = Parameter>,
) -> ConstraintViolation {
    ConstraintViolation::State(InvalidState {
        code: code.into(),
        params: Vec::from_iter(params.into_iter()),
    })
}

/// Convenience function to construct a [`Parameter`].
///
/// [`Parameter`]: struct.Parameter.html
pub fn param(name: impl Into<Cow<'static, str>>, value: impl Into<Value>) -> Parameter {
    Parameter {
        name: name.into(),
        value: value.into(),
    }
}

#[cfg(test)]
mod tests;