Debian Codegraph @

src/validator.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //! Building a JSON Schema validator.
2 //! The main idea is to create a tree from the input JSON Schema. This tree will contain
3 //! everything needed to perform such validation in runtime.
4 use craterust-analyzer cargo jsonschema 0.37.4 crate/::{
5 errorrust-analyzer cargo jsonschema 0.37.4 error/::{errorrust-analyzer cargo jsonschema 0.37.4 error/error()., no_errorrust-analyzer cargo jsonschema 0.37.4 error/no_error()., ErrorIteratorrust-analyzer cargo jsonschema 0.37.4 error/ErrorIterator#},
6 evaluationrust-analyzer cargo jsonschema 0.37.4 evaluation/::{Annotationsrust-analyzer cargo jsonschema 0.37.4 evaluation/Annotations#, ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#, Evaluationrust-analyzer cargo jsonschema 0.37.4 evaluation/Evaluation#, EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#},
7 noderust-analyzer cargo jsonschema 0.37.4 node/::SchemaNoderust-analyzer cargo jsonschema 0.37.4 node/SchemaNode#,
8 pathsrust-analyzer cargo jsonschema 0.37.4 paths/::LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
9 threadrust-analyzer cargo jsonschema 0.37.4 thread/::ThreadBoundrust-analyzer cargo jsonschema 0.37.4 thread/ThreadBound#,
10 Draftrust-analyzer cargo referencing 0.37.4 specification/Draft#, ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#, ValidationOptionsrust-analyzer cargo jsonschema 0.37.4 options/ValidationOptions#,
11 };
12 use serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::Valuerust-analyzer cargo serde_json 1.0.145 value/Value#;
13
14 /// Tracks `(node_id, instance_ptr)` pairs to detect cycles in circular `$ref` chains.
15 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Defaultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core default/Default:)]
16 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) struct ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext# {
17 validatingrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#validating.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<(usize, usize)>,
18 }
19
20 impl ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext# {
21 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]new().() -> Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext] {
22 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]::defaultrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext][Default]default().()
23 }
24
25 /// Returns `true` if cycle detected, `false` otherwise (and adds pair to stack).
26 #[inline]
27 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn enterrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]enter().(&mut self, node_id: usize, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> bool {
28 let key = (node_id, stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::ptrrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ptr/::from_refrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ptr/from_ref().::<Valuerust-analyzer cargo serde_json 1.0.145 value/Value#>(instance) as usize);
29 if self.validatingrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#validating..containsrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/impl#[`[T]`]contains().(&key) {
30 return true;
31 }
32 self.validatingrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#validating..pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(key);
33 false
34 }
35
36 #[inline]
37 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn exitrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]exit().(&mut self, node_id: usize, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) {
38 let popped = self.validatingrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#validating..poprust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]pop().();
39 debug_assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/debug_assert_eq!!(
40 popped,
41 Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#((node_id, stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::ptrrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ptr/::from_refrust-analyzer cargo core https://github.com/rust-lang/rust/library/core ptr/from_ref().::<Valuerust-analyzer cargo serde_json 1.0.145 value/Value#>(instance) as usize)),
42 "ValidationContext::exit called out of order"
43 );
44 }
45 }
46
47 /// The Validate trait represents a predicate over some JSON value. Some validators are very simple
48 /// predicates such as "a value which is a string", whereas others may be much more complex,
49 /// consisting of several other validators composed together in various ways.
50 ///
51 /// Much of the time all an application cares about is whether the predicate returns true or false,
52 /// in that case the `is_valid` function is sufficient. Sometimes applications will want more
53 /// detail about why a schema has failed, in which case the `validate` method can be used to
54 /// iterate over the errors produced by this validator. Finally, applications may be interested in
55 /// annotations produced by schemas over valid results, in this case the `evaluate` method can be used
56 /// to obtain this information.
57 ///
58 /// If you are implementing `Validate` it is often sufficient to implement `validate` and
59 /// `is_valid`. `evaluate` is only necessary for validators which compose other validators. See the
60 /// documentation for `evaluate` for more information.
61 ///
62 /// All methods accept a `ValidationContext` parameter for cycle detection in circular `$ref`
63 /// chains. Simple validators that don't recurse into child schemas can ignore this parameter.
64 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) trait Validaterust-analyzer cargo jsonschema 0.37.4 validator/Validate#: ThreadBoundrust-analyzer cargo jsonschema 0.37.4 thread/ThreadBound# {
65 fn iter_errorsrust-analyzer cargo jsonschema 0.37.4 validator/Validate#iter_errors().<'i>(
66 &self,
67 instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
68 location: &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
69 ctx: &mut ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#,
70 ) -> ErrorIteratorrust-analyzer cargo jsonschema 0.37.4 error/ErrorIterator#<'i> {
71 match self.validaterust-analyzer cargo jsonschema 0.37.4 validator/Validate#validate().(instance, location, ctx) {
72 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(()) => no_errorrust-analyzer cargo jsonschema 0.37.4 error/no_error().(),
73 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(err) => errorrust-analyzer cargo jsonschema 0.37.4 error/error().(err),
74 }
75 }
76
77 fn is_validrust-analyzer cargo jsonschema 0.37.4 validator/Validate#is_valid().(&self, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#, ctx: &mut ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#) -> bool;
78
79 fn validaterust-analyzer cargo jsonschema 0.37.4 validator/Validate#validate().<'i>(
80 &self,
81 instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
82 location: &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
83 ctx: &mut ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#,
84 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'i>>;
85
86 fn evaluaterust-analyzer cargo jsonschema 0.37.4 validator/Validate#evaluate().(
87 &self,
88 instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
89 location: &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
90 ctx: &mut ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#,
91 ) -> EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
92 let errors: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#> = self
93 .iter_errorsrust-analyzer cargo jsonschema 0.37.4 validator/Validate#iter_errors().(instance, location, ctx)
94 .maprust-analyzer cargo core https://github.com/rust-lang/rust/library/core iter/traits/iterator/Iterator#map().(|e| ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#::from_validation_errorrust-analyzer cargo jsonschema 0.37.4 evaluation/impl#[ErrorDescription]from_validation_error().(&e))
95 .collectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core iter/traits/iterator/Iterator#collect().();
96 if errors.is_emptyrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]is_empty().() {
97 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::valid_emptyrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]valid_empty().()
98 } else {
99 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::invalid_emptyrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]invalid_empty().(errors)
100 }
101 }
102 }
103
104 /// The result of evaluating a validator against an instance. This is a "partial" result because it does not include information about
105 /// where the error or annotation occurred.
106 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(PartialEqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/PartialEq:)]
107 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) enum EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
108 Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# {
109 /// Annotations produced by this validator
110 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Annotationsrust-analyzer cargo jsonschema 0.37.4 evaluation/Annotations#>,
111 /// Children evaluation nodes
112 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#children.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#>,
113 },
114 Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# {
115 /// Errors which caused this schema to be invalid
116 errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#>,
117 /// Children evaluation nodes
118 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#children.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#>,
119 /// Potential annotations that should be reported as dropped on failure
120 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations.: Optionrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#<Annotationsrust-analyzer cargo jsonschema 0.37.4 evaluation/Annotations#>,
121 },
122 }
123
124 impl EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
125 /// Create an empty `EvaluationResult` which is valid
126 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn valid_emptyrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]valid_empty().() -> EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
127 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# {
128 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
129 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#children.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(),
130 }
131 }
132
133 /// Create an empty `EvaluationResult` which is invalid
134 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn invalid_emptyrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]invalid_empty().(errors: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#>) -> EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
135 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# {
136 errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors.,
137 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#children.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(),
138 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
139 }
140 }
141
142 /// Set the annotation that will be returned for the current validator. If this
143 /// `EvaluationResult` is invalid then this method does nothing
144 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn annotaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]annotate().(&mut self, new_annotations: Annotationsrust-analyzer cargo jsonschema 0.37.4 evaluation/Annotations#) {
145 match self {
146 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]::Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# { annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations., .. } | Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# { annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations., .. } => {
147 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&mut T`][Deref]deref().annotations = Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(new_annotations);
148 }
149 }
150 }
151
152 /// Set the error that will be returned for the current validator. If this
153 /// `EvaluationResult` is valid then this method converts this application into
154 /// `EvaluationResult::Invalid`
155 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn mark_erroredrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]mark_errored().(&mut self, error: ErrorDescriptionrust-analyzer cargo jsonschema 0.37.4 evaluation/ErrorDescription#) {
156 match self {
157 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# { errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors., .. } => errors.pushrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]push().(error),
158 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]::Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# {
159 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations.,
160 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#children.,
161 } => {
162 *rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/deref/impl#[`&mut T`][Deref]deref().self = Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# {
163 errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors.: vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/vec!![error],
164 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#children.: stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::memrust-analyzer cargo core https://github.com/rust-lang/rust/library/core mem/::takerust-analyzer cargo core https://github.com/rust-lang/rust/library/core mem/take().(children),
165 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations.: annotations.takerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]take().(),
166 }
167 }
168 }
169 }
170
171 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) fn from_childrenrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult]from_children().(children: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#>) -> EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
172 if children.iterrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/impl#[`[T]`]iter().().anyrust-analyzer cargo core https://github.com/rust-lang/rust/library/core slice/iter/impl#[`Iter<'a, T>`][Iterator]any().(|node| !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().node.validrust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#valid.) {
173 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# {
174 errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(),
175 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#children.,
176 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
177 }
178 } else {
179 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# {
180 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
181 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#children.,
182 }
183 }
184 }
185 }
186
187 impl Fromrust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/From#<EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#> for EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult# {
188 fn fromrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult][`From<EvaluationNode>`]from().(node: EvaluationNoderust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#) -> Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[EvaluationResult][`From<EvaluationNode>`] {
189 if node.validrust-analyzer cargo jsonschema 0.37.4 evaluation/EvaluationNode#valid. {
190 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Validrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid# {
191 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
192 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Valid#children.: vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/vec!![node],
193 }
194 } else {
195 EvaluationResultrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#::Invalidrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid# {
196 errorsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#errors.: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T>`]new().(),
197 childrenrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#children.: vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc macros/vec!![node],
198 annotationsrust-analyzer cargo jsonschema 0.37.4 validator/EvaluationResult#Invalid#annotations.: Nonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#None#,
199 }
200 }
201 }
202 }
203
204 /// A compiled JSON Schema validator.
205 ///
206 /// This structure represents a JSON Schema that has been parsed and compiled into
207 /// an efficient internal representation for validation. It contains the root node
208 /// of the schema tree and the configuration options used during compilation.
209 #[deriverust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/derive:(Clonerust-analyzer cargo core https://github.com/rust-lang/rust/library/core clone/Clone:, Debugrust-analyzer cargo core https://github.com/rust-lang/rust/library/core fmt/macros/Debug:)]
210 pub struct Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator# {
211 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root.: SchemaNoderust-analyzer cargo jsonschema 0.37.4 node/SchemaNode#,
212 pub(craterust-analyzer cargo jsonschema 0.37.4 crate/) draftrust-analyzer cargo jsonschema 0.37.4 validator/Validator#draft.: Draftrust-analyzer cargo referencing 0.37.4 specification/Draft#,
213 }
214
215 impl Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator# {
216 /// Create a default [`ValidationOptions`] for configuring JSON Schema validation.
217 ///
218 /// Use this to set the draft version and other validation parameters.
219 ///
220 /// # Example
221 ///
222 /// ```rust
223 /// # use jsonschema::Draft;
224 /// # let schema = serde_json::json!({});
225 /// let validator = jsonschema::options()
226 /// .with_draft(Draft::Draft7)
227 /// .build(&schema);
228 /// ```
229 #[must_use]
230 pub fn optionsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]options().() -> ValidationOptionsrust-analyzer cargo jsonschema 0.37.4 options/ValidationOptions# {
231 ValidationOptionsrust-analyzer cargo jsonschema 0.37.4 options/ValidationOptions#::defaultrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions][Default]default().()
232 }
233 /// Create a default [`ValidationOptions`] configured for async validation.
234 ///
235 /// Use this to set the draft version and other validation parameters when working
236 /// with schemas that require async reference resolution.
237 ///
238 /// # Example
239 ///
240 /// ```rust
241 /// # use serde_json::json;
242 /// # use jsonschema::Draft;
243 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
244 /// let schema = json!({
245 /// "$ref": "https://example.com/schema.json"
246 /// });
247 ///
248 /// let validator = jsonschema::async_options()
249 /// .with_draft(Draft::Draft202012)
250 /// .build(&schema)
251 /// .await?;
252 /// # Ok(())
253 /// # }
254 /// ```
255 ///
256 /// For sync validation, use [`options()`](crate::options()) instead.
257 #[cfg(feature = "resolve-async")]
258 #[must_use]
259 pub fn async_optionsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]async_options().() -> ValidationOptionsrust-analyzer cargo jsonschema 0.37.4 options/ValidationOptions#<stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::Arcrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc sync/Arc#<dyn referencingrust-analyzer cargo referencing 0.37.4 crate/::AsyncRetrieverust-analyzer cargo referencing 0.37.4 retriever/AsyncRetrieve#>> {
260 ValidationOptionsrust-analyzer cargo jsonschema 0.37.4 options/ValidationOptions#::defaultrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<Arc<dyn AsyncRetrieve + 'static>>`][Default]default().()
261 }
262 /// Create a validator using the default options.
263 ///
264 /// # Errors
265 ///
266 /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
267 pub fn newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]new().(schema: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator#, ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'static>> {
268 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]::optionsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]options().().buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(schema)
269 }
270 /// Create a validator using the default async options.
271 #[cfg(feature = "resolve-async")]
272 ///
273 /// # Errors
274 ///
275 /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
276 pub async fn async_newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]async_new().(schema: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator#, ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'static>> {
277 Selfrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]::async_optionsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]async_options().().buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<Arc<dyn AsyncRetrieve + 'static>>`]build().(schema).rust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().awaitrust-analyzer cargo core https://github.com/rust-lang/rust/library/core future/future/Future#poll().
278 }
279 /// Validate `instance` against `schema` and return the first error if any.
280 ///
281 /// # Errors
282 ///
283 /// Returns the first [`ValidationError`] describing why `instance` does not satisfy the schema.
284 #[inline]
285 pub fn validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().<'i>(&self, instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'i>> {
286 let mut ctx = ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#::newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]new().();
287 self.rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root..validaterust-analyzer cargo jsonschema 0.37.4 node/impl#[SchemaNode][Validate]validate().(instance, &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[`LazyLocation<'a, '_>`]new().(), &mut ctx)
288 }
289 /// Run validation against `instance` and return an iterator over [`ValidationError`] in the error case.
290 #[inline]
291 #[must_use]
292 pub fn iter_errorsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]iter_errors().<'i>(&'i self, instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> ErrorIteratorrust-analyzer cargo jsonschema 0.37.4 error/ErrorIterator#<'i> {
293 let mut ctx = ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#::newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]new().();
294 self.rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root.
295 .iter_errorsrust-analyzer cargo jsonschema 0.37.4 node/impl#[SchemaNode][Validate]iter_errors().(instance, &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[`LazyLocation<'a, '_>`]new().(), &mut ctx)
296 }
297 /// Run validation against `instance` but return a boolean result instead of an iterator.
298 /// It is useful for cases, where it is important to only know the fact if the data is valid or not.
299 /// This approach is much faster, than [`Validator::validate`].
300 #[must_use]
301 #[inline]
302 pub fn is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&self, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> bool {
303 let mut ctx = ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#::newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]new().();
304 self.rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root..is_validrust-analyzer cargo jsonschema 0.37.4 node/impl#[SchemaNode][Validate]is_valid().(instance, &mut ctx)
305 }
306 /// Evaluate the schema and expose structured output formats.
307 #[must_use]
308 #[inline]
309 pub fn evaluaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]evaluate().(&self, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> Evaluationrust-analyzer cargo jsonschema 0.37.4 evaluation/Evaluation# {
310 let mut ctx = ValidationContextrust-analyzer cargo jsonschema 0.37.4 validator/ValidationContext#::newrust-analyzer cargo jsonschema 0.37.4 validator/impl#[ValidationContext]new().();
311 let root = self
312 .rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root.
313 .evaluate_instancerust-analyzer cargo jsonschema 0.37.4 node/impl#[SchemaNode]evaluate_instance().(instance, &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[`LazyLocation<'a, '_>`]new().(), &mut ctx);
314 Evaluationrust-analyzer cargo jsonschema 0.37.4 evaluation/Evaluation#::newrust-analyzer cargo jsonschema 0.37.4 evaluation/impl#[Evaluation]new().(root)
315 }
316 /// The [`Draft`] which was used to build this validator.
317 #[must_use]
318 pub fn draftrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]draft().(&self) -> Draftrust-analyzer cargo referencing 0.37.4 specification/Draft# {
319 self.draftrust-analyzer cargo jsonschema 0.37.4 validator/Validator#draft.
320 }
321 }
322
323 #[cfg(test)]
324 mod testsrust-analyzer cargo jsonschema 0.37.4 validator/tests/ {
325 use craterust-analyzer cargo jsonschema 0.37.4 crate/::{
326 errorrust-analyzer cargo jsonschema 0.37.4 error/::ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#,
327 keywordsrust-analyzer cargo jsonschema 0.37.4 keywords/::customrust-analyzer cargo jsonschema 0.37.4 keywords/custom/::Keywordrust-analyzer cargo jsonschema 0.37.4 keywords/custom/Keyword#,
328 pathsrust-analyzer cargo jsonschema 0.37.4 paths/::{LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#, Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#},
329 threadrust-analyzer cargo jsonschema 0.37.4 thread/::ThreadBoundrust-analyzer cargo jsonschema 0.37.4 thread/ThreadBound#,
330 typesrust-analyzer cargo jsonschema 0.37.4 types/::JsonTyperust-analyzer cargo jsonschema 0.37.4 types/JsonType#,
331 Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator#,
332 };
333 use fancy_regexrust-analyzer cargo fancy-regex 0.11.0 crate/::Regexrust-analyzer cargo fancy-regex 0.11.0 Regex#;
334 use num_cmprust-analyzer cargo num-cmp 0.1.0 crate/::NumCmprust-analyzer cargo num-cmp 0.1.0 NumCmp#;
335 use serde_jsonrust-analyzer cargo serde_json 1.0.145 crate/::{jsonrust-analyzer cargo serde_json 1.0.145 macros/json!, Maprust-analyzer cargo serde_json 1.0.145 map/Map#, Valuerust-analyzer cargo serde_json 1.0.145 value/Value#};
336 use stdrust-analyzer cargo std https://github.com/rust-lang/rust/library/std crate/::syncrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/::LazyLockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/lazy_lock/LazyLock#;
337
•338 //disabled, file missing #[cfg(not(target_arch = "wasm32"))]
339 //fn load(path: &str, idx: usize) -> Value {
340 // use std::{fs::File, io::Read, path::Path};
341 // let path = Path::new(path);
342 // let mut file = File::open(path).unwrap();
343 // let mut content = String::new();
344 // file.read_to_string(&mut content).ok().unwrap();
345 // let data: Value = serde_json::from_str(&content).unwrap();
346 // let case = &data.as_array().unwrap()[idx];
347 // case.get("schema").unwrap().clone()
348 //}
349
350 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
351 fn only_keywordrust-analyzer cargo jsonschema 0.37.4 validator/tests/only_keyword().() {
352 // When only one keyword is specified
353 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"type": "string"});
354 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
355 let value1 = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("AB");
356 let value2 = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!(1);
357 // And only this validator
358 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(validator.rootrust-analyzer cargo jsonschema 0.37.4 validator/Validator#root..validatorsrust-analyzer cargo jsonschema 0.37.4 node/impl#[SchemaNode]validators().().lenrust-analyzer cargo jsonschema 0.37.4 node/impl#[`NodeValidatorsIter<'_>`][ExactSizeIterator]len().(), 1);
359 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&value1).is_okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_ok().());
360 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&value2).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
361 }
362
•363 //disabled, file missing #[test]
364 //#[cfg(not(target_arch = "wasm32"))]
365 //fn validate_ref() {
366 // let schema = load("tests/suite/tests/draft7/ref.json", 1);
367 // let value = json!({"bar": 3});
368 // let validator = crate::validator_for(&schema).unwrap();
369 // assert!(validator.validate(&value).is_ok());
370 // let value = json!({"bar": true});
371 // assert!(validator.validate(&value).is_err());
372 //}
373
374 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
375 fn wrong_schema_typerust-analyzer cargo jsonschema 0.37.4 validator/tests/wrong_schema_type().() {
376 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!([1]);
377 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema);
378 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
379 }
380
381 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
382 fn multiple_errorsrust-analyzer cargo jsonschema 0.37.4 validator/tests/multiple_errors().() {
383 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"minProperties": 2, "propertyNames": {"minLength": 3}});
384 let value = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"a": 3});
385 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema).unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
386 let errors: Vecrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/Vec#<_> = validator.iter_errorsrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]iter_errors().(&value).collectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core iter/traits/iterator/Iterator#collect().();
387 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(errors.lenrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`]len().(), 2);
388 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(
389 errors[rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index().0]rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index()..to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().(),
390 r#"{"a":3} has less than 2 properties"#
391 );
392 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(errors[rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index().1]rust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc vec/impl#[`Vec<T, A>`][`Index<I>`]index()..to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().(), r#""a" is shorter than 3 characters"#);
393 }
394
395 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
396 fn custom_keyword_definitionrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_keyword_definition().() {
397 /// Define a custom validator that verifies the object's keys consist of
398 /// only ASCII representable characters.
399 /// NOTE: This could be done with `propertyNames` + `pattern` but will be slower due to
400 /// regex usage.
401 struct CustomObjectValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomObjectValidator#;
402 impl Keywordrust-analyzer cargo jsonschema 0.37.4 keywords/custom/Keyword# for CustomObjectValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomObjectValidator# {
403 fn validaterust-analyzer cargo jsonschema 0.37.4 validator/tests/impl#[CustomObjectValidator][Keyword]validate().<'i>(
404 &self,
405 instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
406 location: &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
407 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'i>> {
408 for key in instance.as_objectrust-analyzer cargo serde_json 1.0.145 value/impl#[Value]as_object().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().().keysrust-analyzer cargo serde_json 1.0.145 map/impl#[`Map<String, Value>`]keys().() {
409 if !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().key.is_asciirust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/impl#[str]is_ascii().() {
410 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#::customrust-analyzer cargo jsonschema 0.37.4 error/impl#[`ValidationError<'a>`]custom().(
411 Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[Location]new().(),
412 location.intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().(),
413 instance,
414 "Key is not ASCII",
415 ));
416 }
417 }
418 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(())
419 }
420
421 fn is_validrust-analyzer cargo jsonschema 0.37.4 validator/tests/impl#[CustomObjectValidator][Keyword]is_valid().(&self, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> bool {
422 for (key, _value) in instance.as_objectrust-analyzer cargo serde_json 1.0.145 value/impl#[Value]as_object().().unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]unwrap().() {
423 if !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().key.is_asciirust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/impl#[str]is_ascii().() {
424 return false;
425 }
426 }
427 true
428 }
429 }
430
431 fn custom_object_type_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_object_type_factory().<'a>(
432 _: &'a Maprust-analyzer cargo serde_json 1.0.145 map/Map#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#, Valuerust-analyzer cargo serde_json 1.0.145 value/Value#>,
433 schema: &'a Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
434 path: Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#,
435 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn Keywordrust-analyzer cargo jsonschema 0.37.4 keywords/custom/Keyword#>, ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'a>> {
436 const EXPECTEDrust-analyzer cargo jsonschema 0.37.4 validator/tests/EXPECTED.: &str = "ascii-keys";
437 if schema.as_strrust-analyzer cargo serde_json 1.0.145 value/impl#[Value]as_str().() rust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`][`PartialEq<Self>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`][`PartialEq<Self>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`][`PartialEq<Self>`]eq().Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(EXPECTEDrust-analyzer cargo jsonschema 0.37.4 validator/tests/EXPECTED.) {
438 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/impl#[`Box<T>`]new().(CustomObjectValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomObjectValidator#))
439 } else {
440 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#::constant_stringrust-analyzer cargo jsonschema 0.37.4 error/impl#[`ValidationError<'a>`]constant_string().(
441 Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[Location]new().(),
442 path,
443 schema,
444 EXPECTEDrust-analyzer cargo jsonschema 0.37.4 validator/tests/EXPECTED.,
445 ))
446 }
447 }
448
449 // Define a JSON schema that enforces the top level object has ASCII keys and has at least 1 property
450 let schema =
451 jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "custom-object-type": "ascii-keys", "type": "object", "minProperties": 1 });
452 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
453 .with_keywordrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_keyword().("custom-object-type", custom_object_type_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_object_type_factory().)
454 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
455 .unwraprust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]unwrap().();
456
457 // Verify schema validation detects object with too few properties
458 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({});
459 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
460 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
461
462 // Verify validator succeeds on a valid custom-object-type
463 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "a" : 1 });
464 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_ok().());
465 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
466
467 // Verify validator detects invalid custom-object-type
468 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "å" : 1 });
469 let error = validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).expect_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect_err().("Should fail");
470 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(error.to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().(), "Key is not ASCII");
471 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
472 }
473
474 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
475 fn custom_format_and_override_keywordrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_format_and_override_keyword().() {
476 /// Check that a string has some number of digits followed by a dot followed by exactly 2 digits.
477 fn currency_format_checkerrust-analyzer cargo jsonschema 0.37.4 validator/tests/currency_format_checker().(s: &str) -> bool {
478 static CURRENCY_RErust-analyzer cargo jsonschema 0.37.4 validator/tests/CURRENCY_RE.: LazyLockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/lazy_lock/LazyLock#<Regexrust-analyzer cargo fancy-regex 0.11.0 Regex#> = LazyLockrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/lazy_lock/LazyLock#::newrust-analyzer cargo std https://github.com/rust-lang/rust/library/std sync/lazy_lock/impl#[`LazyLock<T, F>`]new().(|| {
479 Regexrust-analyzer cargo fancy-regex 0.11.0 Regex#::newrust-analyzer cargo fancy-regex 0.11.0 impl#[Regex]new().("^(0|([1-9]+[0-9]*))(\\.[0-9]{2})$").expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid regex")
480 });
481 CURRENCY_RErust-analyzer cargo jsonschema 0.37.4 validator/tests/CURRENCY_RE..is_matchrust-analyzer cargo fancy-regex 0.11.0 impl#[Regex]is_match().(s).expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid regex")
482 }
483 /// A custom keyword validator that overrides "minimum"
484 /// so that "minimum" may apply to "currency"-formatted strings as well.
485 struct CustomMinimumValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator# {
486 limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.: f64,
487 limit_valrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit_val.: Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
488 with_currency_formatrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#with_currency_format.: bool,
489 locationrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#location.: Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#,
490 }
491
492 impl Keywordrust-analyzer cargo jsonschema 0.37.4 keywords/custom/Keyword# for CustomMinimumValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator# {
493 fn validaterust-analyzer cargo jsonschema 0.37.4 validator/tests/impl#[CustomMinimumValidator][Keyword]validate().<'i>(
494 &self,
495 instance: &'i Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
496 location: &LazyLocationrust-analyzer cargo jsonschema 0.37.4 paths/LazyLocation#,
497 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<(), ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'i>> {
498 if self.is_validrust-analyzer cargo jsonschema 0.37.4 validator/tests/impl#[CustomMinimumValidator][Keyword]is_valid().(instance) {
499 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(())
500 } else {
501 Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#::minimumrust-analyzer cargo jsonschema 0.37.4 error/impl#[`ValidationError<'a>`]minimum().(
502 self.locationrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#location..clonerust-analyzer cargo jsonschema 0.37.4 paths/impl#[Location][Clone]clone().(),
503 location.intorust-analyzer cargo core https://github.com/rust-lang/rust/library/core convert/impl#[T][`Into<U>`]into().(),
504 instance,
505 self.limit_valrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit_val..clonerust-analyzer cargo serde_json 1.0.145 value/impl#[Value][Clone]clone().(),
506 ))
507 }
508 }
509
510 fn is_validrust-analyzer cargo jsonschema 0.37.4 validator/tests/impl#[CustomMinimumValidator][Keyword]is_valid().(&self, instance: &Valuerust-analyzer cargo serde_json 1.0.145 value/Value#) -> bool {
511 match instance {
512 // Numeric comparison should happen just like original behavior
513 Valuerust-analyzer cargo serde_json 1.0.145 value/Value#::Numberrust-analyzer cargo serde_json 1.0.145 value/Value#Number#(instance) => {
514 if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(item) = instance.as_u64rust-analyzer cargo serde_json 1.0.145 number/impl#[Number]as_u64().() {
515 !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().NumCmprust-analyzer cargo num-cmp 0.1.0 NumCmp#::num_ltrust-analyzer cargo num-cmp 0.1.0 impl#[u64][`NumCmp<f64>`]num_lt().(item, self.limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.)
516 } else if let Somerust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/Option#Some#(item) = instance.as_i64rust-analyzer cargo serde_json 1.0.145 number/impl#[Number]as_i64().() {
517 !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().NumCmprust-analyzer cargo num-cmp 0.1.0 NumCmp#::num_ltrust-analyzer cargo num-cmp 0.1.0 impl#[i64][`NumCmp<f64>`]num_lt().(item, self.limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.)
518 } else {
519 let item = instance.as_f64rust-analyzer cargo serde_json 1.0.145 number/impl#[Number]as_f64().().expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]expect().("Always valid");
520 !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().NumCmprust-analyzer cargo num-cmp 0.1.0 NumCmp#::num_ltrust-analyzer cargo num-cmp 0.1.0 impl#[f64][`NumCmp<Self>`]num_lt().(item, self.limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.)
521 }
522 }
523 // String comparison should cast currency-formatted
524 Valuerust-analyzer cargo serde_json 1.0.145 value/Value#::Stringrust-analyzer cargo serde_json 1.0.145 value/Value#String#(instance) => {
525 if self.with_currency_formatrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#with_currency_format. && currency_format_checkerrust-analyzer cargo jsonschema 0.37.4 validator/tests/currency_format_checker().(instance) {
526 // all preconditions for minimum applying are met
527 let value = instance
528 .parserust-analyzer cargo core https://github.com/rust-lang/rust/library/core str/impl#[str]parse().::<f64>()
529 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("format validated by regex checker");
530 !rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().NumCmprust-analyzer cargo num-cmp 0.1.0 NumCmp#::num_ltrust-analyzer cargo num-cmp 0.1.0 impl#[f64][`NumCmp<Self>`]num_lt().(value, self.limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.)
531 } else {
532 true
533 }
534 }
535 // In all other cases, the "minimum" keyword should not apply
536 _ => true,
537 }
538 }
539 }
540
541 /// Build a validator that overrides the standard `minimum` keyword
542 fn custom_minimum_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_minimum_factory().<'a>(
543 parent: &'a Maprust-analyzer cargo serde_json 1.0.145 map/Map#<Stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/String#, Valuerust-analyzer cargo serde_json 1.0.145 value/Value#>,
544 schema: &'a Valuerust-analyzer cargo serde_json 1.0.145 value/Value#,
545 location: Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#,
546 ) -> Resultrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#<Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#<dyn Keywordrust-analyzer cargo jsonschema 0.37.4 keywords/custom/Keyword#>, ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#<'a>> {
547 let limit = if let Valuerust-analyzer cargo serde_json 1.0.145 value/Value#::Numberrust-analyzer cargo serde_json 1.0.145 value/Value#Number#(limit) = schema {
548 limit.as_f64rust-analyzer cargo serde_json 1.0.145 number/impl#[Number]as_f64().().expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]expect().("Always valid")
549 } else {
550 return Errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Err#(ValidationErrorrust-analyzer cargo jsonschema 0.37.4 error/ValidationError#::single_type_errorrust-analyzer cargo jsonschema 0.37.4 error/impl#[`ValidationError<'a>`]single_type_error().(
551 // There is no metaschema definition for a custom keyword, hence empty `schema` pointer
552 Locationrust-analyzer cargo jsonschema 0.37.4 paths/Location#::newrust-analyzer cargo jsonschema 0.37.4 paths/impl#[Location]new().(),
553 location,
554 schema,
555 JsonTyperust-analyzer cargo jsonschema 0.37.4 types/JsonType#::Numberrust-analyzer cargo jsonschema 0.37.4 types/JsonType#Number#,
556 ));
557 };
558 let with_currency_format = parent
559 .getrust-analyzer cargo serde_json 1.0.145 map/impl#[`Map<String, Value>`]get().("format")
560 .is_some_andrust-analyzer cargo core https://github.com/rust-lang/rust/library/core option/impl#[`Option<T>`]is_some_and().(|format| format rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq().==rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq(). rust-analyzer cargo core https://github.com/rust-lang/rust/library/core cmp/impls/impl#[`&A`][`PartialEq<&B>`]eq()."currency");
561 Okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/Result#Ok#(Boxrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/Box#::newrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc boxed/impl#[`Box<T>`]new().(CustomMinimumValidatorrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator# {
562 limitrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit.,
563 limit_valrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#limit_val.: schema.clonerust-analyzer cargo serde_json 1.0.145 value/impl#[Value][Clone]clone().(),
564 with_currency_formatrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#with_currency_format.,
565 locationrust-analyzer cargo jsonschema 0.37.4 validator/tests/CustomMinimumValidator#location.,
566 }))
567 }
568
569 // Schema includes both the custom format and the overridden keyword
570 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "minimum": 2, "type": "string", "format": "currency" });
571 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
572 .with_formatrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_format().("currency", currency_format_checkerrust-analyzer cargo jsonschema 0.37.4 validator/tests/currency_format_checker().)
573 .with_keywordrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_keyword().("minimum", custom_minimum_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_minimum_factory().)
574 .with_keywordrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_keyword().("minimum-2", custom_minimum_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_minimum_factory().)
575 .should_validate_formatsrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]should_validate_formats().(true)
576 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
577 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid schema");
578
579 // Control: verify schema validation rejects non-string types
580 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!(15);
581 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
582 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
583
584 // Control: verify validator rejects ill-formatted strings
585 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("not a currency");
586 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
587 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
588
589 // Verify validator allows properly formatted strings that conform to custom keyword
590 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("3.00");
591 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_ok().());
592 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
593
594 // Verify validator rejects properly formatted strings that do not conform to custom keyword
595 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("1.99");
596 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
597 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
598
599 // Define another schema that applies "minimum" to an integer to ensure original behavior
600 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "minimum": 2, "type": "integer" });
601 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
602 .with_formatrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_format().("currency", currency_format_checkerrust-analyzer cargo jsonschema 0.37.4 validator/tests/currency_format_checker().)
603 .with_keywordrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_keyword().("minimum", custom_minimum_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_minimum_factory().)
604 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
605 .expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Invalid schema");
606
607 // Verify schema allows integers greater than 2
608 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!(3);
609 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_okrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_ok().());
610 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
611
612 // Verify schema rejects integers less than 2
613 let instance = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!(1);
614 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.validaterust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]validate().(&instance).is_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]is_err().());
615 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&instance));
616
617 // Invalid `minimum` value
618 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({ "minimum": "foo" });
619 let error = craterust-analyzer cargo jsonschema 0.37.4 crate/::optionsrust-analyzer cargo jsonschema 0.37.4 options().()
620 .with_keywordrust-analyzer cargo jsonschema 0.37.4 options/impl#[`ValidationOptions<R>`]with_keyword().("minimum", custom_minimum_factoryrust-analyzer cargo jsonschema 0.37.4 validator/tests/custom_minimum_factory().)
621 .buildrust-analyzer cargo jsonschema 0.37.4 options/impl#[ValidationOptions]build().(&schema)
622 .expect_errrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect_err().("Should fail");
623 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(error.to_stringrust-analyzer cargo alloc https://github.com/rust-lang/rust/library/alloc string/impl#[T][ToString]to_string().(), "\"foo\" is not of type \"number\"");
624 }
625
626 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
627 fn test_validator_is_send_and_syncrust-analyzer cargo jsonschema 0.37.4 validator/tests/test_validator_is_send_and_sync().() {
628 fn assert_send_syncrust-analyzer cargo jsonschema 0.37.4 validator/tests/assert_send_sync().<T: ThreadBoundrust-analyzer cargo jsonschema 0.37.4 thread/ThreadBound#>() {}
629 assert_send_syncrust-analyzer cargo jsonschema 0.37.4 validator/tests/assert_send_sync().::<Validatorrust-analyzer cargo jsonschema 0.37.4 validator/Validator#>();
630 }
631
632 #[testrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/test:]
633 fn test_validator_clonerust-analyzer cargo jsonschema 0.37.4 validator/tests/test_validator_clone().() {
634 let schema = jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!({"type": "string", "minLength": 3});
635 let validator = craterust-analyzer cargo jsonschema 0.37.4 crate/::validator_forrust-analyzer cargo jsonschema 0.37.4 validator_for().(&schema).expectrust-analyzer cargo core https://github.com/rust-lang/rust/library/core result/impl#[`Result<T, E>`]expect().("Valid schema");
636
637 // Clone the validator
638 let cloned = validator.clonerust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator][Clone]clone().();
639
640 // Both validators should work independently
641 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("hello")));
642 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("hi")));
643
644 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(cloned.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("hello")));
645 assertrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/builtin/assert!!(!rust-analyzer cargo core https://github.com/rust-lang/rust/library/core ops/bit/impl#[bool][Not]not().cloned.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("hi")));
646
647 // Verify they validate the same way
648 assert_eqrust-analyzer cargo core https://github.com/rust-lang/rust/library/core macros/assert_eq!!(
649 validator.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("test")),
650 cloned.is_validrust-analyzer cargo jsonschema 0.37.4 validator/impl#[Validator]is_valid().(&jsonrust-analyzer cargo serde_json 1.0.145 macros/json!!("test"))
651 );
652 }
653 }