| 1 | use crate::{ |
| 2 | paths::{LazyLocation, Location}, |
| 3 | thread::ThreadBound, |
| 4 | validator::{Validate, ValidationContext}, |
| 5 | ValidationError, |
| 6 | }; |
| 7 | use serde_json::{Map, Value}; |
| 8 | |
| 9 | pub(crate) struct CustomKeyword { |
| 10 | inner: Box<dyn Keyword>, |
| 11 | } |
| 12 | |
| 13 | impl CustomKeyword { |
| 14 | pub(crate) fn new(inner: Box<dyn Keyword>) -> Self { |
| 15 | Self { inner } |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | impl Validate for CustomKeyword { |
| 20 | fn validate<'i>( |
| 21 | &self, |
| 22 | instance: &'i Value, |
| 23 | location: &LazyLocation, |
| 24 | _ctx: &mut ValidationContext, |
| 25 | ) -> Result<(), ValidationError<'i>> { |
| 26 | self.inner.validate(instance, location) |
| 27 | } |
| 28 | |
| 29 | fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool { |
| 30 | self.inner.is_valid(instance) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | /// Trait that allows implementing custom validation for keywords. |
| 35 | pub trait Keyword: ThreadBound { |
| 36 | /// Validate instance according to a custom specification. |
| 37 | /// |
| 38 | /// A custom keyword validator may be used when a validation that cannot be |
| 39 | /// easily or efficiently expressed in JSON schema. |
| 40 | /// |
| 41 | /// The custom validation is applied in addition to the JSON schema validation. |
| 42 | /// |
| 43 | /// # Errors |
| 44 | /// |
| 45 | /// Returns an error describing why `instance` violates the custom keyword semantics. |
| 46 | fn validate<'i>( |
| 47 | &self, |
| 48 | instance: &'i Value, |
| 49 | location: &LazyLocation, |
| 50 | ) -> Result<(), ValidationError<'i>>; |
| 51 | /// Validate instance and return a boolean result. |
| 52 | /// |
| 53 | /// Could be potentilly faster than [`Keyword::validate`] method. |
| 54 | fn is_valid(&self, instance: &Value) -> bool; |
| 55 | } |
| 56 | |
| 57 | pub(crate) trait KeywordFactory: ThreadBound { |
| 58 | fn init<'a>( |
| 59 | &self, |
| 60 | parent: &'a Map<String, Value>, |
| 61 | schema: &'a Value, |
| 62 | path: Location, |
| 63 | ) -> Result<Box<dyn Keyword>, ValidationError<'a>>; |
| 64 | } |
| 65 | |
| 66 | impl<F> KeywordFactory for F |
| 67 | where |
| 68 | F: for<'a> Fn( |
| 69 | &'a Map<String, Value>, |
| 70 | &'a Value, |
| 71 | Location, |
| 72 | ) -> Result<Box<dyn Keyword>, ValidationError<'a>> |
| 73 | + ThreadBound, |
| 74 | { |
| 75 | fn init<'a>( |
| 76 | &self, |
| 77 | parent: &'a Map<String, Value>, |
| 78 | schema: &'a Value, |
| 79 | path: Location, |
| 80 | ) -> Result<Box<dyn Keyword>, ValidationError<'a>> { |
| 81 | self(parent, schema, path) |
| 82 | } |
| 83 | } |