Skip to content

Commit

Permalink
feat: Rework public API
Browse files Browse the repository at this point in the history
Signed-off-by: Dmitry Dygalo <dmitry@dygalo.dev>
  • Loading branch information
Stranger6667 committed Sep 17, 2024
1 parent d8eb69d commit d0e63c0
Show file tree
Hide file tree
Showing 24 changed files with 1,015 additions and 470 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
assert!(jsonschema::is_valid(&schema, &instance));

// Build & reuse (faster)
let validator = jsonschema::compile(&schema)
let validator = jsonschema::validator_for(&schema)
.expect("Invalid schema");

// Iterate over errors
Expand Down
2 changes: 1 addition & 1 deletion crates/benchmark-suite/benches/boon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
b.iter(|| {
compiler
.compile("schema.json", &mut Schemas::new())
.expect("Failed to compiled");
.expect("Failed to compile");
})
});
}
Expand Down
11 changes: 5 additions & 6 deletions crates/benchmark-suite/benches/jsonschema.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
use benchmark::Benchmark;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use jsonschema::JSONSchema;
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("jsonschema/{}/compile", name), |b| {
b.iter(|| JSONSchema::compile(schema).expect("Valid schema"))
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}

fn bench_is_valid(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(name, "is_valid"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.is_valid(instance);
let _ = validator.is_valid(instance);
})
},
);
}

fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(name, "validate"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.validate(instance);
let _ = validator.validate(instance);
})
},
);
Expand Down
4 changes: 2 additions & 2 deletions crates/benchmark-suite/benches/valico.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {

fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let mut scope = json_schema::Scope::new();
let compiled = scope
let validator = scope
.compile_and_return(schema.clone(), false)
.expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(name, "validate"),
instance,
|b, instance| {
b.iter(|| {
compiled.validate(instance).is_valid();
validator.validate(instance).is_valid();
})
},
);
Expand Down
7 changes: 3 additions & 4 deletions crates/jsonschema-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::{
};

use clap::Parser;
use jsonschema::JSONSchema;

