| 1 | use crate::{ |
| 2 | compiler, |
| 3 | error::ValidationError, |
| 4 | evaluation::ErrorDescription, |
| 5 | keywords::CompilationResult, |
| 6 | node::SchemaNode, |
| 7 | paths::{LazyLocation, Location}, |
| 8 | types::JsonType, |
| 9 | validator::{EvaluationResult, Validate, ValidationContext}, |
| 10 | }; |
| 11 | use serde_json::{Map, Value}; |
| 12 | |
| 13 | pub(crate) struct OneOfValidator { |
| 14 | schemas: Vec<SchemaNode>, |
| 15 | location: Location, |
| 16 | } |
| 17 | |
| 18 | impl OneOfValidator { |
| 19 | #[inline] |
| 20 | pub(crate) fn compile<'a>(ctx: &compiler::Context, schema: &'a Value) -> CompilationResult<'a> { |
| 21 | if let Value::Array(items) = schema { |
| 22 | let ctx = ctx.new_at_location("oneOf"); |
| 23 | let mut schemas = Vec::with_capacity(items.len()); |
| 24 | for (idx, item) in items.iter().enumerate() { |
| 25 | let ctx = ctx.new_at_location(idx); |
| 26 | let node = compiler::compile(&ctx, ctx.as_resource_ref(item))?; |
| 27 | schemas.push(node); |
| 28 | } |
| 29 | Ok(Box::new(OneOfValidator { |
| 30 | schemas, |
| 31 | location: ctx.location().clone(), |
| 32 | })) |
| 33 | } else { |
| 34 | Err(ValidationError::single_type_error( |
| 35 | Location::new(), |
| 36 | ctx.location().clone(), |
| 37 | schema, |
| 38 | JsonType::Array, |
| 39 | )) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn get_first_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> Option<usize> { |
| 44 | let mut first_valid_idx = None; |
| 45 | for (idx, node) in self.schemas.iter().enumerate() { |
| 46 | if node.is_valid(instance, ctx) { |
| 47 | first_valid_idx = Some(idx); |
| 48 | break; |
| 49 | } |
| 50 | } |
| 51 | first_valid_idx |
| 52 | } |
| 53 | |
| 54 | #[allow(clippy::arithmetic_side_effects)] |
| 55 | fn are_others_valid(&self, instance: &Value, idx: usize, ctx: &mut ValidationContext) -> bool { |
| 56 | self.schemas |
| 57 | .iter() |
| 58 | .skip(idx + 1) |
| 59 | .any(|n| n.is_valid(instance, ctx)) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl Validate for OneOfValidator { |
| 64 | fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool { |
| 65 | let first_valid_idx = self.get_first_valid(instance, ctx); |
| 66 | first_valid_idx.is_some_and(|idx| !self.are_others_valid(instance, idx, ctx)) |
| 67 | } |
| 68 | |
| 69 | fn validate<'i>( |
| 70 | &self, |
| 71 | instance: &'i Value, |
| 72 | location: &LazyLocation, |
| 73 | ctx: &mut ValidationContext, |
| 74 | ) -> Result<(), ValidationError<'i>> { |
| 75 | let first_valid_idx = self.get_first_valid(instance, ctx); |
| 76 | if let Some(idx) = first_valid_idx { |
| 77 | if self.are_others_valid(instance, idx, ctx) { |
| 78 | return Err(ValidationError::one_of_multiple_valid( |
| 79 | self.location.clone(), |
| 80 | location.into(), |
| 81 | instance, |
| 82 | self.schemas |
| 83 | .iter() |
| 84 | .map(|schema| schema.iter_errors(instance, location, ctx).collect()) |
| 85 | .collect(), |
| 86 | )); |
| 87 | } |
| 88 | Ok(()) |
| 89 | } else { |
| 90 | Err(ValidationError::one_of_not_valid( |
| 91 | self.location.clone(), |
| 92 | location.into(), |
| 93 | instance, |
| 94 | self.schemas |
| 95 | .iter() |
| 96 | .map(|schema| schema.iter_errors(instance, location, ctx).collect()) |
| 97 | .collect(), |
| 98 | )) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | fn evaluate( |
| 103 | &self, |
| 104 | instance: &Value, |
| 105 | location: &LazyLocation, |
| 106 | ctx: &mut ValidationContext, |
| 107 | ) -> EvaluationResult { |
| 108 | let total = self.schemas.len(); |
| 109 | let mut failures = Vec::with_capacity(total); |
| 110 | let mut iter = self.schemas.iter(); |
| 111 | while let Some(node) = iter.next() { |
| 112 | let child = node.evaluate_instance(instance, location, ctx); |
| 113 | if child.valid { |
| 114 | let mut successes = Vec::with_capacity(total.saturating_sub(failures.len())); |
| 115 | successes.push(child); |
| 116 | for node in iter { |
| 117 | let next = node.evaluate_instance(instance, location, ctx); |
| 118 | if next.valid { |
| 119 | successes.push(next); |
| 120 | } |
| 121 | } |
| 122 | return match successes.len() { |
| 123 | 1 => EvaluationResult::from(successes.remove(0)), |
| 124 | _ => EvaluationResult::Invalid { |
| 125 | errors: vec![ErrorDescription::new( |
| 126 | "oneOf", |
| 127 | "more than one subschema succeeded".to_string(), |
| 128 | )], |
| 129 | children: successes, |
| 130 | annotations: None, |
| 131 | }, |
| 132 | }; |
| 133 | } |
| 134 | failures.push(child); |
| 135 | } |
| 136 | EvaluationResult::Invalid { |
| 137 | errors: Vec::new(), |
| 138 | children: failures, |
| 139 | annotations: None, |
| 140 | } |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | #[inline] |
| 145 | pub(crate) fn compile<'a>( |
| 146 | ctx: &compiler::Context, |
| 147 | _: &'a Map<String, Value>, |
| 148 | schema: &'a Value, |
| 149 | ) -> Option<CompilationResult<'a>> { |
| 150 | Some(OneOfValidator::compile(ctx, schema)) |
| 151 | } |
| 152 | |
| 153 | #[cfg(test)] |
| 154 | mod tests { |
| 155 | use crate::tests_util; |
| 156 | use serde_json::{json, Value}; |
| 157 | use test_case::test_case; |
| 158 | |
| 159 | #[test_case(&json!({"oneOf": [{"type": "string"}]}), &json!(0), "/oneOf")] |
| 160 | #[test_case(&json!({"oneOf": [{"type": "string"}, {"maxLength": 3}]}), &json!(""), "/oneOf")] |
| 161 | fn location(schema: &Value, instance: &Value, expected: &str) { |
| 162 | tests_util::assert_schema_location(schema, instance, expected); |
| 163 | } |
| 164 | } |