| 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 MinPropertiesValidator { |
| 13 | limit: u64, |
| 14 | location: Location, |
| 15 | } |
| 16 | |
| 17 | impl MinPropertiesValidator { |
| 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(MinPropertiesValidator { 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(MinPropertiesValidator { |
| 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 MinPropertiesValidator { |
| 44 | fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool { |
| 45 | if let Value::Object(item) = instance { |
| 46 | if (item.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::Object(item) = instance { |
| 60 | if (item.len() as u64) < self.limit { |
| 61 | return Err(ValidationError::min_properties( |
| 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 | _: &'a Map<String, Value>, |
| 77 | schema: &'a Value, |
| 78 | ) -> Option<CompilationResult<'a>> { |
| 79 | let location = ctx.location().join("minProperties"); |
| 80 | Some(MinPropertiesValidator::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( |
| 91 | &json!({"minProperties": 2}), |
| 92 | &json!({"a": 1}), |
| 93 | "/minProperties", |
| 94 | ); |
| 95 | } |
| 96 | } |