validify/validation/
length.rs

1use crate::traits::Length;
2
3/// Validates the length of the value given.
4///
5/// If the validator has `equal` set, it will ignore any `min` and `max` value.
6///
7/// See the [Length] trait for more details.
8pub fn validate_length<T: Length>(
9    value: T,
10    min: Option<usize>,
11    max: Option<usize>,
12    equal: Option<usize>,
13) -> bool {
14    let val_length = value.length();
15
16    if let Some(eq) = equal {
17        return val_length == eq;
18    } else {
19        if let Some(m) = min {
20            if val_length < m {
21                return false;
22            }
23        }
24        if let Some(m) = max {
25            if val_length > m {
26                return false;
27            }
28        }
29    }
30
31    true
32}
33
34#[cfg(test)]
35mod tests {
36    use std::borrow::Cow;
37
38    use super::validate_length;
39
40    #[test]
41    fn test_validate_length_equal_overrides_min_max() {
42        assert!(validate_length("hello", Some(1), Some(2), Some(5)));
43    }
44
45    #[test]
46    fn test_validate_length_string_min_max() {
47        assert!(validate_length("hello", Some(1), Some(10), None));
48    }
49
50    #[test]
51    fn test_validate_length_string_min_only() {
52        assert!(!validate_length("hello", Some(10), None, None));
53    }
54
55    #[test]
56    fn test_validate_length_string_max_only() {
57        assert!(!validate_length("hello", None, Some(1), None));
58    }
59
60    #[test]
61    fn test_validate_length_cow() {
62        let test: Cow<'static, str> = "hello".into();
63        assert!(validate_length(test, None, None, Some(5)));
64
65        let test: Cow<'static, str> = String::from("hello").into();
66        assert!(validate_length(test, None, None, Some(5)));
67    }
68
69    #[test]
70    fn test_validate_length_vec() {
71        assert!(validate_length(vec![1, 2, 3], None, None, Some(3)));
72    }
73
74    #[test]
75    fn test_validate_length_unicode_chars() {
76        assert!(validate_length("日本", None, None, Some(2)));
77    }
78}