protocheck_core/validators/
maps.rs1use std::{collections::HashMap, sync::LazyLock};
2
3use crate::{
4 field_data::FieldContext,
5 protovalidate::{FieldPathElement, Violation},
6 validators::static_data::base_violations::create_violation,
7 ProtoType,
8};
9
10pub fn min_pairs<K, V>(
11 field_context: &FieldContext,
12 value: &HashMap<K, V>,
13 min_pairs: u64,
14 error_message: &'static str,
15) -> Result<(), Violation> {
16 let check = value.len() >= min_pairs as usize;
17
18 if check {
19 Ok(())
20 } else {
21 Err(create_violation(
22 field_context,
23 &MAP_MIN_PAIRS_VIOLATION,
24 "map.min_pairs",
25 error_message,
26 ))
27 }
28}
29
30pub fn max_pairs<K, V>(
31 field_context: &FieldContext,
32 value: &HashMap<K, V>,
33 max_pairs: u64,
34 error_message: &'static str,
35) -> Result<(), Violation> {
36 let check = value.len() <= max_pairs as usize;
37
38 if check {
39 Ok(())
40 } else {
41 Err(create_violation(
42 field_context,
43 &MAP_MAX_PAIRS_VIOLATION,
44 "map.max_pairs",
45 error_message,
46 ))
47 }
48}
49
50static MAP_MIN_PAIRS_VIOLATION: LazyLock<Vec<FieldPathElement>> = LazyLock::new(|| {
51 vec![
52 FieldPathElement {
53 field_name: Some("map".to_string()),
54 field_number: Some(19),
55 field_type: Some(ProtoType::Message as i32),
56 subscript: None,
57 key_type: None,
58 value_type: None,
59 },
60 FieldPathElement {
61 field_name: Some("min_pairs".to_string()),
62 field_number: Some(1),
63 field_type: Some(ProtoType::Uint64 as i32),
64 key_type: None,
65 value_type: None,
66 subscript: None,
67 },
68 ]
69});
70
71static MAP_MAX_PAIRS_VIOLATION: LazyLock<Vec<FieldPathElement>> = LazyLock::new(|| {
72 vec![
73 FieldPathElement {
74 field_name: Some("map".to_string()),
75 field_number: Some(19),
76 field_type: Some(ProtoType::Message as i32),
77 subscript: None,
78 key_type: None,
79 value_type: None,
80 },
81 FieldPathElement {
82 field_name: Some("max_pairs".to_string()),
83 field_number: Some(2),
84 field_type: Some(ProtoType::Uint64 as i32),
85 key_type: None,
86 value_type: None,
87 subscript: None,
88 },
89 ]
90});