nosj 0.4.0 → 0.4.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: d57a15d6dbdf7dc81518662ef44348f538b6dcf2a95098c3491c741b9e2517b6
4
- data.tar.gz: e5508e9cf8ea61c51e21599ef4a887f024ab08a920a0c642dfcb3ac7fd7b4954
3
+ metadata.gz: 938bbe04908f0865a510008040c4a1bf8f1e4b1cb80821de3757e3ac078f2e47
4
+ data.tar.gz: feea0d89e6f7559642127a2333d01cc3f93b1d3763e54f6ed620b596a7102d30
5
5
  SHA512:
6
- metadata.gz: 9a7797c890345c879153069e63808fa916fe0e5944376680a86ba30696ef7eec16a6a0f45ae7c428c08783c56bb1a08bed448c27d3b7a7075caea064edee4205
7
- data.tar.gz: 29113d820443054acafaeda1a976f4a388424466d79d09353fac5980cc80d803937a800b6384ed9395d9386735420cbd378cc8a6e6629cd5bdbefd1bd70fd5bd
6
+ metadata.gz: b1ff3aef1231141f9333030016f1ff308a81ca27a1ad8318fadf2ce42c77869756c5674716485c4b5be4ca948290f4450142c59eed76df2894bde460cd0530bc
7
+ data.tar.gz: 5e40f2cfb493c13b546ef3367e02efafb7eea5697181b0daad9efeed89f06db58b0db798cd5cad2f09555ee900c673753595584829ab333bdc125c45eaeca41a
data/CHANGELOG.md CHANGED
@@ -1,3 +1,47 @@
1
+ ## [0.4.1] - 2026-09-25
2
+
3
+ - Fixed a crash in `NOSJ.generate`: an object whose `to_json` or
4
+ `to_s` shrank the array being generated (for example with
5
+ `Array#clear`) made the generator read freed memory, usually a
6
+ segfault. The array length is now re-read for every element, like
7
+ the json gem, so elements a callback appends are emitted too.
8
+ - Fixed memory corruption in `NOSJ.splice`: a replacement value whose
9
+ `to_json` modified the source string, deduplicated a frozen String
10
+ subclass (`-str`), or removed entries from the edits hash could make
11
+ splice read freed memory, copying unrelated heap bytes into the
12
+ result or crashing. All values are now generated before the source
13
+ is read.
14
+ - Fixed `NOSJ.lazy` and `NOSJ.each_line` reading freed memory when the
15
+ source is a frozen String subclass (such as
16
+ `ActiveSupport::SafeBuffer`) or a frozen string carrying instance
17
+ variables, and it is deduplicated with `-str` while the lazy
18
+ document is alive or between lines: Ruby swaps such a string's
19
+ buffer, and the old one kept being read (wrong values, or a crash).
20
+ - Fixed a memory leak in `NOSJ.generate` and `NOSJ.write_file`: an
21
+ exception raised by user code the generator calls bypassed its
22
+ cleanup and leaked its output buffer (megabytes per call after large
23
+ documents). Affected: a raising `respond_to?` or
24
+ `respond_to_missing?`, a raising `to_s` on an encoding-conversion
25
+ error, a raising autoload of `JSON::Fragment` (strict and Rails
26
+ modes), and a raising `Errno` constructor for a failed write. The
27
+ exception still propagates unchanged.
28
+ - Fixed: after a `NoMemoryError` in the middle of a parse (or
29
+ `minify`/`reformat`), the next call on that thread aborted the whole
30
+ process. Per-thread parser state is now recovered instead.
31
+ - `NOSJ::Lazy` nodes now take part in generational GC: holding many
32
+ nodes no longer slows down every minor GC (200,000 live nodes: 2.9 ms
33
+ per minor GC before, 0.1 ms now), and they are freed immediately
34
+ when collected.
35
+ - Fixed: lazy documents opened with `allow_trailing_comma: true` or
36
+ `allow_nan: true` could not be walked. `size`, `keys`, `each`, and
37
+ any lookup that missed or stepped over a trailing comma or a `NaN`
38
+ raised `NOSJ::ParserError`, even though `value` worked.
39
+ - `NOSJ.at_pointer`, `NOSJ.at_pointers`, and `NOSJ.at_pointer_file`
40
+ now honor `allow_nan` and `allow_trailing_comma` while resolving the
41
+ pointer, not only when materializing the matched value.
42
+ - Updated the nosj crate to 0.2.2.
43
+ - Updated dependencies, Magnus bumped to 0.9.0.
44
+
1
45
  ## [0.4.0] - 2026-09-05
