serde_valid/validation/array/
max_items.rs

1/// Max length validation of the array items.
2///
3/// See <https://json-schema.org/understanding-json-schema/reference/array.html#length>
4///
5/// ```rust
6/// use serde_json::json;
7/// use serde_valid::{Validate, ValidateMaxItems};
8///
9/// struct MyType(Vec<i32>);
10///
11/// impl ValidateMaxItems for MyType {
12///     fn validate_max_items(
13///         &self,
14///         max_items: usize,
15///     ) -> Result<(), serde_valid::MaxItemsError> {
16///         self.0.validate_max_items(max_items)
17///     }
18/// }
19///
20/// #[derive(Validate)]
21/// struct TestStruct {
22///     #[validate(max_items = 2)]
23///     val: MyType,
24/// }
25///
26/// let s = TestStruct {
27///     val: MyType(vec![1, 2, 3]),
28/// };
29///
30/// assert_eq!(
31///     s.validate().unwrap_err().to_string(),
32///     json!({
33///         "errors": [],
34///         "properties": {
35///             "val": {
36///                 "errors": ["The length of the items must be `<= 2`."]
37///             }
38///         }
39///     })
40///     .to_string()
41/// );
42/// ```
43pub trait ValidateMaxItems {
44    fn validate_max_items(&self, max_items: usize) -> Result<(), crate::MaxItemsError>;
45}
46
47impl<T> ValidateMaxItems for Vec<T> {
48    fn validate_max_items(&self, max_items: usize) -> Result<(), crate::MaxItemsError> {
49        if max_items >= self.len() {
50            Ok(())
51        } else {
52            Err(crate::MaxItemsError::new(max_items))
53        }
54    }
55}
56
57impl<T, const N: usize> ValidateMaxItems for [T; N] {
58    fn validate_max_items(&self, max_items: usize) -> Result<(), crate::MaxItemsError> {
59        if max_items >= self.len() {
60            Ok(())
61        } else {
62            Err(crate::MaxItemsError::new(max_items))
63        }
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn test_validate_array_vec_type() {
73        assert!(ValidateMaxItems::validate_max_items(&vec!['a', 'b', 'c'], 3).is_ok());
74    }
75
76    #[test]
77    fn test_validate_array_max_items_array_type() {
78        assert!(ValidateMaxItems::validate_max_items(&['a', 'b', 'c'], 3).is_ok());
79    }
80
81    #[test]
82    fn test_validate_array_max_items_is_true() {
83        assert!(ValidateMaxItems::validate_max_items(&[1, 2, 3], 3).is_ok());
84    }
85
86    #[test]
87    fn test_validate_array_max_items_is_false() {
88        assert!(ValidateMaxItems::validate_max_items(&[1, 2, 3], 2).is_err());
89    }
90}