#[derive(Parser)]
#[command(name = "jsonschema")]
Expand Down Expand Up @@ -40,11 +39,11 @@ fn validate_instances(
let mut success = true;

let schema_json = read_json(schema_path)??;
match JSONSchema::compile(&schema_json) {
Ok(schema) => {
match jsonschema::validator_for(&schema_json) {
Ok(validator) => {
for instance in instances {
let instance_json = read_json(instance)??;
let validation = schema.validate(&instance_json);
let validation = validator.validate(&instance_json);
let filename = instance.to_string_lossy();
match validation {
Ok(()) => println!("{filename} - VALID"),
Expand Down
40 changes: 20 additions & 20 deletions crates/jsonschema-py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ fn make_options(
draft: Option<u8>,
formats: Option<&Bound<'_, PyDict>>,
) -> PyResult<jsonschema::CompilationOptions> {
let mut options = jsonschema::JSONSchema::options();
let mut options = jsonschema::options();
if let Some(raw_draft_version) = draft {
options.with_draft(get_draft(raw_draft_version)?);
}
Expand Down Expand Up @@ -166,14 +166,14 @@ fn make_options(

fn iter_on_error(
py: Python<'_>,
compiled: &jsonschema::JSONSchema,
validator: &jsonschema::JSONSchema,
instance: &Bound<'_, PyAny>,
) -> PyResult<ValidationErrorIter> {
let instance = ser::to_value(instance)?;
let mut pyerrors = vec![];

panic::catch_unwind(AssertUnwindSafe(|| {
if let Err(errors) = compiled.validate(&instance) {
if let Err(errors) = validator.validate(&instance) {
for error in errors {
pyerrors.push(into_py_err(py, error)?);
}
Expand All @@ -188,11 +188,11 @@ fn iter_on_error(

fn raise_on_error(
py: Python<'_>,
compiled: &jsonschema::JSONSchema,
validator: &jsonschema::JSONSchema,
instance: &Bound<'_, PyAny>,
) -> PyResult<()> {
let instance = ser::to_value(instance)?;
let result = panic::catch_unwind(AssertUnwindSafe(|| compiled.validate(&instance)))
let result = panic::catch_unwind(AssertUnwindSafe(|| validator.validate(&instance)))
.map_err(handle_format_checked_panic)?;
let error = result
.err()
Expand Down Expand Up @@ -277,9 +277,9 @@ fn is_valid(
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => {
Ok(validator) => {
let instance = ser::to_value(instance)?;
panic::catch_unwind(AssertUnwindSafe(|| Ok(compiled.is_valid(&instance))))
panic::catch_unwind(AssertUnwindSafe(|| Ok(validator.is_valid(&instance))))
.map_err(handle_format_checked_panic)?
}
Err(error) => Err(into_py_err(py, error)?),
Expand Down Expand Up @@ -311,7 +311,7 @@ fn validate(
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => raise_on_error(py, &compiled, instance),
Ok(validator) => raise_on_error(py, &validator, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}
Expand Down Expand Up @@ -340,17 +340,17 @@ fn iter_errors(
let options = make_options(draft, formats)?;
let schema = ser::to_value(schema)?;
match options.compile(&schema) {
Ok(compiled) => iter_on_error(py, &compiled, instance),
Ok(validator) => iter_on_error(py, &validator, instance),
Err(error) => Err(into_py_err(py, error)?),
}
}

/// JSONSchema(schema, draft=None, with_meta_schemas=False)
///
/// JSON Schema compiled into a validation tree.
/// A JSON Schema validator.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// >>> validator = JSONSchema({"minimum": 5})
/// >>> validator.is_valid(3)
/// False
///
/// By default Draft 7 will be used for compilation.
Expand Down Expand Up @@ -409,7 +409,7 @@ impl JSONSchema {
///
/// Create `JSONSchema` from a serialized JSON string.
///
/// >>> compiled = JSONSchema.from_str('{"minimum": 5}')
/// >>> validator = JSONSchema.from_str('{"minimum": 5}')
///
/// Use it if you have your schema as a string and want to utilize Rust JSON parsing.
#[classmethod]
Expand Down Expand Up @@ -451,10 +451,10 @@ impl JSONSchema {

/// is_valid(instance)
///
/// Perform fast validation against the compiled schema.
/// Perform fast validation against the schema.
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.is_valid(3)
/// >>> validator = JSONSchema({"minimum": 5})
/// >>> validator.is_valid(3)
/// False
///
/// The output is a boolean value, that indicates whether the instance is valid or not.
Expand All @@ -469,8 +469,8 @@ impl JSONSchema {
///
/// Validate the input instance and raise `ValidationError` in the error case
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> compiled.validate(3)
/// >>> validator = JSONSchema({"minimum": 5})
/// >>> validator.validate(3)
/// ...
/// ValidationError: 3 is less than the minimum of 5
///
Expand All @@ -484,8 +484,8 @@ impl JSONSchema {
///
/// Iterate the validation errors of the input instance
///
/// >>> compiled = JSONSchema({"minimum": 5})
/// >>> next(compiled.iter_errors(3))
/// >>> validator = JSONSchema({"minimum": 5})
/// >>> next(validator.iter_errors(3))
/// ...
/// ValidationError: 3 is less than the minimum of 5
#[pyo3(text_signature = "(instance)")]
Expand Down
11 changes: 5 additions & 6 deletions crates/jsonschema/benches/jsonschema.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
use benchmark::Benchmark;
use codspeed_criterion_compat::{criterion_group, criterion_main, BenchmarkId, Criterion};
use jsonschema::JSONSchema;
use serde_json::Value;

fn bench_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("{}/compile", name), |b| {
b.iter(|| JSONSchema::compile(schema).expect("Valid schema"))
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}

fn bench_is_valid(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(name, "is_valid"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.is_valid(instance);
let _ = validator.is_valid(instance);
})
},
);
}

fn bench_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(name, "validate"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.validate(instance);
let _ = validator.validate(instance);
})
},
);
Expand Down
11 changes: 5 additions & 6 deletions crates/jsonschema/benches/keywords.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
use benchmark::run_keyword_benchmarks;
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use jsonschema::JSONSchema;
use serde_json::Value;

fn bench_keyword_compile(c: &mut Criterion, name: &str, schema: &Value) {
c.bench_function(&format!("keyword/{}/compile", name), |b| {
b.iter(|| JSONSchema::compile(schema).expect("Valid schema"))
b.iter(|| jsonschema::validator_for(schema).expect("Valid schema"))
});
}

fn bench_keyword_is_valid(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(format!("keyword/{}", name), "is_valid"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.is_valid(instance);
let _ = validator.is_valid(instance);
})
},
);
}

fn bench_keyword_validate(c: &mut Criterion, name: &str, schema: &Value, instance: &Value) {
let compiled = JSONSchema::compile(schema).expect("Valid schema");
let validator = jsonschema::validator_for(schema).expect("Valid schema");
c.bench_with_input(
BenchmarkId::new(format!("keyword/{}", name), "validate"),
instance,
|b, instance| {
b.iter(|| {
let _ = compiled.validate(instance);
let _ = validator.validate(instance);
})
},
);
Expand Down
Loading

0 comments on commit d0e63c0

Please sign in to comment.