2
46
 
3
47
  - Ractors: on Ruby 4.0+, `NOSJ.parse`, `NOSJ.generate`, and every
data/Cargo.lock CHANGED
@@ -44,9 +44,9 @@ dependencies = [
44
44
 
45
45
  [[package]]
46
46
  name = "bitflags"
47
- version = "2.13.1"
47
+ version = "2.13.2"
48
48
  source = "registry+https://github.com/rust-lang/crates.io-index"
49
- checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
49
+ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
50
50
 
51
51
  [[package]]
52
52
  name = "cexpr"
@@ -59,9 +59,9 @@ dependencies = [
59
59
 
60
60
  [[package]]
61
61
  name = "cfg-if"
62
- version = "1.0.4"
62
+ version = "1.0.5"
63
63
  source = "registry+https://github.com/rust-lang/crates.io-index"
64
- checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
64
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
65
65
 
66
66
  [[package]]
67
67
  name = "clang-sys"
@@ -137,9 +137,9 @@ dependencies = [
137
137
 
138
138
  [[package]]
139
139
  name = "magnus"
140
- version = "0.8.2"
140
+ version = "0.9.0"
141
141
  source = "registry+https://github.com/rust-lang/crates.io-index"
142
- checksum = "3b36a5b126bbe97eb0d02d07acfeb327036c6319fd816139a49824a83b7f9012"
142
+ checksum = "379d50b6eea4ca84074ccd3e551eb9b07f7865194d5b3198325317e9ef78e5e9"
143
143
  dependencies = [
144
144
  "magnus-macros",
145
145
  "rb-sys",
@@ -149,9 +149,9 @@ dependencies = [
149
149
 
150
150
  [[package]]
151
151
  name = "magnus-macros"
152
- version = "0.8.0"
152
+ version = "0.9.0"
153
153
  source = "registry+https://github.com/rust-lang/crates.io-index"
154
- checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
154
+ checksum = "4ca70566af98184bb92d4d9853daaf533c1a3418b9570d0547ea44970035f3fe"
155
155
  dependencies = [
156
156
  "proc-macro2",
157
157
  "quote",
@@ -191,16 +191,16 @@ dependencies = [
191
191
 
192
192
  [[package]]
193
193
  name = "nosj"
194
- version = "0.2.0"
194
+ version = "0.2.2"
195
195
  source = "registry+https://github.com/rust-lang/crates.io-index"
196
- checksum = "d25913644b7871b36095cc3da27daf95ebf9508189c5d8ccfb16da3bdb9f802f"
196
+ checksum = "3d398b0019f2d8bf39b10de6038451b0f3d96a9e3111748097192d8f57d6f120"
197
197
  dependencies = [
198
198
  "fast-float2",
199
199
  ]
200
200
 
201
201
  [[package]]
202
202
  name = "nosj_native"
203
- version = "0.4.0"
203
+ version = "0.4.1"
204
204
  dependencies = [
205
205
  "ahash",
206
206
  "magnus",
@@ -335,9 +335,9 @@ dependencies = [
335
335
 
336
336
  [[package]]
337
337
  name = "unicode-ident"
338
- version = "1.0.24"
338
+ version = "1.0.26"
339
339
  source = "registry+https://github.com/rust-lang/crates.io-index"
340
- checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
340
+ checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
341
341
 
342
342
  [[package]]
343
343
  name = "version_check"
@@ -368,18 +368,18 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
368
368
 
369
369
  [[package]]
370
370
  name = "zerocopy"
371
- version = "0.8.56"
371
+ version = "0.8.58"
372
372
  source = "registry+https://github.com/rust-lang/crates.io-index"
373
- checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"
373
+ checksum = "c17e8fafad82b542ff3717217ecdc736231b59e387768c9630123b4ce4d2db44"
374
374
  dependencies = [
375
375
  "zerocopy-derive",
376
376
  ]
377
377
 
378
378
  [[package]]
379
379
  name = "zerocopy-derive"
380
- version = "0.8.56"
380
+ version = "0.8.58"
381
381
  source = "registry+https://github.com/rust-lang/crates.io-index"
382
- checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"
382
+ checksum = "595f56e044df4f46a0c9a626f65c3d99eb8488f7e8a8baa12dd76326d9710bf2"
383
383
  dependencies = [
384
384
  "proc-macro2",
385
385
  "quote",
data/README.md CHANGED
@@ -151,7 +151,8 @@ Example: an early field resolves in ~0.35µs where `JSON.parse(json).dig(...)`
151
151
  costs ~980µs on the same document—three orders of magnitude. A field
152
152
  at the far end of a 570 KB document costs ~71µs, still 13× faster
153
153
  than parse-then-dig. Misses return nil; matched subtrees materialize
154
- with the same options as `parse` (`symbolize_names:`, `freeze:`).
154
+ with the same options as `parse` (`symbolize_names:`, `freeze:`), and
155
+ `allow_nan:`/`allow_trailing_comma:` govern the walk to them too.
155
156
 
156
157
  ### Files API
157
158
 
data/ext/nosj/Cargo.toml CHANGED
@@ -5,7 +5,7 @@
5
5
  # required by lib/nosj.rb as "nosj/nosj" (Init_nosj set explicitly in
6
6
  # lib.rs). Gem name, module, and API are plain nosj.
7
7
  name = "nosj_native"
8
- version = "0.4.0"
8
+ version = "0.4.1"
9
9
  edition = "2021"
10
10
  authors = ["Yaroslav Markin <yaroslav@markin.net>"]
11
11
  license = "MIT"
@@ -16,13 +16,13 @@ name = "nosj"
16
16
  crate-type = ["cdylib", "rlib"]
17
17
 
18
18
  [dependencies]
19
- magnus = { version = "0.8", features = ["rb-sys"] }
20
- rb-sys = { version = "0.9.124", default-features = false }
21
- ahash = "0.8.11"
19
+ magnus = { version = "0.9", features = ["rb-sys"] }
20
+ rb-sys = { version = "0.9.130", default-features = false }
21
+ ahash = "0.8.12"
22
22
  # Read-only file mapping for the file entry points (load_lazy_file,
23
23
  # at_pointer_file, dig_file): pages never touched are never read.
24
- memmap2 = "0.9"
24
+ memmap2 = "0.9.11"
25
25
  # First-party SIMD JSON parse/generate library (github.com/yaroslav/nosj).
26
26
  # For coordinated crate+gem work, temporarily flip to
27
27
  # { path = "../../../nosj" } and restore before any commit or release.
28
- nosj = "0.2.0"
28
+ nosj = "0.2.2"
@@ -13,7 +13,7 @@ libfuzzer-sys = "0.4"
13
13
  # crate. Only this harness enables "embed" (rb-sys/link-ruby): fuzz
14
14
  # binaries host their own VM, while the extension must never link
15
15
  # libruby (its symbols resolve from the host process at load time).
16
- magnus = { version = "0.8", features = ["embed", "rb-sys"] }
16
+ magnus = { version = "0.9", features = ["embed", "rb-sys"] }
17
17
  # The extension as an rlib; its lib target is named `nosj` (the bundle
18
18
  # name), so rename the dependency to keep fuzz code readable.
19
19
  nosj_ext = { path = "..", package = "nosj_native" }
@@ -10,7 +10,7 @@
10
10
  //! I/O failures raise the mapped `Errno::*` exception, like `File`
11
11
  //! methods do.
12
12
 
13
- use std::cell::RefCell;
13
+ use std::cell::Cell;
14
14
  use std::fs;
15
15
  use std::io::Read;
16
16
 
@@ -22,14 +22,15 @@ use crate::gen;
22
22
  use crate::lazy::{self, DocBytes};
23
23
  use crate::parse::{err, materialize, materialize_at, parse_native_opts, span_of, ParseNativeOpts};
24
24
  use crate::pointer::path_to_pointer;
25
- use crate::state::PULL_STATE;
25
+ use crate::state::{with_pull_state, with_taken};
26
26
 
27
27
  const NOT_UTF8: &str = "input is not valid UTF-8";
28
28
 
29
29
  thread_local! {
30
30
  /// Reused read buffer for `load_file`: capacity survives across
31
- /// calls, so a hot loop over files allocates nothing.
32
- static FILE_BUF: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
31
+ /// calls, so a hot loop over files allocates nothing (see
32
+ /// `state::with_taken`).
33
+ static FILE_BUF: Cell<Vec<u8>> = const { Cell::new(Vec::new()) };
33
34
  }
34
35
 
35
36
  /// On Unix the raw OS error IS the errno `rb_syserr_new` expects.
@@ -58,6 +59,9 @@ fn errno_of(e: &std::io::Error) -> Option<i32> {
58
59
 
59
60
  /// Map an I/O failure onto the matching `Errno::*` exception (class
60
61
  /// parity with `File.read`/`File.write`; the message carries the path).
62
+ /// Constructing it runs the class's `initialize` (overridable Ruby), so
63
+ /// the call is protected; a raise there propagates in its place, as it
64
+ /// would from `File.read`.
61
65
  fn io_error(ruby: &Ruby, path: &str, e: &std::io::Error) -> Error {
62
66
  use magnus::rb_sys::FromRawValue;
63
67
  let Some(errno) = errno_of(e) else {
@@ -66,8 +70,13 @@ fn io_error(ruby: &Ruby, path: &str, e: &std::io::Error) -> Error {
66
70
  let Ok(cpath) = std::ffi::CString::new(path) else {
67
71
  return runtime_error(ruby, format!("{e} - {path}"));
68
72
  };
73
+ let raw =
74
+ match magnus::rb_sys::protect(|| unsafe { rb_sys::rb_syserr_new(errno, cpath.as_ptr()) }) {
75
+ Ok(raw) => raw,
76
+ Err(raised) => return raised,
77
+ };
69
78
  // SAFETY: rb_syserr_new returns a live Errno exception instance.
70
- let exc = unsafe { Value::from_raw(rb_sys::rb_syserr_new(errno, cpath.as_ptr())) };
79
+ let exc = unsafe { Value::from_raw(raw) };
71
80
  match magnus::Exception::from_value(exc) {
72
81
  Some(exc) => exc.into(),
73
82
  None => runtime_error(ruby, format!("{e} - {path}")),
@@ -84,23 +93,16 @@ pub fn load_file_native(
84
93
  ) -> Result<Value, Error> {
85
94
  let o = parse_native_opts(ruby, opts)?;
86
95
  let p = path.to_string()?;
87
- FILE_BUF.with(|cell| {
88
- let mut buf = cell
89
- .try_borrow_mut()
90
- .map_or_else(|_| Vec::new(), |mut b| std::mem::take(&mut *b));
96
+ with_taken(&FILE_BUF, |buf| {
91
97
  buf.clear();
92
- let result = read_into(&mut buf, &p)
98
+ read_into(buf, &p)
93
99
  .map_err(|e| io_error(ruby, &p, &e))
94
100
  .and_then(|()| {
95
- if std::str::from_utf8(&buf).is_err() {
101
+ if std::str::from_utf8(buf).is_err() {
96
102
  return Err(err(ruby, NOT_UTF8.into()));
97
103
  }
98
- materialize(ruby, &buf, &o)
99
- });
100
- if let Ok(mut slot) = cell.try_borrow_mut() {
101
- *slot = buf;
102
- }
103
- result
104
+ materialize(ruby, buf, &o)
105
+ })
104
106
  })
105
107
  }
106
108
 
@@ -190,10 +192,9 @@ fn resolve_file_pointer(
190
192
  o: &ParseNativeOpts,
191
193
  ) -> Result<Value, Error> {
192
194
  with_mapped_file(ruby, path, |map| {
193
- let resolved = PULL_STATE.with(|cell| {
194
- let mut state = cell.borrow_mut();
195
+ let resolved = with_pull_state(|state| {
195
196
  // SAFETY: UTF-8 checked by with_mapped_file.
196
- unsafe { nosj::pointer_utf8_unchecked(&map, pointer, &mut state.bufs) }
197
+ unsafe { nosj::pointer_utf8_unchecked_with(&map, pointer, &mut state.bufs, o.popts) }
197
198
  });
198
199
  match resolved {
199
200
  Ok(None) => Ok(ruby.qnil().as_value()),
@@ -7,7 +7,7 @@ use magnus::rb_sys::AsRawValue;
7
7
  use magnus::value::ReprValue;
8
8
  use magnus::{Error, Ruby};
9
9
 
10
- use super::ruby::rstring_bytes;
10
+ use super::ruby::{protected_to_s, rstring_bytes};
11
11
  use crate::errors::nosj_exception;
12
12
 
13
13
  pub(super) enum GenFail {
@@ -24,26 +24,28 @@ pub(super) enum GenFail {
24
24
  }
25
25
 
26
26
  /// The exception's `to_s` (its message), matching what the gem embeds
27
- /// when it wraps a secondary exception.
28
- fn error_message(err: &Error) -> String {
27
+ /// when it wraps a secondary exception. Protected: an exception class
28
+ /// may override `to_s`, and a raise there propagates in place of the
29
+ /// GeneratorError (as it does from the gem).
30
+ fn error_message(err: &Error) -> Result<String, Error> {
29
31
  if let ErrorType::Exception(exc) = err.error_type() {
30
- let s = unsafe { rb_sys::rb_obj_as_string(exc.as_value().as_raw()) };
32
+ let s = protected_to_s(exc.as_value().as_raw())?;
31
33
  // Safety: rb_obj_as_string returns a T_STRING; the bytes are
32
34
  // copied into an owned String before any further Ruby call.
33
35
  let bytes = unsafe { rstring_bytes(s) };
34
- return String::from_utf8_lossy(bytes).into_owned();
36
+ return Ok(String::from_utf8_lossy(bytes).into_owned());
35
37
  }
36
- err.to_string()
38
+ Ok(err.to_string())
37
39
  }
38
40
 
39
41
  pub(super) fn raise_fail(ruby: &Ruby, fail: GenFail) -> Error {
40
42
  match fail {
41
43
  GenFail::Reraise(err) => err,
42
44
  GenFail::Generator(msg) => Error::new(nosj_exception(ruby, "GeneratorError"), msg),
43
- GenFail::GeneratorFrom(err) => {
44
- let msg = error_message(&err);
45
- Error::new(nosj_exception(ruby, "GeneratorError"), msg)
46
- }
45
+ GenFail::GeneratorFrom(err) => match error_message(&err) {
46
+ Ok(msg) => Error::new(nosj_exception(ruby, "GeneratorError"), msg),
47
+ Err(raised) => raised,
48
+ },
47
49
  GenFail::Nesting(limit) => Error::new(
48
50
  nosj_exception(ruby, "NestingError"),
49
51
  format!(
@@ -31,6 +31,7 @@ use magnus::rb_sys::{AsRawValue, FromRawValue};
31
31
  use magnus::{Error, RString, Ruby, Value};
32
32
  use std::cell::Cell;
33
33
 
34
+ use crate::state::with_taken;
34
35
  use errors::raise_fail;
35
36
  use keys::GenKeyCache;
36
37
  pub(crate) use ruby::warm_up;
@@ -57,6 +58,7 @@ struct GenScratch {
57
58
  }
58
59
 
59
60
  impl GenScratch {
61
+ #[cold]
60
62
  fn fresh() -> Box<Self> {
61
63
  Box::new(GenScratch {
62
64
  buf: Vec::new(),
@@ -70,17 +72,13 @@ thread_local! {
70
72
  static GEN_SCRATCH: Cell<Option<Box<GenScratch>>> = const { Cell::new(None) };
71
73
  }
72
74
 
73
- /// Run `f` on this thread's scratch, then store it back, replacing one a
74
- /// recursive generate stored meanwhile (the outermost call's is the warm
75
- /// one; the replaced scratch's key cache keeps its shadow, exactly as
76
- /// the old fallback arm's did).
75
+ /// Run `f` on this thread's scratch (see [`with_taken`]). A recursive
76
+ /// generate stores its own fresh scratch meanwhile; the outermost call's
77
+ /// warm one replaces it (the replaced key cache keeps its shadow).
77
78
  fn with_scratch<R>(f: impl FnOnce(&mut GenScratch) -> R) -> R {
78
- let mut scratch = GEN_SCRATCH
79
- .with(Cell::take)
80
- .unwrap_or_else(GenScratch::fresh);
81
- let result = f(&mut scratch);
82
- GEN_SCRATCH.with(|cell| cell.set(Some(scratch)));
83
- result
79
+ with_taken(&GEN_SCRATCH, |slot| {
80
+ f(slot.get_or_insert_with(GenScratch::fresh))
81
+ })
84
82
  }
85
83
 
86
84
  /// `NOSJ.generate(obj, opts = nil)`, registered as a variadic native
@@ -23,6 +23,21 @@ pub(super) fn protected_to_json(v: VALUE) -> Result<VALUE, Error> {
23
23
  magnus::rb_sys::protect(|| unsafe { rb_sys::rb_funcall(v, to_json_id(), 0) })
24
24
  }
25
25
 
26
+ /// `v.to_json` if `v.respond_to?(:to_json)`, else `None`, under ONE
27
+ /// protect: `rb_respond_to` dispatches to a user-defined `respond_to?` /
28
+ /// `respond_to_missing?`, which may raise just like `to_json` itself.
29
+ pub(super) fn protected_to_json_if_responds(v: VALUE) -> Result<Option<VALUE>, Error> {
30
+ const QUNDEF: VALUE = ruby_special_consts::RUBY_Qundef as VALUE;
31
+ let json = magnus::rb_sys::protect(|| unsafe {
32
+ if rb_sys::rb_respond_to(v, to_json_id()) != 0 {
33
+ rb_sys::rb_funcall(v, to_json_id(), 0)
34
+ } else {
35
+ QUNDEF
36
+ }
37
+ })?;
38
+ Ok((json != QUNDEF).then_some(json))
39
+ }
40
+
26
41
  /// `v.as_json`, protected. Argument-less on purpose: ActiveSupport's
27
42
  /// JSONGemEncoder#jsonify recursion also calls as_json without
28
43
  /// options (only the top-level value receives them).
@@ -53,33 +68,37 @@ pub(crate) fn warm_up() {
53
68
  /// first generate is still found; a fragment instance existing implies
54
69
  /// its class does. The cached VALUE is a constant of the JSON module,
55
70
  /// so it can never be collected.
56
- pub(super) fn is_json_fragment(v: VALUE) -> bool {
71
+ pub(super) fn is_json_fragment(v: VALUE) -> Result<bool, Error> {
57
72
  use std::sync::atomic::{AtomicUsize, Ordering};
58
73
  static FRAGMENT: AtomicUsize = AtomicUsize::new(0);
59
- let mut cls = FRAGMENT.load(Ordering::Relaxed);
74
+ let mut cls = FRAGMENT.load(Ordering::Relaxed) as VALUE;
60
75
  if cls == 0 {
61
- cls = resolve_json_fragment();
76
+ cls = resolve_json_fragment()?;
62
77
  if cls == 0 {
63
- return false;
78
+ return Ok(false);
64
79
  }
65
- FRAGMENT.store(cls, Ordering::Relaxed);
80
+ FRAGMENT.store(cls as usize, Ordering::Relaxed);
66
81
  }
67
- unsafe { rb_sys::rb_obj_is_kind_of(v, cls as VALUE) != QFALSE }
82
+ Ok(unsafe { rb_sys::rb_obj_is_kind_of(v, cls) != QFALSE })
68
83
  }
69
84
 
70
- fn resolve_json_fragment() -> usize {
85
+ /// `JSON::Fragment`, or 0 while undefined. Only the `rb_const_get`s are
86
+ /// protected: fetching a constant can run its pending autoload (user
87
+ /// code, whose raise propagates as any constant reference's would),
88
+ /// while `rb_const_defined` never loads anything.
89
+ fn resolve_json_fragment() -> Result<VALUE, Error> {
71
90
  unsafe {
72
91
  let object = rb_sys::rb_cObject;
73
92
  let json_id = rb_sys::rb_intern(c"JSON".as_ptr());
74
93
  if rb_sys::rb_const_defined(object, json_id) == 0 {
75
- return 0;
94
+ return Ok(0);
76
95
  }
77
- let json = rb_sys::rb_const_get(object, json_id);
96
+ let json = magnus::rb_sys::protect(|| rb_sys::rb_const_get(object, json_id))?;
78
97
  let fragment_id = rb_sys::rb_intern(c"Fragment".as_ptr());
79
98
  if rb_sys::rb_const_defined(json, fragment_id) == 0 {
80
- return 0;
99
+ return Ok(0);
81
100
  }
82
- rb_sys::rb_const_get(json, fragment_id) as usize
101
+ magnus::rb_sys::protect(|| rb_sys::rb_const_get(json, fragment_id))
83
102
  }
84
103
  }
85
104
 
@@ -95,7 +114,7 @@ pub(super) fn protected_encode_utf8(v: VALUE) -> Result<VALUE, Error> {
95
114
  }
96
115
 
97
116
  /// Interned `to_json` method ID, resolved once per process.
98
- pub(super) fn to_json_id() -> rb_sys::ID {
117
+ fn to_json_id() -> rb_sys::ID {
99
118
  static TO_JSON: OnceLock<usize> = OnceLock::new();
100
119
  *TO_JSON.get_or_init(|| unsafe { rb_sys::rb_intern(c"to_json".as_ptr()) } as usize)
101
120
  as rb_sys::ID
@@ -109,12 +128,16 @@ pub(super) fn utf8_encindexes() -> (c_int, c_int) {
109
128
  // Coderange and encoding index live in RBasic flags (public ABI); reading
110
129
  // them inline instead of calling rb_enc_str_coderange / rb_enc_get_index is
111
130
  // how the gem avoids two C calls per string (RB_ENC_CODERANGE,
112
- // RB_ENCODING_GET_INLINED).
113
- const CR_MASK: u64 = 3 << 20;
114
- pub(super) const CR_7BIT: u64 = 1 << 20;
115
- pub(super) const CR_VALID: u64 = 2 << 20;
116
- const ENC_SHIFT: u64 = 22;
117
- const ENC_MASK: u64 = 127 << 22;
131
+ // RB_ENCODING_GET_INLINED). The bit layout comes from rb-sys's bindings,
132
+ // generated from the headers of the Ruby being built against, so it
133
+ // follows any layout change instead of silently misreading flags.
134
+ const CR_MASK: u64 = rb_sys::ruby_coderange_type::RUBY_ENC_CODERANGE_MASK as u64;
135
+ pub(super) const CR_7BIT: u64 = rb_sys::ruby_coderange_type::RUBY_ENC_CODERANGE_7BIT as u64;
136
+ pub(super) const CR_VALID: u64 = rb_sys::ruby_coderange_type::RUBY_ENC_CODERANGE_VALID as u64;
137
+ const ENC_SHIFT: u64 = rb_sys::ruby_encoding_consts::RUBY_ENCODING_SHIFT as u64;
138
+ const ENC_MASK: u64 = rb_sys::ruby_encoding_consts::RUBY_ENCODING_MASK as u64;
139
+ /// Inline encoding-index sentinel: the real index is stored out of line.
140
+ const ENC_INLINE_MAX: c_int = rb_sys::ruby_encoding_consts::RUBY_ENCODING_INLINE_MAX as c_int;
118
141
 
119
142
  #[inline(always)]
120
143
  pub(super) fn str_coderange(s: VALUE) -> u64 {
@@ -131,18 +154,18 @@ pub(super) fn str_coderange(s: VALUE) -> u64 {
131
154
  pub(super) fn str_enc_index(s: VALUE) -> c_int {
132
155
  let flags = unsafe { (*(s as *const rb_sys::RBasic)).flags };
133
156
  let idx = ((flags & ENC_MASK) >> ENC_SHIFT) as c_int;
134
- if idx == 127 {
135
- // RUBY_ENCODING_INLINE_MAX sentinel: index stored out of line.
157
+ if idx == ENC_INLINE_MAX {
136
158
  unsafe { rb_sys::rb_enc_get_index(s) }
137
159
  } else {
138
160
  idx
139
161
  }
140
162
  }
141
163
 
164
+ /// `RB_SPECIAL_CONST_P` (immediates plus Qnil/Qfalse), through rb-sys's
165
+ /// inline versioned stable API rather than a hand-copied bit test.
142
166
  #[inline(always)]
143
167
  pub(super) fn is_special_const(v: VALUE) -> bool {
144
- // RB_SPECIAL_CONST_P: immediates plus Qnil/Qfalse.
145
- (v & (ruby_special_consts::RUBY_IMMEDIATE_MASK as VALUE)) != 0 || v == QNIL || v == QFALSE
168
+ rb_sys::macros::SPECIAL_CONST_P(v)
146
169
  }
147
170
 
148
171
  /// Borrow a Ruby String's bytes.