perf: Avoid allocations while constructing path segments
Signed-off-by: Dmitry Dygalo <dmitry@dygalo.dev>
This commit is contained in:
parent
21df1810bd
commit
cfab6027a1
|
@ -11,6 +11,7 @@
|
|||
### Performance
|
||||
|
||||
- Optimize building `JSONPointer` for validation errors by allocating the exact amount of memory needed.
|
||||
- Avoid cloning path segments during validation.
|
||||
|
||||
### Changed
|
||||
|
||||
|
|
16
README.md
16
README.md
|
@ -225,7 +225,7 @@ $ cargo test
|
|||
|
||||
## Performance
|
||||
|
||||
There is a comparison with other JSON Schema validators written in Rust - `jsonschema_valid==0.4.0` and `valico==3.6.0`.
|
||||
There is a comparison with other JSON Schema validators written in Rust - `jsonschema_valid==0.5.2` and `valico==4.0.0`.
|
||||
|
||||
Test machine i8700K (12 cores), 32GB RAM.
|
||||
|
||||
|
@ -250,12 +250,12 @@ Here is the average time for each contender to validate. Ratios are given agains
|
|||
|
||||
| Case | jsonschema_valid | valico | jsonschema (validate) | jsonschema (is_valid) |
|
||||
| -------------- | ----------------------- | ----------------------- | --------------------- | ---------------------- |
|
||||
| OpenAPI | - (1) | - (1) | 4.717 ms | 4.279 ms (**x0.90**) |
|
||||
| Swagger | - (2) | 83.357 ms (**x12.47**) | 6.681 ms | 4.533 ms (**x0.67**) |
|
||||
| Canada | 32.987 ms (**x31.38**) | 141.41 ms (**x134.54**) | 1.051 ms | 1.046 ms (**x0.99**) |
|
||||
| CITM catalog | 4.735 ms (**x2.00**) | 13.222 ms (**x5.58**) | 2.367 ms | 535.07 us (**x0.22**) |
|
||||
| Fast (valid) | 2.00 us (**x3.85**) | 3.18 us (**x6.13**) | 518.39 ns | 97.91 ns (**x0.18**) |
|
||||
| Fast (invalid) | 339.28 ns (**x0.50**) | 3.34 us (**x5.00**) | 667.55 ns | 5.41ns (**x0.01**) |
|
||||
| OpenAPI | - (1) | - (1) | 3.500 ms | 3.147 ms (**x0.89**) |
|
||||
| Swagger | - (2) | 180.65 ms (**x32.12**) | 5.623 ms | 3.634 ms (**x0.64**) |
|
||||
| Canada | 40.363 ms (**x33.13**) | 427.40 ms (**x350.90**) | 1.218 ms | 1.217 ms (**x0.99**) |
|
||||
| CITM catalog | 5.357 ms (**x2.51**) | 39.215 ms (**x18.44**) | 2.126 ms | 569.23 us (**x0.26**) |
|
||||
| Fast (valid) | 2.27 us (**x4.87**) | 6.55 us (**x14.05**) | 465.89 ns | 113.94 ns (**x0.24**) |
|
||||
| Fast (invalid) | 412.21 ns (**x0.46**) | 6.69 us (**x7.61**) | 878.23 ns | 4.21ns (**x0.004**) |
|
||||
|
||||
Notes:
|
||||
|
||||
|
@ -263,7 +263,7 @@ Notes:
|
|||
|
||||
2. `jsonschema_valid` fails to resolve local references (e.g. `#/definitions/definitions`).
|
||||
|
||||
You can find benchmark code in `benches/jsonschema.rs`, Rust version is `1.57`.
|
||||
You can find benchmark code in `benches/jsonschema.rs`, Rust version is `1.78`.
|
||||
|
||||
## Support
|
||||
|
||||
|
|
|
@ -41,7 +41,7 @@ pub(crate) fn setup(json_schema_test_suite_path: &Path) -> Vec<TokenStream> {
|
|||
let path = remote_path
|
||||
.trim_start_matches(base_path)
|
||||
.replace(std::path::MAIN_SEPARATOR, "/");
|
||||
if let Ok(file_content) = std::fs::read_to_string(remote_path) {
|
||||
if let Ok(file_content) = fs::read_to_string(remote_path) {
|
||||
Some(quote! {
|
||||
mockito::mock("GET", #path)
|
||||
.with_body(
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use super::options::CompilationOptions;
|
||||
use crate::{
|
||||
compilation::DEFAULT_SCOPE,
|
||||
paths::{JSONPointer, JsonPointerNode, PathChunk},
|
||||
paths::{JSONPointer, JsonPointerNode, PathChunkRef},
|
||||
resolver::Resolver,
|
||||
schemas,
|
||||
};
|
||||
|
@ -17,7 +17,7 @@ pub(crate) struct CompilationContext<'a> {
|
|||
base_uri: BaseUri<'a>,
|
||||
pub(crate) config: Arc<CompilationOptions>,
|
||||
pub(crate) resolver: Arc<Resolver>,
|
||||
pub(crate) schema_path: JsonPointerNode<'a>,
|
||||
pub(crate) schema_path: JsonPointerNode<'a, 'a>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
@ -118,7 +118,7 @@ impl<'a> CompilationContext<'a> {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn with_path(&'a self, chunk: impl Into<PathChunk>) -> Self {
|
||||
pub(crate) fn with_path(&'a self, chunk: impl Into<PathChunkRef<'a>>) -> Self {
|
||||
let schema_path = self.schema_path.push(chunk);
|
||||
CompilationContext {
|
||||
base_uri: self.base_uri.clone(),
|
||||
|
@ -136,7 +136,7 @@ impl<'a> CompilationContext<'a> {
|
|||
|
||||
/// Create a JSON Pointer from the current `schema_path` & a new chunk.
|
||||
#[inline]
|
||||
pub(crate) fn as_pointer_with(&self, chunk: impl Into<PathChunk>) -> JSONPointer {
|
||||
pub(crate) fn as_pointer_with(&'a self, chunk: impl Into<PathChunkRef<'a>>) -> JSONPointer {
|
||||
self.schema_path.push(chunk).into()
|
||||
}
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ pub struct JSONSchema {
|
|||
}
|
||||
|
||||
pub(crate) static DEFAULT_SCOPE: Lazy<Url> =
|
||||
Lazy::new(|| url::Url::parse(DEFAULT_ROOT_URL).expect("Is a valid URL"));
|
||||
Lazy::new(|| Url::parse(DEFAULT_ROOT_URL).expect("Is a valid URL"));
|
||||
|
||||
impl JSONSchema {
|
||||
/// Return a default `CompilationOptions` that can configure
|
||||
|
@ -200,7 +200,7 @@ pub(crate) fn compile_validators<'a>(
|
|||
}
|
||||
// Check if this keyword is overridden, then check the standard definitions
|
||||
if let Some(factory) = context.config.get_keyword_factory(keyword) {
|
||||
let path = context.as_pointer_with(keyword.to_owned());
|
||||
let path = context.as_pointer_with(keyword.as_str());
|
||||
let validator = CustomKeyword::new(factory.init(object, subschema, path)?);
|
||||
let validator: BoxedValidator = Box::new(validator);
|
||||
validators.push((keyword.clone(), validator));
|
||||
|
|
|
@ -55,7 +55,7 @@ macro_rules! is_valid_patterns {
|
|||
|
||||
macro_rules! validate {
|
||||
($node:expr, $value:ident, $instance_path:expr, $property_name:expr) => {{
|
||||
let instance_path = $instance_path.push($property_name.clone());
|
||||
let instance_path = $instance_path.push($property_name.as_str());
|
||||
$node.validate($value, &instance_path)
|
||||
}};
|
||||
}
|
||||
|
@ -125,12 +125,12 @@ impl Validate for AdditionalPropertiesValidator {
|
|||
let mut matched_props = Vec::with_capacity(item.len());
|
||||
let mut output = BasicOutput::default();
|
||||
for (name, value) in item {
|
||||
let path = instance_path.push(name.to_string());
|
||||
let path = instance_path.push(name.as_str());
|
||||
output += self.node.apply_rooted(value, &path);
|
||||
matched_props.push(name.clone());
|
||||
}
|
||||
let mut result: PartialApplication = output.into();
|
||||
result.annotate(serde_json::Value::from(matched_props).into());
|
||||
result.annotate(Value::from(matched_props).into());
|
||||
result
|
||||
} else {
|
||||
PartialApplication::valid_empty()
|
||||
|
@ -298,7 +298,7 @@ impl<M: PropertiesValidatorsMap> Validate for AdditionalPropertiesNotEmptyFalseV
|
|||
let mut output = BasicOutput::default();
|
||||
for (property, value) in item {
|
||||
if let Some((_name, node)) = self.properties.get_key_validator(property) {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
output += node.apply_rooted(value, &path);
|
||||
} else {
|
||||
unexpected.push(property.clone())
|
||||
|
@ -424,7 +424,7 @@ impl<M: PropertiesValidatorsMap> Validate for AdditionalPropertiesNotEmptyValida
|
|||
let mut matched_propnames = Vec::with_capacity(map.len());
|
||||
let mut output = BasicOutput::default();
|
||||
for (property, value) in map {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
if let Some((_name, property_validators)) =
|
||||
self.properties.get_key_validator(property)
|
||||
{
|
||||
|
@ -436,7 +436,7 @@ impl<M: PropertiesValidatorsMap> Validate for AdditionalPropertiesNotEmptyValida
|
|||
}
|
||||
let mut result: PartialApplication = output.into();
|
||||
if !matched_propnames.is_empty() {
|
||||
result.annotate(serde_json::Value::from(matched_propnames).into());
|
||||
result.annotate(Value::from(matched_propnames).into());
|
||||
}
|
||||
result
|
||||
} else {
|
||||
|
@ -561,7 +561,7 @@ impl Validate for AdditionalPropertiesWithPatternsValidator {
|
|||
let mut pattern_matched_propnames = Vec::with_capacity(item.len());
|
||||
let mut additional_matched_propnames = Vec::with_capacity(item.len());
|
||||
for (property, value) in item {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
let mut has_match = false;
|
||||
for (pattern, node) in &self.patterns {
|
||||
if pattern.is_match(property).unwrap_or(false) {
|
||||
|
@ -580,13 +580,13 @@ impl Validate for AdditionalPropertiesWithPatternsValidator {
|
|||
self.pattern_keyword_path.clone(),
|
||||
instance_path.into(),
|
||||
self.pattern_keyword_absolute_path.clone(),
|
||||
serde_json::Value::from(pattern_matched_propnames).into(),
|
||||
Value::from(pattern_matched_propnames).into(),
|
||||
)
|
||||
.into();
|
||||
}
|
||||
let mut result: PartialApplication = output.into();
|
||||
if !additional_matched_propnames.is_empty() {
|
||||
result.annotate(serde_json::Value::from(additional_matched_propnames).into())
|
||||
result.annotate(Value::from(additional_matched_propnames).into())
|
||||
}
|
||||
result
|
||||
} else {
|
||||
|
@ -707,7 +707,7 @@ impl Validate for AdditionalPropertiesWithPatternsFalseValidator {
|
|||
let mut unexpected = Vec::with_capacity(item.len());
|
||||
let mut pattern_matched_props = Vec::with_capacity(item.len());
|
||||
for (property, value) in item {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
let mut has_match = false;
|
||||
for (pattern, node) in &self.patterns {
|
||||
if pattern.is_match(property).unwrap_or(false) {
|
||||
|
@ -725,7 +725,7 @@ impl Validate for AdditionalPropertiesWithPatternsFalseValidator {
|
|||
self.pattern_keyword_path.clone(),
|
||||
instance_path.into(),
|
||||
self.pattern_keyword_absolute_path.clone(),
|
||||
serde_json::Value::from(pattern_matched_props).into(),
|
||||
Value::from(pattern_matched_props).into(),
|
||||
)
|
||||
.into();
|
||||
}
|
||||
|
@ -905,7 +905,7 @@ impl<M: PropertiesValidatorsMap> Validate for AdditionalPropertiesWithPatternsNo
|
|||
let mut output = BasicOutput::default();
|
||||
let mut additional_matches = Vec::with_capacity(item.len());
|
||||
for (property, value) in item {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
if let Some((_name, node)) = self.properties.get_key_validator(property) {
|
||||
output += node.apply_rooted(value, &path);
|
||||
for (pattern, node) in &self.patterns {
|
||||
|
@ -928,7 +928,7 @@ impl<M: PropertiesValidatorsMap> Validate for AdditionalPropertiesWithPatternsNo
|
|||
}
|
||||
}
|
||||
let mut result: PartialApplication = output.into();
|
||||
result.annotate(serde_json::Value::from(additional_matches).into());
|
||||
result.annotate(Value::from(additional_matches).into());
|
||||
result
|
||||
} else {
|
||||
PartialApplication::valid_empty()
|
||||
|
@ -1097,7 +1097,7 @@ impl<M: PropertiesValidatorsMap> Validate
|
|||
let mut unexpected = vec![];
|
||||
// No properties are allowed, except ones defined in `properties` or `patternProperties`
|
||||
for (property, value) in item {
|
||||
let path = instance_path.push(property.clone());
|
||||
let path = instance_path.push(property.as_str());
|
||||
if let Some((_name, node)) = self.properties.get_key_validator(property) {
|
||||
output += node.apply_rooted(value, &path);
|
||||
for (pattern, node) in &self.patterns {
|
||||
|
|
|
@ -86,12 +86,12 @@ impl Validate for ContainsValidator {
|
|||
.into(),
|
||||
);
|
||||
} else {
|
||||
result.annotate(serde_json::Value::from(indices).into());
|
||||
result.annotate(Value::from(indices).into());
|
||||
}
|
||||
result
|
||||
} else {
|
||||
let mut result = PartialApplication::valid_empty();
|
||||
result.annotate(serde_json::Value::Array(Vec::new()).into());
|
||||
result.annotate(Value::Array(Vec::new()).into());
|
||||
result
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ impl DependenciesValidator {
|
|||
let keyword_context = context.with_path("dependencies");
|
||||
let mut dependencies = Vec::with_capacity(map.len());
|
||||
for (key, subschema) in map {
|
||||
let item_context = keyword_context.with_path(key.to_string());
|
||||
let item_context = keyword_context.with_path(key.as_str());
|
||||
let s = match subschema {
|
||||
Value::Array(_) => {
|
||||
let validators = vec![required::compile_with_path(
|
||||
|
@ -106,7 +106,7 @@ impl DependentRequiredValidator {
|
|||
let keyword_context = context.with_path("dependentRequired");
|
||||
let mut dependencies = Vec::with_capacity(map.len());
|
||||
for (key, subschema) in map {
|
||||
let item_context = keyword_context.with_path(key.to_string());
|
||||
let item_context = keyword_context.with_path(key.as_str());
|
||||
if let Value::Array(dependency_array) = subschema {
|
||||
if !unique_items::is_unique(dependency_array) {
|
||||
return Err(ValidationError::unique_items(
|
||||
|
@ -196,7 +196,7 @@ impl DependentSchemasValidator {
|
|||
let keyword_context = context.with_path("dependentSchemas");
|
||||
let mut dependencies = Vec::with_capacity(map.len());
|
||||
for (key, subschema) in map {
|
||||
let item_context = keyword_context.with_path(key.to_string());
|
||||
let item_context = keyword_context.with_path(key.as_str());
|
||||
let schema_nodes = compile_validators(subschema, &item_context)?;
|
||||
dependencies.push((key.clone(), schema_nodes));
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ impl PatternPropertiesValidator {
|
|||
let keyword_context = context.with_path("patternProperties");
|
||||
let mut patterns = Vec::with_capacity(map.len());
|
||||
for (pattern, subschema) in map {
|
||||
let pattern_context = keyword_context.with_path(pattern.to_string());
|
||||
let pattern_context = keyword_context.with_path(pattern.as_str());
|
||||
patterns.push((
|
||||
match Regex::new(pattern) {
|
||||
Ok(r) => r,
|
||||
|
@ -71,7 +71,7 @@ impl Validate for PatternPropertiesValidator {
|
|||
item.iter()
|
||||
.filter(move |(key, _)| re.is_match(key).unwrap_or(false))
|
||||
.flat_map(move |(key, value)| {
|
||||
let instance_path = instance_path.push(key.clone());
|
||||
let instance_path = instance_path.push(key.as_str());
|
||||
node.validate(value, &instance_path)
|
||||
})
|
||||
})
|
||||
|
@ -93,14 +93,14 @@ impl Validate for PatternPropertiesValidator {
|
|||
for (pattern, node) in &self.patterns {
|
||||
for (key, value) in item {
|
||||
if pattern.is_match(key).unwrap_or(false) {
|
||||
let path = instance_path.push(key.clone());
|
||||
let path = instance_path.push(key.as_str());
|
||||
matched_propnames.push(key.clone());
|
||||
sub_results += node.apply_rooted(value, &path);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut result: PartialApplication = sub_results.into();
|
||||
result.annotate(serde_json::Value::from(matched_propnames).into());
|
||||
result.annotate(Value::from(matched_propnames).into());
|
||||
result
|
||||
} else {
|
||||
PartialApplication::valid_empty()
|
||||
|
@ -135,7 +135,7 @@ impl SingleValuePatternPropertiesValidator {
|
|||
context: &CompilationContext,
|
||||
) -> CompilationResult<'a> {
|
||||
let keyword_context = context.with_path("patternProperties");
|
||||
let pattern_context = keyword_context.with_path(pattern.to_string());
|
||||
let pattern_context = keyword_context.with_path(pattern);
|
||||
Ok(Box::new(SingleValuePatternPropertiesValidator {
|
||||
pattern: match Regex::new(pattern) {
|
||||
Ok(r) => r,
|
||||
|
@ -175,7 +175,7 @@ impl Validate for SingleValuePatternPropertiesValidator {
|
|||
.iter()
|
||||
.filter(move |(key, _)| self.pattern.is_match(key).unwrap_or(false))
|
||||
.flat_map(move |(key, value)| {
|
||||
let instance_path = instance_path.push(key.clone());
|
||||
let instance_path = instance_path.push(key.as_str());
|
||||
self.node.validate(value, &instance_path)
|
||||
})
|
||||
.collect();
|
||||
|
@ -195,13 +195,13 @@ impl Validate for SingleValuePatternPropertiesValidator {
|
|||
let mut outputs = BasicOutput::default();
|
||||
for (key, value) in item {
|
||||
if self.pattern.is_match(key).unwrap_or(false) {
|
||||
let path = instance_path.push(key.clone());
|
||||
let path = instance_path.push(key.as_str());
|
||||
matched_propnames.push(key.clone());
|
||||
outputs += self.node.apply_rooted(value, &path);
|
||||
}
|
||||
}
|
||||
let mut result: PartialApplication = outputs.into();
|
||||
result.annotate(serde_json::Value::from(matched_propnames).into());
|
||||
result.annotate(Value::from(matched_propnames).into());
|
||||
result
|
||||
} else {
|
||||
PartialApplication::valid_empty()
|
||||
|
|
|
@ -25,7 +25,7 @@ impl PropertiesValidator {
|
|||
let context = context.with_path("properties");
|
||||
let mut properties = Vec::with_capacity(map.len());
|
||||
for (key, subschema) in map {
|
||||
let property_context = context.with_path(key.clone());
|
||||
let property_context = context.with_path(key.as_str());
|
||||
properties.push((
|
||||
key.clone(),
|
||||
compile_validators(subschema, &property_context)?,
|
||||
|
@ -68,7 +68,7 @@ impl Validate for PropertiesValidator {
|
|||
.flat_map(move |(name, node)| {
|
||||
let option = item.get(name);
|
||||
option.into_iter().flat_map(move |item| {
|
||||
let instance_path = instance_path.push(name.clone());
|
||||
let instance_path = instance_path.push(name.as_str());
|
||||
node.validate(item, &instance_path)
|
||||
})
|
||||
})
|
||||
|
@ -89,13 +89,13 @@ impl Validate for PropertiesValidator {
|
|||
let mut matched_props = Vec::with_capacity(props.len());
|
||||
for (prop_name, node) in &self.properties {
|
||||
if let Some(prop) = props.get(prop_name) {
|
||||
let path = instance_path.push(prop_name.clone());
|
||||
let path = instance_path.push(prop_name.as_str());
|
||||
matched_props.push(prop_name.clone());
|
||||
result += node.apply_rooted(prop, &path);
|
||||
}
|
||||
}
|
||||
let mut application: PartialApplication = result.into();
|
||||
application.annotate(serde_json::Value::from(matched_props).into());
|
||||
application.annotate(Value::from(matched_props).into());
|
||||
application
|
||||
} else {
|
||||
PartialApplication::valid_empty()
|
||||
|
|
|
@ -17,11 +17,6 @@ use url::Url;
|
|||
pub(crate) struct RefValidator {
|
||||
original_reference: String,
|
||||
reference: Url,
|
||||
/// Precomputed validators.
|
||||
/// They are behind a RwLock as is not possible to compute them
|
||||
/// at compile time without risking infinite loops of references
|
||||
/// and at the same time during validation we iterate over shared
|
||||
/// references (&self) and not owned references (&mut self).
|
||||
sub_nodes: RwLock<Option<SchemaNode>>,
|
||||
schema_path: JSONPointer,
|
||||
config: Arc<CompilationOptions>,
|
||||
|
|
|
@ -361,7 +361,7 @@ impl Validate for UnevaluatedPropertiesValidator {
|
|||
let mut unevaluated = vec![];
|
||||
|
||||
for (property_name, property_instance) in props {
|
||||
let property_path = instance_path.push(property_name.clone());
|
||||
let property_path = instance_path.push(property_name.as_str());
|
||||
let maybe_property_errors = self.validate_property(
|
||||
instance,
|
||||
instance_path,
|
||||
|
@ -403,7 +403,7 @@ impl Validate for UnevaluatedPropertiesValidator {
|
|||
let mut unevaluated = vec![];
|
||||
|
||||
for (property_name, property_instance) in props {
|
||||
let property_path = instance_path.push(property_name.clone());
|
||||
let property_path = instance_path.push(property_name.as_str());
|
||||
let maybe_property_output = self.apply_property(
|
||||
instance,
|
||||
instance_path,
|
||||
|
@ -610,7 +610,7 @@ impl SubschemaSubvalidator {
|
|||
|
||||
for (i, value) in values.iter().enumerate() {
|
||||
if let Value::Object(subschema) = value {
|
||||
let subschema_context = keyword_context.with_path(i.to_string());
|
||||
let subschema_context = keyword_context.with_path(i);
|
||||
|
||||
let node = compile_validators(value, &subschema_context)?;
|
||||
let subvalidator = UnevaluatedPropertiesValidator::compile(
|
||||
|
@ -1124,7 +1124,7 @@ impl DependentSchemaSubvalidator {
|
|||
.as_object()
|
||||
.ok_or_else(ValidationError::null_schema)?;
|
||||
|
||||
let schema_context = keyword_context.with_path(dependent_property_name.to_string());
|
||||
let schema_context = keyword_context.with_path(dependent_property_name.as_str());
|
||||
let node = UnevaluatedPropertiesValidator::compile(
|
||||
dependent_schema,
|
||||
get_transitive_unevaluated_props_schema(dependent_schema, parent),
|
||||
|
|
|
@ -80,7 +80,6 @@ impl fmt::Display for JSONPointer {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
/// A key within a JSON object or an index within a JSON array.
|
||||
/// A sequence of chunks represents a valid path within a JSON value.
|
||||
///
|
||||
|
@ -96,6 +95,7 @@ impl fmt::Display for JSONPointer {
|
|||
/// 2. Take the 2nd value from the array - `PathChunk::Index(2)`
|
||||
///
|
||||
/// The primary purpose of this enum is to avoid converting indexes to strings during validation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum PathChunk {
|
||||
/// Property name within a JSON object.
|
||||
Property(Box<str>),
|
||||
|
@ -105,6 +105,15 @@ pub enum PathChunk {
|
|||
Keyword(&'static str),
|
||||
}
|
||||
|
||||
/// A borrowed variant of `PathChunk`.
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub enum PathChunkRef<'a> {
|
||||
/// Property name within a JSON object.
|
||||
Property(&'a str),
|
||||
/// JSON Schema keyword.
|
||||
Index(usize),
|
||||
}
|
||||
|
||||
/// A node in a linked list representing a JSON pointer.
|
||||
///
|
||||
/// `JsonPointerNode` is used to build a JSON pointer incrementally during the JSON Schema validation process.
|
||||
|
@ -114,24 +123,30 @@ pub enum PathChunk {
|
|||
/// The linked list representation allows for efficient traversal and manipulation of the JSON pointer
|
||||
/// without the need for memory allocation.
|
||||
#[derive(Debug, Clone, Eq, PartialEq)]
|
||||
pub struct JsonPointerNode<'a> {
|
||||
pub(crate) segment: PathChunk,
|
||||
pub(crate) parent: Option<&'a JsonPointerNode<'a>>,
|
||||
pub struct JsonPointerNode<'a, 'b> {
|
||||
pub(crate) segment: PathChunkRef<'a>,
|
||||
pub(crate) parent: Option<&'b JsonPointerNode<'b, 'a>>,
|
||||
}
|
||||
|
||||
impl<'a> JsonPointerNode<'a> {
|
||||
impl Default for JsonPointerNode<'_, '_> {
|
||||
fn default() -> Self {
|
||||
JsonPointerNode::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> JsonPointerNode<'a, 'b> {
|
||||
/// Create a root node of a JSON pointer.
|
||||
pub const fn new() -> Self {
|
||||
JsonPointerNode {
|
||||
// The value does not matter, it will never be used
|
||||
segment: PathChunk::Index(0),
|
||||
segment: PathChunkRef::Index(0),
|
||||
parent: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Push a new segment to the JSON pointer.
|
||||
#[inline]
|
||||
pub fn push(&'a self, segment: impl Into<PathChunk>) -> Self {
|
||||
pub fn push(&'a self, segment: impl Into<PathChunkRef<'a>>) -> Self {
|
||||
JsonPointerNode {
|
||||
segment: segment.into(),
|
||||
parent: Some(self),
|
||||
|
@ -151,12 +166,12 @@ impl<'a> JsonPointerNode<'a> {
|
|||
let mut buffer = Vec::with_capacity(capacity);
|
||||
let mut head = self;
|
||||
if head.parent.is_some() {
|
||||
buffer.push(head.segment.clone())
|
||||
buffer.push(head.segment.into())
|
||||
}
|
||||
while let Some(next) = head.parent {
|
||||
head = next;
|
||||
if head.parent.is_some() {
|
||||
buffer.push(head.segment.clone());
|
||||
buffer.push(head.segment.into());
|
||||
}
|
||||
}
|
||||
// Reverse the buffer to get the segments in the correct order
|
||||
|
@ -189,12 +204,14 @@ impl From<String> for PathChunk {
|
|||
PathChunk::Property(value.into_boxed_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for PathChunk {
|
||||
#[inline]
|
||||
fn from(value: &'static str) -> Self {
|
||||
PathChunk::Keyword(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<usize> for PathChunk {
|
||||
#[inline]
|
||||
fn from(value: usize) -> Self {
|
||||
|
@ -202,16 +219,40 @@ impl From<usize> for PathChunk {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a JsonPointerNode<'a>> for JSONPointer {
|
||||
impl<'a> From<&'a str> for PathChunkRef<'a> {
|
||||
#[inline]
|
||||
fn from(path: &'a JsonPointerNode<'a>) -> Self {
|
||||
fn from(value: &'a str) -> PathChunkRef<'a> {
|
||||
PathChunkRef::Property(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<usize> for PathChunkRef<'_> {
|
||||
#[inline]
|
||||
fn from(value: usize) -> Self {
|
||||
PathChunkRef::Index(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<PathChunkRef<'a>> for PathChunk {
|
||||
#[inline]
|
||||
fn from(value: PathChunkRef<'a>) -> Self {
|
||||
match value {
|
||||
PathChunkRef::Property(value) => PathChunk::Property(value.into()),
|
||||
PathChunkRef::Index(value) => PathChunk::Index(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'b> From<&'a JsonPointerNode<'a, 'b>> for JSONPointer {
|
||||
#[inline]
|
||||
fn from(path: &'a JsonPointerNode<'a, 'b>) -> Self {
|
||||
JSONPointer(path.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JsonPointerNode<'_>> for JSONPointer {
|
||||
impl From<JsonPointerNode<'_, '_>> for JSONPointer {
|
||||
#[inline]
|
||||
fn from(path: JsonPointerNode<'_>) -> Self {
|
||||
fn from(path: JsonPointerNode<'_, '_>) -> Self {
|
||||
JSONPointer(path.to_vec())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -95,7 +95,7 @@ pub(crate) fn compile_small_map<'a>(
|
|||
let mut properties = Vec::with_capacity(map.len());
|
||||
let keyword_context = context.with_path("properties");
|
||||
for (key, subschema) in map {
|
||||
let property_context = keyword_context.with_path(key.clone());
|
||||
let property_context = keyword_context.with_path(key.as_str());
|
||||
properties.push((
|
||||
key.clone(),
|
||||
compile_validators(subschema, &property_context)?,
|
||||
|
@ -111,7 +111,7 @@ pub(crate) fn compile_big_map<'a>(
|
|||
let mut properties = AHashMap::with_capacity(map.len());
|
||||
let keyword_context = context.with_path("properties");
|
||||
for (key, subschema) in map {
|
||||
let property_context = keyword_context.with_path(key.clone());
|
||||
let property_context = keyword_context.with_path(key.as_str());
|
||||
properties.insert(
|
||||
key.clone(),
|
||||
compile_validators(subschema, &property_context)?,
|
||||
|
@ -143,7 +143,7 @@ pub(crate) fn compile_patterns<'a>(
|
|||
let keyword_context = context.with_path("patternProperties");
|
||||
let mut compiled_patterns = Vec::with_capacity(obj.len());
|
||||
for (pattern, subschema) in obj {
|
||||
let pattern_context = keyword_context.with_path(pattern.to_string());
|
||||
let pattern_context = keyword_context.with_path(pattern.as_str());
|
||||
if let Ok(compiled_pattern) = Regex::new(pattern) {
|
||||
let node = compile_validators(subschema, &pattern_context)?;
|
||||
compiled_patterns.push((compiled_pattern, node));
|
||||
|
|
|
@ -216,7 +216,7 @@ impl SchemaNode {
|
|||
) -> PartialApplication<'a>
|
||||
where
|
||||
I: Iterator<Item = (P, &'a Box<dyn Validate + Send + Sync + 'a>)> + 'a,
|
||||
P: Into<crate::paths::PathChunk> + std::fmt::Display,
|
||||
P: Into<crate::paths::PathChunk> + fmt::Display,
|
||||
{
|
||||
let mut success_results: VecDeque<OutputUnit<Annotations>> = VecDeque::new();
|
||||
let mut error_results = VecDeque::new();
|
||||
|
@ -283,7 +283,7 @@ impl Validate for SchemaNode {
|
|||
instance: &'instance serde_json::Value,
|
||||
instance_path: &JsonPointerNode,
|
||||
) -> ErrorIterator<'instance> {
|
||||
return Box::new(self.err_iter(instance, instance_path));
|
||||
Box::new(self.err_iter(instance, instance_path))
|
||||
}
|
||||
|
||||
fn is_valid(&self, instance: &serde_json::Value) -> bool {
|
||||
|
|
Loading…
Reference in New Issue