Debian Codegraph @

src/keywords/max_items.rs

raw symbols SCIP
1 #![allow(clippy::float_cmp, clippy::cast_sign_loss)]
2
3 use crate::{
4 compiler,
5 error::ValidationError,
6 keywords::{helpers::fail_on_non_positive_integer, CompilationResult},
7 paths::{LazyLocation, Location},
8 validator::{Validate, ValidationContext},
9 };
10 use serde_json::{Map, Value};
11
12 pub(crate) struct MaxItemsValidator {
13 limit: u64,
14 location: Location,
15 }
16
17 impl MaxItemsValidator {
18 #[inline]
19 pub(crate) fn compile<'a>(
20 ctx: &compiler::Context,
21 schema: &'a Value,
22 location: Location,
23 ) -> CompilationResult<'a> {
24 if let Some(limit) = schema.as_u64() {
25 return Ok(Box::new(MaxItemsValidator { limit, location }));
26 }
27 if ctx.supports_integer_valued_numbers() {
28 if let Some(limit) = schema.as_f64() {
29 if limit.trunc() == limit {
30 #[allow(clippy::cast_possible_truncation)]
31 return Ok(Box::new(MaxItemsValidator {
32 // NOTE: Imprecise cast as big integers are not supported yet
33 limit: limit as u64,
34 location,
35 }));
36 }
37 }
38 }
39 Err(fail_on_non_positive_integer(schema, location))
40 }
41 }
42
43 impl Validate for MaxItemsValidator {
44 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
45 if let Value::Array(items) = instance {
46 if (items.len() as u64) > self.limit {
47 return false;
48 }
49 }
50 true
51 }
52
53 fn validate<'i>(
54 &self,
55 instance: &'i Value,
56 location: &LazyLocation,
57 _ctx: &mut ValidationContext,
58 ) -> Result<(), ValidationError<'i>> {
59 if let Value::Array(items) = instance {
60 if (items.len() as u64) > self.limit {
61 return Err(ValidationError::max_items(
62 self.location.clone(),
63 location.into(),
64 instance,
65 self.limit,
66 ));
67 }
68 }
69 Ok(())
70 }
71 }
72
73 #[inline]
74 pub(crate) fn compile<'a>(
75 ctx: &compiler::Context,
76 _: &Map<String, Value>,
77 schema: &'a Value,
78 ) -> Option<CompilationResult<'a>> {
79 let location = ctx.location().join("maxItems");
80 Some(MaxItemsValidator::compile(ctx, schema, location))
81 }
82
83 #[cfg(test)]
84 mod tests {
85 use crate::tests_util;
86 use serde_json::json;
87
88 #[test]
89 fn location() {
90 tests_util::assert_schema_location(&json!({"maxItems": 1}), &json!([1, 2]), "/maxItems");
91 }
92 }