Debian Codegraph @

src/keywords/not.rs

raw symbols SCIP
1 use crate::{
2 compiler,
3 error::ValidationError,
4 keywords::CompilationResult,
5 node::SchemaNode,
6 paths::LazyLocation,
7 validator::{Validate, ValidationContext},
8 };
9 use serde_json::{Map, Value};
10
11 pub(crate) struct NotValidator {
12 // needed only for error representation
13 original: Value,
14 node: SchemaNode,
15 }
16
17 impl NotValidator {
18 #[inline]
19 pub(crate) fn compile<'a>(ctx: &compiler::Context, schema: &'a Value) -> CompilationResult<'a> {
20 let ctx = ctx.new_at_location("not");
21 Ok(Box::new(NotValidator {
22 original: schema.clone(),
23 node: compiler::compile(&ctx, ctx.as_resource_ref(schema))?,
24 }))
25 }
26 }
27
28 impl Validate for NotValidator {
29 fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool {
30 !self.node.is_valid(instance, ctx)
31 }
32
33 fn validate<'i>(
34 &self,
35 instance: &'i Value,
36 location: &LazyLocation,
37 ctx: &mut ValidationContext,
38 ) -> Result<(), ValidationError<'i>> {
39 if self.is_valid(instance, ctx) {
40 Ok(())
41 } else {
42 Err(ValidationError::not(
43 self.node.location().clone(),
44 location.into(),
45 instance,
46 self.original.clone(),
47 ))
48 }
49 }
50 }
51
52 #[inline]
53 pub(crate) fn compile<'a>(
54 ctx: &compiler::Context,
55 _: &'a Map<String, Value>,
56 schema: &'a Value,
57 ) -> Option<CompilationResult<'a>> {
58 Some(NotValidator::compile(ctx, schema))
59 }
60
61 #[cfg(test)]
62 mod tests {
63 use crate::tests_util;
64 use serde_json::json;
65
66 #[test]
67 fn location() {
68 tests_util::assert_schema_location(
69 &json!({"not": {"type": "string"}}),
70 &json!("foo"),
71 "/not",
72 );
73 }
74 }