jsonschema_rs 0.60.2 → 0.61.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a56307e439b329704bd7a8e29e55cb2b2dd935f565a5b8d3d30da1d480947ce2
4
- data.tar.gz: 391a89618435402034a4b0bd164ff8ef38d3863ff7b3e69e1ff965c54b7c6620
3
+ metadata.gz: 7991fd779f7b3f79fa474601bb2e896fd7e68d6564a1d99bcef65e15c2aede23
4
+ data.tar.gz: 93d3052bf83414055a7b45e87f4be14f93ab2b908ec8e5ffad397dd8d8dd4a5d
5
5
  SHA512:
6
- metadata.gz: bd4784bf8572a56fa98533d18ee8cfca8b6de65abf687db51944e5dd5dfaf19f24ac35d1cf74fd7dff0d7533e3874df9c79d1af9745d31ba6b5f6f9f6834ba78
7
- data.tar.gz: b5593af7f28c81f4e84114ddabe6fc6553c1f6902b78d418f2bc570eec6dd82e3d2e08101ec86ea95f2e5088a7f75f1fcbb0bddffca331c6efd5f8f150971e80
6
+ metadata.gz: e5c53b7ee85c71f5001b64be6d97272a3530ddc724007a818dcfbf5a2a9fe01272ba18f7f9b427a62b1218122756ff573a7f0d0ddffc3313b147840c0916a381
7
+ data.tar.gz: 42b8fccd2e131105bb22ca79ddcf3fa6f4f65ebee3c944c047a5ea695b83366431bc3cbb8f2bf59e1720f011847c9a98873597074b8dad9e4ed47e24d93af19e
data/CHANGELOG.md CHANGED
@@ -2,6 +2,56 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.61.1] - 2026-11-10
6
+
7
+ ### Fixed
8
+
9
+ - `dereference` following `$ref` in keywords that hold data, such as `const` and `examples`. [#1858](https://github.com/Stranger6667/jsonschema/issues/1858)
10
+ - `pattern` over one character class under a large bounded count, such as `^.{0,404600}$`, failing with a regex engine error on the empty string when the size limit was raised to compile it.
11
+
12
+ ### Performance
13
+
14
+ - `pattern` and `patternProperties` with a large bounded count over one character class, such as `^.{0,262144}$` or `[^\p{C}]{1,2048}`, build without unrolling the count and fit the default size limit.
15
+ - `pattern` and `patternProperties` match anchored character-class patterns such as `^[a-z0-9-]+$` without a regex engine.
16
+
17
+ ## [0.61.0] - 2026-11-08
18
+
19
+ ### Fixed
20
+
21
+ - `.` in `pattern` and `patternProperties` matched `\r`, U+2028 and U+2029 (it should reject every line terminator).
22
+ - `evaluate()` reported a missing single `required` name beside `additionalProperties: false` at `/additionalProperties` (it should be `/required`).
23
+ - Numeric keywords misjudging whole floats past 2^53. [#1825](https://github.com/Stranger6667/jsonschema/issues/1825)
24
+ - Building a validator with an explicit draft retrieving the schema's `$schema` URI.
25
+ - `format: "date-time"`, `"date"` and `"time"` accepting `+`, `,`, `-`, `.` or `/` where RFC 3339 requires a digit. [#1829](https://github.com/Stranger6667/jsonschema/issues/1829)
26
+ - Numeric keywords misjudging instances against whole floats past 2^53 in the schema. [#1825](https://github.com/Stranger6667/jsonschema/issues/1825)
27
+ - `$ref` pointers through a numeric object key (`#/responses/200`) skipping the references under their target.
28
+ - `oneOf` / `anyOf` rejecting valid instances when a `$ref` inside a branch sits under an `$id`.
29
+ - `unevaluatedItems` treated every element as evaluated beside a non-schema `items` value (it should evaluate none).
30
+ - `validate!` raising `ValidationError` with an emptied `instance` for a value JSON cannot hold, where `each_error` and `evaluate` raise `EncodingError` or `TypeError`.
31
+
32
+ ### Performance
33
+
34
+ - Gems built from source up to 12% faster, from compiling the extension with link-time optimization.
35
+ - Building validators up to 15% faster on schemas that repeat the same `$ref`, from resolving each reference once.
36
+ - `Evaluation#list` up to 1.8x and `Evaluation#hierarchical` up to 3x faster, from building output units directly as Ruby objects.
37
+ - Building registries up to 30% faster and validators up to 3% faster, from a cheaper walk over schema documents.
38
+ - Building validators up to 25% faster on schemas that declare a base URI, from building absolute keyword locations on first use.
39
+ - Building validators up to 3% faster, from cheaper compilation cache keys.
40
+ - Validation errors on large values up to 40% faster, from returning the validated object as `ValidationError#instance` instead of a copy.
41
+ - `oneOf` / `anyOf` up to 7x faster when branches fix a property with `const` or `enum`.
42
+ - `oneOf` / `anyOf` skip branches that exclude the instance's value with `not` over `enum` or `const`.
43
+ - `properties` up to 40% faster on objects with a few more keys than it declares.
44
+ - `minLength` / `maxLength` skip counting code points when the byte length decides.
45
+ - `pattern` starting with lookaheads (`^(?=...)(?=...)...`) up to 2x faster.
46
+ - `properties` and `additionalProperties` up to 13% faster on schemas declaring 15 or more properties.
47
+ - `properties` up to 12% faster on objects with keys it does not declare.
48
+ - `unevaluatedProperties` up to 10% faster on schemas that combine it with `patternProperties` or applicators.
49
+ - `required` up to 40% faster when it lists every property of an object closed by `additionalProperties: false`.
50
+ - `properties`, `anyOf` and other applicators faster on subschemas that only check a non-numeric `type`, directly or through `$ref`.
51
+ - `evaluate()` up to 20% faster on instances with many errors, from fewer allocations per error.
52
+ - `evaluate()` up to 20% faster, from rendering instance locations only when the output reads them.
53
+ - `is_valid()` and `validate()` up to 14% faster on small instances, from a cheaper per-call validation context.
54
+
5
55
  ## [0.60.2] - 2026-10-27
6
56
 
7
57
  ### Fixed
@@ -697,7 +747,9 @@
697
747
 
698
748
  - Initial public release
699
749
 
700
- [Unreleased]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.60.2...HEAD
750
+ [Unreleased]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.1...HEAD
751
+ [0.61.1]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.61.0...ruby-v0.61.1
752
+ [0.61.0]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.60.2...ruby-v0.61.0
701
753
  [0.60.2]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.60.1...ruby-v0.60.2
702
754
  [0.60.1]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.60.0...ruby-v0.60.1
703
755
  [0.60.0]: https://github.com/Stranger6667/jsonschema/compare/ruby-v0.59.0...ruby-v0.60.0
data/Cargo.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "jsonschema-rb"
3
- version = "0.60.2"
3
+ version = "0.61.1"
4
4
  edition = "2021"
5
5
  authors = ["Dmitry Dygalo <dmitry@dygalo.dev>"]
6
6
  license = "MIT"
@@ -14,7 +14,7 @@ crate-type = ["cdylib"]
14
14
 
15
15
  [dependencies]
16
16
  strum = "0.28.0"
17
- jsonschema = { version = "0.60.2", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna"] }
17
+ jsonschema = { version = "0.61.1", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna"] }
18
18
  magnus = { version = "0.9", features = ["rb-sys"] }
19
19
  rb-sys = "0.9"
20
20
  serde = { workspace = true }
data/README.md CHANGED
@@ -726,9 +726,9 @@ Valid draft symbols: `:draft4`, `:draft6`, `:draft7`, `:draft201909`, `:draft202
726
726
 
727
727
  Compared with other Ruby validators:
728
728
 
729
- - **28-148x** faster than `json_schemer` for complex schemas and large instances
730
- - **200-567x** faster than `json-schema` where supported
731
- - **7-130x** faster than `rj_schema` (RapidJSON/C++)
729
+ - **95-1,241x** faster than `json_schemer` for complex schemas and large instances
730
+ - **960-1,033x** faster than `json-schema` where supported
731
+ - **24-179x** faster than `rj_schema` (RapidJSON/C++)
732
732
 
733
733
  Full results and methodology are in [BENCHMARKS.md](https://github.com/Stranger6667/jsonschema/blob/master/crates/jsonschema-rb/BENCHMARKS.md).
734
734
 
@@ -220,9 +220,9 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
220
220
 
221
221
  [[package]]
222
222
  name = "fancy-regex"
223
- version = "0.19.0"
223
+ version = "0.20.1"
224
224
  source = "registry+https://github.com/rust-lang/crates.io-index"
225
- checksum = "476de73bddf2ef8490aa4ee8f1cf40b430bf1d56c48c22080e5186952cd580e6"
225
+ checksum = "7b32c6266c2b14b0db7aa3409d3ee3f0ddda3b1d0279c4ba24fbec18af81d90e"
226
226
  dependencies = [
227
227
  "bit-set",
228
228
  "regex-automata",
@@ -693,9 +693,9 @@ dependencies = [
693
693
 
694
694
  [[package]]
695
695
  name = "jsonschema"
696
- version = "0.60.2"
696
+ version = "0.61.1"
697
697
  source = "registry+https://github.com/rust-lang/crates.io-index"
698
- checksum = "a42a11b47492e6a2cc76e9c7bcc8077776cb31dac444e0795d7f61bcc6441c08"
698
+ checksum = "e404978f72e1a21b53c96114b8a56e4cee7f17bd0a09b9c130875ed02a696f43"
699
699
  dependencies = [
700
700
  "ahash",
701
701
  "bytecount",
@@ -727,9 +727,9 @@ dependencies = [
727
727
 
728
728
  [[package]]
729
729
  name = "jsonschema-macros"
730
- version = "0.60.2"
730
+ version = "0.61.1"
731
731
  source = "registry+https://github.com/rust-lang/crates.io-index"
732
- checksum = "2b70c94dc0ea54d4a8f4b42becc5356a33dc203a421f99fdc551f72b6b8b8457"
732
+ checksum = "c6818bc23837bfa2d6caf3a39358b37f5abc4add05084b7bfc30c2c10d1cfaa1"
733
733
  dependencies = [
734
734
  "jsonschema-macros-core",
735
735
  "proc-macro2",
@@ -737,9 +737,9 @@ dependencies = [
737
737
 
738
738
  [[package]]
739
739
  name = "jsonschema-macros-core"
740
- version = "0.60.2"
740
+ version = "0.61.1"
741
741
  source = "registry+https://github.com/rust-lang/crates.io-index"
742
- checksum = "20fd89a50cb8da14c3a7be6bb6ba6b79e439723381008dece905b72412176b52"
742
+ checksum = "f0db6f7ef5249b9cc81f6dc20050e01bd352be935e72d9aabda9e63977445947"
743
743
  dependencies = [
744
744
  "fancy-regex",
745
745
  "indexmap",
@@ -756,7 +756,7 @@ dependencies = [
756
756
 
757
757
  [[package]]
758
758
  name = "jsonschema-rb-ext"
759
- version = "0.60.2"
759
+ version = "0.61.1"
760
760
  dependencies = [
761
761
  "jsonschema",
762
762
  "magnus",
@@ -770,18 +770,18 @@ dependencies = [
770
770
 
771
771
  [[package]]
772
772
  name = "jsonschema-regex"
773
- version = "0.60.2"
773
+ version = "0.61.1"
774
774
  source = "registry+https://github.com/rust-lang/crates.io-index"
775
- checksum = "107aeb6ff14b8deb5610096a8ce5c554ec89806b521147eaeb3cae05b07edb7a"
775
+ checksum = "84cdf272371326ec8db8ce2608a52635d8edeeaf0189604e2ad627327b79e6db"
776
776
  dependencies = [
777
777
  "regex-syntax",
778
778
  ]
779
779
 
780
780
  [[package]]
781
781
  name = "jsonschema-value"
782
- version = "0.60.2"
782
+ version = "0.61.1"
783
783
  source = "registry+https://github.com/rust-lang/crates.io-index"
784
- checksum = "e281d6b177bb4834f2ffd6f92aa0443cffe29c996b251c8d94eb6f456186feba"
784
+ checksum = "e5e4a7f3b3c19c9cd2aa37937e1704229a0bcb1b446308a148574d56ace0c6ba"
785
785
  dependencies = [
786
786
  "ahash",
787
787
  "bytecount",
@@ -842,9 +842,9 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
842
842
 
843
843
  [[package]]
844
844
  name = "magnus"
845
- version = "0.9.1"
845
+ version = "0.9.3"
846
846
  source = "registry+https://github.com/rust-lang/crates.io-index"
847
- checksum = "4c01bef153b8d0f086991f0e166474a1d57b738221f9a9c11405d498ac95a44d"
847
+ checksum = "40ef424404d166cbb71c8b8d19c9c589c748c4547c1afa1928c5504299f6c713"
848
848
  dependencies = [
849
849
  "magnus-macros",
850
850
  "rb-sys",
@@ -1137,9 +1137,9 @@ dependencies = [
1137
1137
 
1138
1138
  [[package]]
1139
1139
  name = "referencing"
1140
- version = "0.60.2"
1140
+ version = "0.61.1"
1141
1141
  source = "registry+https://github.com/rust-lang/crates.io-index"
1142
- checksum = "f42818036d3b37cda6bd4c494543158a36e431cb717015ef7c93acc6ba214d3b"
1142
+ checksum = "eba9bfd41f0d7d8fbf9c7ed23b788a3f97e9f5d9419be812ff7e08b8dc6b14ec"
1143
1143
  dependencies = [
1144
1144
  "ahash",
1145
1145
  "fluent-uri",
@@ -1404,9 +1404,9 @@ dependencies = [
1404
1404
 
1405
1405
  [[package]]
1406
1406
  name = "serde_json"
1407
- version = "1.0.151"
1407
+ version = "1.0.154"
1408
1408
  source = "registry+https://github.com/rust-lang/crates.io-index"
1409
- checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
1409
+ checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
1410
1410
  dependencies = [
1411
1411
  "itoa",
1412
1412
  "memchr",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "jsonschema-rb-ext"
3
- version = "0.60.2"
3
+ version = "0.61.1"
4
4
  edition = "2021"
5
5
  publish = false
6
6
 
@@ -10,13 +10,17 @@ name = "jsonschema_rb"
10
10
  path = "../../src/lib.rs"
11
11
 
12
12
  [dependencies]
13
- jsonschema = { version = "0.60.2", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna"] }
13
+ jsonschema = { version = "0.61.1", default-features = false, features = ["magnus", "arbitrary-precision", "resolve-http", "resolve-file", "tls-ring", "macros", "idna"] }
14
14
  magnus = { version = "0.9", features = ["rb-sys"] }
15
15
  rb-sys = "0.9"
16
- referencing = "0.60.2"
16
+ referencing = "0.61.1"
17
17
  serde = { version = "1", features = ["derive"] }
18
18
  serde_json = { version = "1", features = ["arbitrary_precision"] }
19
19
  strum = "0.28.0"
20
20
  zmij = "1"
21
21
 
22
22
  [workspace]
23
+
24
+ [profile.release]
25
+ lto = "fat"
26
+ codegen-units = 1
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module JSONSchema
4
- VERSION = "0.60.2"
4
+ VERSION = "0.61.1"
5
5
  end
data/src/evaluation.rs CHANGED
@@ -1,7 +1,8 @@
1
1
  //! Evaluation output wrapper for Ruby
2
2
  //!
3
3
  //! Provides full JSON Schema output format support: flag, list, and hierarchical.
4
- use magnus::{method, prelude::*, Error, RModule, Ruby, Value};
4
+ use jsonschema::{output::ErrorDescription, OutputUnit};
5
+ use magnus::{method, prelude::*, Error, RArray, RHash, RModule, Ruby, Value};
5
6
 
6
7
  use crate::{
7
8
  ser::{serialize_to_ruby, value_to_ruby},
@@ -14,6 +15,10 @@ define_rb_intern!(static ID_INSTANCE_LOCATION: "instanceLocation");
14
15
  define_rb_intern!(static ID_ANNOTATIONS: "annotations");
15
16
  define_rb_intern!(static ID_ERROR: "error");
16
17
  define_rb_intern!(static ID_VALID: "valid");
18
+ define_rb_intern!(static ID_EVALUATION_PATH: "evaluationPath");
19
+ define_rb_intern!(static ID_DROPPED_ANNOTATIONS: "droppedAnnotations");
20
+ define_rb_intern!(static ID_ERRORS: "errors");
21
+ define_rb_intern!(static ID_DETAILS: "details");
17
22
 
18
23
  #[magnus::wrap(class = "JSONSchema::Evaluation", free_immediately, size)]
19
24
  pub struct Evaluation {
@@ -39,14 +44,18 @@ impl Evaluation {
39
44
 
40
45
  /// Flat list of all evaluation results with annotations and errors.
41
46
  fn list(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
42
- let list_output = rb_self.inner.list();
43
- serialize_to_ruby(ruby, &list_output)
47
+ let root = rb_self.inner.root();
48
+ let details = ruby.ary_new();
49
+ list_units(ruby, root, details)?;
50
+ let hash = ruby.hash_new_capa(2);
51
+ hash.aset(ID_VALID.to_symbol(), root.valid())?;
52
+ hash.aset(ID_DETAILS.to_symbol(), details)?;
53
+ Ok(hash.as_value())
44
54
  }
45
55
 
46
56
  /// Nested tree structure following the schema structure.
47
57
  fn hierarchical(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
48
- let hierarchical_output = rb_self.inner.hierarchical();
49
- serialize_to_ruby(ruby, &hierarchical_output)
58
+ Ok(unit_to_ruby(ruby, rb_self.inner.root(), true)?.as_value())
50
59
  }
51
60
 
52
61
  fn annotations(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
@@ -99,6 +108,99 @@ impl Evaluation {
99
108
  }
100
109
  }
101
110
 
111
+ // Builds an output unit straight into a Ruby Hash, with the keys and order the serialized
112
+ // output has.
113
+ fn unit_to_ruby(ruby: &Ruby, unit: OutputUnit<'_>, nested: bool) -> Result<RHash, Error> {
114
+ // Key-value pairs inserted with one call, the order the serialized output has.
115
+ let mut pairs = [ruby.qnil().as_value(); 16];
116
+ let mut len = 0;
117
+ let mut push = |key: Value, value: Value| {
118
+ pairs[len] = key;
119
+ pairs[len + 1] = value;
120
+ len += 2;
121
+ };
122
+ push(
123
+ ID_VALID.to_symbol().as_value(),
124
+ ruby.into_value(unit.valid()),
125
+ );
126
+ push(
127
+ ID_EVALUATION_PATH.to_symbol().as_value(),
128
+ ruby.into_value(unit.evaluation_path().as_str()),
129
+ );
130
+ push(
131
+ ID_SCHEMA_LOCATION.to_symbol().as_value(),
132
+ ruby.into_value(unit.schema_location()),
133
+ );
134
+ push(
135
+ ID_INSTANCE_LOCATION.to_symbol().as_value(),
136
+ ruby.into_value(unit.instance_location().as_str()),
137
+ );
138
+ if let Some(annotations) = unit.annotations() {
139
+ push(
140
+ ID_ANNOTATIONS.to_symbol().as_value(),
141
+ serialize_to_ruby(ruby, annotations)?,
142
+ );
143
+ }
144
+ if let Some(annotations) = unit.dropped_annotations() {
145
+ push(
146
+ ID_DROPPED_ANNOTATIONS.to_symbol().as_value(),
147
+ serialize_to_ruby(ruby, annotations)?,
148
+ );
149
+ }
150
+ if !unit.errors().is_empty() {
151
+ push(
152
+ ID_ERRORS.to_symbol().as_value(),
153
+ errors_to_ruby(ruby, unit.errors())?.as_value(),
154
+ );
155
+ }
156
+ if nested {
157
+ let mut children = unit.children().peekable();
158
+ if children.peek().is_some() {
159
+ let details = ruby.ary_new();
160
+ for child in children {
161
+ details.push(unit_to_ruby(ruby, child, true)?)?;
162
+ }
163
+ push(ID_DETAILS.to_symbol().as_value(), details.as_value());
164
+ }
165
+ }
166
+ let hash = ruby.hash_new_capa(len / 2);
167
+ hash.bulk_insert(&pairs[..len])?;
168
+ Ok(hash)
169
+ }
170
+
171
+ fn list_units(ruby: &Ruby, unit: OutputUnit<'_>, out: RArray) -> Result<(), Error> {
172
+ out.push(unit_to_ruby(ruby, unit, false)?)?;
173
+ for child in unit.children() {
174
+ list_units(ruby, child, out)?;
175
+ }
176
+ Ok(())
177
+ }
178
+
179
+ /// Messages grouped by keyword in first-seen order: one message as a String, several as an Array.
180
+ fn errors_to_ruby(ruby: &Ruby, errors: &[ErrorDescription]) -> Result<RHash, Error> {
181
+ let hash = ruby.hash_new();
182
+ // ponytail: quadratic in a unit's errors, which hold about one per keyword.
183
+ for (index, error) in errors.iter().enumerate() {
184
+ let keyword = error.keyword();
185
+ if errors[..index].iter().any(|seen| seen.keyword() == keyword) {
186
+ continue;
187
+ }
188
+ let mut messages = errors[index..]
189
+ .iter()
190
+ .filter(|other| other.keyword() == keyword)
191
+ .map(ErrorDescription::message);
192
+ let first = messages.next().expect("the current error has this keyword");
193
+ match messages.next() {
194
+ None => hash.aset(keyword, first)?,
195
+ Some(second) => {
196
+ let all = ruby.ary_from_iter([first, second].into_iter().chain(messages));
197
+ hash.aset(keyword, all)?;
198
+ }
199
+ }
200
+ }
201
+ Ok(hash)
202
+ }
203
+
102
204
  pub fn define_class(ruby: &Ruby, module: &RModule) -> Result<(), Error> {
103
205
  let class = module.define_class("Evaluation", ruby.class_object())?;
104
206
  class.define_method("valid?", method!(Evaluation::is_valid, 0))?;
data/src/lib.rs CHANGED
@@ -24,16 +24,18 @@ use jsonschema::{
24
24
  ValidationOptions,
25
25
  };
26
26
  use magnus::{
27
+ encoding::Coderange,
27
28
  error::ErrorType,
28
29
  function, method,
29
30
  prelude::*,
31
+ r_hash::ForEach,
30
32
  rb_sys::AsRawValue,
31
33
  scan_args::scan_args,
32
34
  value::{Lazy, ReprValue},
33
- DataTypeFunctions, Error, Exception, ExceptionClass, RClass, RHash, RModule, RObject, RString,
34
- Ruby, Value,
35
+ DataTypeFunctions, Error, Exception, ExceptionClass, RArray, RClass, RHash, RModule, RObject,
36
+ RString, Ruby, Value,
35
37
  };
36
- use referencing::unescape_segment;
38
+ use referencing::{parse_index, unescape_segment};
37
39
  use std::{
38
40
  cell::RefCell,
39
41
  collections::VecDeque,
@@ -386,6 +388,77 @@ fn error_message(error: &jsonschema::ValidationError<'_>, mask: Option<&str>) ->
386
388
  }
387
389
  }
388
390
 
391
+ // The object at `location` under `root`, when it and everything in it are plain JSON types, which
392
+ // convert to and from JSON unchanged. Other values keep their JSON form.
393
+ fn plain_instance_at(ruby: &Ruby, root: RbNode<'_>, location: &str) -> Option<Value> {
394
+ #[allow(unsafe_code)]
395
+ let mut current: Value = unsafe { magnus::rb_sys::FromRawValue::from_raw(root.raw()) };
396
+ for segment in location.split('/').skip(1) {
397
+ current = if let Some(hash) = RHash::from_value(current) {
398
+ if hash.class().as_raw() != ruby.class_hash().as_raw() {
399
+ return None;
400
+ }
401
+ hash.get(unescape_segment(segment).as_ref())?
402
+ } else {
403
+ let array = RArray::from_value(current)?;
404
+ let index = parse_index(segment)?;
405
+ if index >= array.len() {
406
+ return None;
407
+ }
408
+ array.entry(isize::try_from(index).ok()?).ok()?
409
+ };
410
+ }
411
+ is_plain_json(ruby, current, 0).then_some(current)
412
+ }
413
+
414
+ fn is_plain_json(ruby: &Ruby, value: Value, depth: u16) -> bool {
415
+ // Deeper values, cycles included, keep the conversion that reports the nesting limit.
416
+ if depth >= ser::RECURSION_LIMIT {
417
+ return false;
418
+ }
419
+ if value.is_nil()
420
+ || value.is_kind_of(ruby.class_true_class())
421
+ || value.is_kind_of(ruby.class_false_class())
422
+ {
423
+ return true;
424
+ }
425
+ let class = value.class().as_raw();
426
+ let is = |expected: RClass| class == expected.as_raw();
427
+ if is(ruby.class_integer()) || is(ruby.class_float()) {
428
+ return true;
429
+ }
430
+ if is(ruby.class_string()) {
431
+ let string = RString::from_value(value).expect("an instance of String");
432
+ return string.is_utf8_compatible_encoding()
433
+ && string.enc_coderange_scan() != Coderange::Broken;
434
+ }
435
+ if is(ruby.class_array()) {
436
+ let array = RArray::from_value(value).expect("an instance of Array");
437
+ return (0..array.len()).all(|index| {
438
+ isize::try_from(index)
439
+ .ok()
440
+ .and_then(|index| array.entry::<Value>(index).ok())
441
+ .is_some_and(|item| is_plain_json(ruby, item, depth + 1))
442
+ });
443
+ }
444
+ if is(ruby.class_hash()) {
445
+ let hash = RHash::from_value(value).expect("an instance of Hash");
446
+ let mut plain = true;
447
+ let _ = hash.foreach(|key: Value, item: Value| {
448
+ plain = key.class().as_raw() == ruby.class_string().as_raw()
449
+ && is_plain_json(ruby, key, depth + 1)
450
+ && is_plain_json(ruby, item, depth + 1);
451
+ Ok(if plain {
452
+ ForEach::Continue
453
+ } else {
454
+ ForEach::Stop
455
+ })
456
+ });
457
+ return plain;
458
+ }
459
+ false
460
+ }
461
+
389
462
  /// Convert a jsonschema `ValidationError` to a Ruby `ValidationError`.
390
463
  fn into_ruby_error(
391
464
  ruby: &Ruby,
@@ -422,7 +495,16 @@ fn into_ruby_error(
422
495
  };
423
496
 
424
497
  let kind_obj = ValidationErrorKind::new(ruby, &parts.kind, mask)?;
425
- let rb_instance = ser::value_to_ruby(ruby, parts.instance.as_ref())?;
498
+ // Scalars convert faster than the path to them is followed.
499
+ let original = match parts.instance.as_ref() {
500
+ serde_json::Value::Array(_) | serde_json::Value::Object(_) => root_instance
501
+ .and_then(|root| plain_instance_at(ruby, root, parts.instance_path.as_str())),
502
+ _ => None,
503
+ };
504
+ let rb_instance = match original {
505
+ Some(instance) => instance,
506
+ None => ser::value_to_ruby(ruby, parts.instance.as_ref())?,
507
+ };
426
508
 
427
509
  let exc_class = ruby.get_inner(&VALIDATION_ERROR_CLASS);
428
510
 
@@ -565,11 +647,12 @@ fn surface_pending_errors<T>(
565
647
  if let Some(error) = magnus_take_pending_error() {
566
648
  return Err(Error::from(error));
567
649
  }
568
- let result = run(node)?;
650
+ // Checked before `run`'s own error: converting a validation error records what it cannot read.
651
+ let result = run(node);
569
652
  if let Some(error) = magnus_take_pending_error() {
570
653
  return Err(Error::from(error));
571
654
  }
572
- Ok(result)
655
+ result
573
656
  }
574
657
 
575
658
  /// Wrapper around `jsonschema::Validator`.
data/src/ser.rs CHANGED
@@ -31,10 +31,12 @@ static BIG_DECIMAL_CLASS: Lazy<RClass> = Lazy::new(|ruby| {
31
31
  cls
32
32
  });
33
33
 
34
- const RECURSION_LIMIT: u16 = 255;
34
+ pub(crate) const RECURSION_LIMIT: u16 = 255;
35
35
  const I64_LOWER_INCLUSIVE_F64: f64 = -9_223_372_036_854_775_808.0;
36
36
  const I64_UPPER_EXCLUSIVE_F64: f64 = 9_223_372_036_854_775_808.0;
37
37
  const U64_UPPER_EXCLUSIVE_F64: f64 = 18_446_744_073_709_551_616.0;
38
+ /// 2^53, from which consecutive integers are no longer all representable as `f64`.
39
+ const MAX_SAFE_INTEGER_F64: f64 = 9_007_199_254_740_992.0;
38
40
  const IEEE754_F64_FRAC_BITS: u32 = 52;
39
41
  const IEEE754_F64_EXP_BIAS: i32 = 1023;
40
42
  const DECIMAL_BASE_U64: u64 = 1_000_000_000;
@@ -128,6 +130,14 @@ fn to_value_typed(
128
130
  #[inline]
129
131
  fn convert_float(ruby: &Ruby, value: Value) -> Result<JsonValue, Error> {
130
132
  let float = f64::try_convert(value)?;
133
+ // From 2^53 up, the shortest text of a whole float can name a neighbouring integer:
134
+ // `2.0**55` prints as `3.602879701896397e16`. Keep its exact digits.
135
+ if float.fract() == 0.0 && float.abs() >= MAX_SAFE_INTEGER_F64 {
136
+ return format!("{float:.1}")
137
+ .parse()
138
+ .map(JsonValue::Number)
139
+ .map_err(|error| Error::new(ruby.exception_arg_error(), error.to_string()));
140
+ }
131
141
  Number::from_f64(float)
132
142
  .map(JsonValue::Number)
133
143
  .ok_or_else(|| {
@@ -812,8 +822,10 @@ fn number_string_to_ruby(ruby: &Ruby, number: &str) -> Result<Value, Error> {
812
822
  }
813
823
 
814
824
  if let Ok(f) = number.parse::<f64>() {
825
+ // A whole float past 2^53 is written with its exact digits, which its shortest text can miss.
815
826
  if f.is_finite()
816
- && Number::from_f64(f).is_some_and(|roundtrip| roundtrip.to_string() == number)
827
+ && (Number::from_f64(f).is_some_and(|roundtrip| roundtrip.to_string() == number)
828
+ || (f.fract() == 0.0 && format!("{f:.1}") == number))
817
829
  {
818
830
  return Ok(ruby.into_value(f));
819
831
  }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jsonschema_rs
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.60.2
4
+ version: 0.61.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dygalo
@@ -80,7 +80,7 @@ metadata:
80
80
  homepage_uri: https://github.com/Stranger6667/jsonschema/tree/master/crates/jsonschema-rb
81
81
  source_code_uri: https://github.com/Stranger6667/jsonschema
82
82
  changelog_uri: https://github.com/Stranger6667/jsonschema/blob/master/crates/jsonschema-rb/CHANGELOG.md
83
- documentation_uri: https://github.com/Stranger6667/jsonschema/blob/ruby-v0.60.2/crates/jsonschema-rb/README.md
83
+ documentation_uri: https://github.com/Stranger6667/jsonschema/blob/ruby-v0.61.1/crates/jsonschema-rb/README.md
84
84
  bug_tracker_uri: https://github.com/Stranger6667/jsonschema/issues
85
85
  funding_uri: https://github.com/sponsors/Stranger6667
86
86
  rubygems_mfa_required: 'true'