Skip to content

Commit c571e73

Browse files
authored
Fix validate's checking of non-root definitions (#13)
* Fix validate's checking of non-root definitions * Release 0.2.1
1 parent 32fbcd8 commit c571e73

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "jtd"
3-
version = "0.2.0"
3+
version = "0.2.1"
44
description = "A Rust implementation of JSON Type Definition"
55
authors = ["JSON Type Definition Contributors"]
66
edition = "2018"

src/schema.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,25 @@ impl Schema {
110110
}
111111

112112
fn validate_with_root(&self, root: Option<&Self>) -> Result<(), ValidateError> {
113-
if root.is_none() && !self.definitions.is_empty() {
113+
// If root is non-None, then self is not the root schema. We should
114+
// therefore not tolerate definitions being placed on this schema.
115+
if root.is_some() && !self.definitions.is_empty() {
114116
return Err(ValidateError::NonRootDefinitions);
115117
}
116118

119+
// This root variable is the one we will use for recursive calls to
120+
// validate_with_root.
121+
//
122+
// If we are at the top-level call of validate_with_root (invoked by the
123+
// public validate method) wherein root is None, then root will be
124+
// Some(self) for the recursive calls, since we ourselves are the root.
125+
let root = root.or(Some(self));
126+
127+
// Validate each definition, if any.
128+
for sub_schema in self.definitions.values() {
129+
sub_schema.validate_with_root(root)?;
130+
}
131+
117132
match &self.form {
118133
form::Form::Empty | form::Form::Type(_) => {}
119134
form::Form::Enum(form::Enum { values, .. }) => {
@@ -122,7 +137,9 @@ impl Schema {
122137
}
123138
}
124139
form::Form::Ref(form::Ref { definition, .. }) => {
125-
if !root.unwrap_or(&self).definitions.contains_key(definition) {
140+
// This unwrap is safe because the assignment to root above
141+
// guarantees root will be non-None.
142+
if !root.unwrap().definitions.contains_key(definition) {
126143
return Err(ValidateError::NoSuchDefinition(definition.clone()));
127144
}
128145
}

src/validator.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -403,11 +403,13 @@ mod tests {
403403
.unwrap();
404404

405405
for (name, test_case) in test_cases {
406-
let schema = test_case
406+
let schema: Schema = test_case
407407
.schema
408408
.try_into()
409409
.expect(&format!("parsing schema: {}", name));
410410

411+
schema.validate().expect(&format!("validating schema: {}", name));
412+
411413
let validator = Validator {
412414
max_depth: None,
413415
max_errors: None,

0 commit comments

Comments
 (0)