lz4rip 0.2.0 → 0.2.2

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: 2f66c12c967a06a207c9e8e742fac306280863bf655bd7b4318a2265d08c1cdf
4
- data.tar.gz: be95ea7eb336509e7077737f0d4703dc500931f1608fdc2f52dc3b170904b16d
3
+ metadata.gz: 67a8b9bf2a0abb6a7630773720ae606dc1729be0aa56bdf4b851bf523beb2d4f
4
+ data.tar.gz: 55a3745ca8e940589a6659d68c41f2af81d82b3edf6a6ca22d9f496d4c331fd4
5
5
  SHA512:
6
- metadata.gz: 2fc02b8f797989ca99f23e97658dab9442c4fbb70ab03ff3436a73b5026b78d20c1bbf240e4febba0baed905863b225655f03c627d6db4ddee128224b419c82c
7
- data.tar.gz: 92b2aa66f6282317c5b805f77cf47715288c8debc013520e5dffc78fb7d9c102f62f330906042b062b93aa2104ca21c5b1b0830edd87852b585f6451f4146efd
6
+ metadata.gz: b56524f4b6c057d47a31f5e4e411c7e155a70d4027cb9de42b54e61d2d97c10a6aa94f31473d4ec73afa282eaef786e10497d9d1b73e6db5142a322eec1c4820
7
+ data.tar.gz: 5e5a4186fcfbcfdfc254bc33768f63469868182ed898716ea7e6161f69ec744f9c285306810b982178e52d2d713b674a5fdd9b60f373607c29dceaf100b51961
data/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.2.2] - 2026-11-26
6
+
7
+ - Update the `lz4rip` crate dependency to 0.12.7. Block decompression caps
8
+ its output buffer at what the input can decode to, so a large
9
+ `decompressed_size:` no longer allocates that much up front. Dictionary
10
+ compression output differs from 0.2.1.
11
+ - `DictTrainer#train` no longer raises `RuntimeError` (native Rust panic)
12
+ for a `max_dict_size` of 4 to 31.
13
+ - Let several threads compress or decompress one mutable String at once.
14
+ Calls that release the GVL now borrow a frozen copy of the input instead
15
+ of locking it, so they no longer raise `RuntimeError` when another call
16
+ holds the same String, and the caller may modify it meanwhile.
17
+ - Check the LZ4 frame magic before releasing the GVL.
18
+
19
+ ## [0.2.1] - 2026-10-11
20
+
21
+ - Update the `lz4rip` crate dependency to 0.11.10 and `rb-sys` to 0.9.130.
22
+ - Make `FrameCodec` instances Ractor-shareable as documented, with native
23
+ dictionary copies that leave caller strings mutable.
24
+ - Unlock input strings and free native results when Ruby interrupts a call
25
+ that released the GVL.
26
+ - Protect mutable inputs when mutex contention releases the GVL, including
27
+ calls below the normal size threshold.
28
+ - Catch Rust panics inside native callbacks instead of aborting the process.
29
+ - Preserve Ruby exceptions, `Thread#kill`, and `catch`/`throw` through
30
+ protected native calls.
31
+ - Avoid trainer deadlocks during sample coercion and borrow decompression
32
+ input after size coercion.
33
+ - Update GitHub Actions checkout to v7 and check Rust tests, formatting, and
34
+ Clippy in CI.
35
+
5
36
  ## [0.2.0] - 2026-08-07
6
37
 
7
38
  - Release the Ruby GVL around large frame/block compression and frame
data/Cargo.lock CHANGED
@@ -31,9 +31,9 @@ dependencies = [
31
31
 
32
32
  [[package]]
33
33
  name = "bitflags"
34
- version = "2.13.1"
34
+ version = "2.13.2"
35
35
  source = "registry+https://github.com/rust-lang/crates.io-index"
36
- checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
36
+ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
37
37
 
38
38
  [[package]]
39
39
  name = "cexpr"
@@ -46,9 +46,9 @@ dependencies = [
46
46
 
47
47
  [[package]]
48
48
  name = "cfg-if"
49
- version = "1.0.4"
49
+ version = "1.0.5"
50
50
  source = "registry+https://github.com/rust-lang/crates.io-index"
51
- checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
51
+ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
52
52
 
53
53
  [[package]]
54
54
  name = "clang-sys"
@@ -63,9 +63,9 @@ dependencies = [
63
63
 
64
64
  [[package]]
65
65
  name = "either"
66
- version = "1.17.0"
66
+ version = "1.19.0"
67
67
  source = "registry+https://github.com/rust-lang/crates.io-index"
68
- checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
68
+ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
69
69
 
70
70
  [[package]]
71
71
  name = "glob"
@@ -84,15 +84,15 @@ dependencies = [
84
84
 
85
85
  [[package]]
86
86
  name = "lazy_static"
87
- version = "1.5.0"
87
+ version = "1.5.1"
88
88
  source = "registry+https://github.com/rust-lang/crates.io-index"
89
- checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
89
+ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
90
90
 
91
91
  [[package]]
92
92
  name = "libc"
93
- version = "0.2.189"
93
+ version = "0.2.191"
94
94
  source = "registry+https://github.com/rust-lang/crates.io-index"
95
- checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
95
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
96
96
 
97
97
  [[package]]
98
98
  name = "libloading"
@@ -106,17 +106,17 @@ dependencies = [
106
106
 
107
107
  [[package]]
108
108
  name = "lz4rip"
109
- version = "0.1.2"
109
+ version = "0.2.2"
110
110
  dependencies = [
111
- "lz4rip 0.11.3",
111
+ "lz4rip 0.12.7",
112
112
  "rb-sys",
113
113
  ]
114
114
 
115
115
  [[package]]
116
116
  name = "lz4rip"
117
- version = "0.11.3"
117
+ version = "0.12.7"
118
118
  source = "registry+https://github.com/rust-lang/crates.io-index"
119
- checksum = "55bde261679fd1d14bcae126094d7afb98c63c1a5018d0718741b658b686e950"
119
+ checksum = "ba714cda4452679bec0dd3910f3979a3a803d51dbb490c237aa15dcb95432dd1"
120
120
  dependencies = [
121
121
  "lz4rip-core",
122
122
  "lz4rip-decode",
@@ -126,24 +126,24 @@ dependencies = [
126
126
 
127
127
  [[package]]
128
128
  name = "lz4rip-core"
129
- version = "0.5.5"
129
+ version = "0.6.2"
130
130
  source = "registry+https://github.com/rust-lang/crates.io-index"
131
- checksum = "22fc4edb61fcaf1cdad24ac2982eff7af4417ef463c33bcf5c42ba549abd8b96"
131
+ checksum = "052afa89a977207a207f3e074b1518b0fb5767dab3274464fd1ee5fc7699a30b"
132
132
 
133
133
  [[package]]
134
134
  name = "lz4rip-decode"
135
- version = "0.10.3"
135
+ version = "0.11.2"
136
136
  source = "registry+https://github.com/rust-lang/crates.io-index"
137
- checksum = "60d65bfd4c032fefcf8c18fb5f8d9958f4925146845db16dbc9d416f1566b9bf"
137
+ checksum = "1b0652316d9108ecf75802ddc55f4174a836f2c93c3ab3b06ed009e211d9f9c7"
138
138
  dependencies = [
139
139
  "lz4rip-core",
140
140
  ]
141
141
 
142
142
  [[package]]
143
143
  name = "lz4rip-encode"
144
- version = "0.10.5"
144
+ version = "0.10.17"
145
145
  source = "registry+https://github.com/rust-lang/crates.io-index"
146
- checksum = "09e92b7345788ec0d32b5e31051dc6a86730e17b01267e502e9ec2744b689d34"
146
+ checksum = "ff6d1b221814509df4735ac32847dc169e6a8b0375683e6c5bc8139c4dd620c2"
147
147
  dependencies = [
148
148
  "lz4rip-core",
149
149
  ]
@@ -190,18 +190,18 @@ dependencies = [
190
190
 
191
191
  [[package]]
192
192
  name = "rb-sys"
193
- version = "0.9.128"
193
+ version = "0.9.130"
194
194
  source = "registry+https://github.com/rust-lang/crates.io-index"
195
- checksum = "45ca28513560e56cfb79a62b1fce363c73af170a182024ce880c77ee9429920a"
195
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
196
196
  dependencies = [
197
197
  "rb-sys-build",
198
198
  ]
199
199
 
200
200
  [[package]]
201
201
  name = "rb-sys-build"
202
- version = "0.9.128"
202
+ version = "0.9.130"
203
203
  source = "registry+https://github.com/rust-lang/crates.io-index"
204
- checksum = "ce04b2c55eff3a21aaa623fcc655d94373238e72cac6b3e1a3641ff31649f99a"
204
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
205
205
  dependencies = [
206
206
  "bindgen",
207
207
  "lazy_static",
@@ -214,9 +214,9 @@ dependencies = [
214
214
 
215
215
  [[package]]
216
216
  name = "regex"
217
- version = "1.13.1"
217
+ version = "1.13.2"
218
218
  source = "registry+https://github.com/rust-lang/crates.io-index"
219
- checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
219
+ checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
220
220
  dependencies = [
221
221
  "aho-corasick",
222
222
  "memchr",
@@ -226,9 +226,9 @@ dependencies = [
226
226
 
227
227
  [[package]]
228
228
  name = "regex-automata"
229
- version = "0.4.18"
229
+ version = "0.4.19"
230
230
  source = "registry+https://github.com/rust-lang/crates.io-index"
231
- checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
231
+ checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
232
232
  dependencies = [
233
233
  "aho-corasick",
234
234
  "memchr",
@@ -237,9 +237,9 @@ dependencies = [
237
237
 
238
238
  [[package]]
239
239
  name = "regex-syntax"
240
- version = "0.8.11"
240
+ version = "0.8.12"
241
241
  source = "registry+https://github.com/rust-lang/crates.io-index"
242
- checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
242
+ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
243
243
 
244
244
  [[package]]
245
245
  name = "rustc-hash"
@@ -272,15 +272,15 @@ dependencies = [
272
272
 
273
273
  [[package]]
274
274
  name = "twox-hash"
275
- version = "2.1.3"
275
+ version = "2.1.5"
276
276
  source = "registry+https://github.com/rust-lang/crates.io-index"
277
- checksum = "8464ec13c3691491391d9fce00f6416c9a48e46972f72d7865688be2080192c9"
277
+ checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
278
278
 
279
279
  [[package]]
280
280
  name = "unicode-ident"
281
- version = "1.0.24"
281
+ version = "1.0.27"
282
282
  source = "registry+https://github.com/rust-lang/crates.io-index"
283
- checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
283
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
284
284
 
285
285
  [[package]]
286
286
  name = "windows-link"
data/Cargo.toml CHANGED
@@ -6,4 +6,3 @@ resolver = "2"
6
6
  opt-level = 3
7
7
  lto = true
8
8
  codegen-units = 1
9
- panic = "abort"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "lz4rip"
3
- version = "0.1.2"
3
+ version = "0.2.2"
4
4
  edition = "2021"
5
5
  build = "build.rs"
6
6
 
@@ -9,8 +9,8 @@ name = "lz4rip"
9
9
  crate-type = ["cdylib", "rlib"]
10
10
 
11
11
  [dependencies]
12
- lz4 = { version = "0.11.3", package = "lz4rip" }
13
- rb-sys = "0.9"
12
+ lz4 = { version = "0.12.7", package = "lz4rip" }
13
+ rb-sys = "0.9.130"
14
14
 
15
15
  [build-dependencies]
16
- rb-sys = "0.9"
16
+ rb-sys = "0.9.130"
@@ -40,27 +40,38 @@ fn should_release_frame_decompress_gvl(input_len: usize) -> bool {
40
40
  input_len >= GVL_FRAME_DECOMPRESS_THRESHOLD
41
41
  }
42
42
 
43
- fn with_mutex<T, R, F>(mutex: &Mutex<T>, release_gvl: bool, name: &str, func: F) -> RbResult<R>
43
+ fn with_mutex<T, R, F>(
44
+ mutex: &Mutex<T>,
45
+ release_gvl: bool,
46
+ name: &str,
47
+ input: &mut rb::InputBytes,
48
+ func: F,
49
+ ) -> RbResult<R>
44
50
  where
45
- F: FnOnce(&mut T) -> RbResult<R>,
51
+ F: FnOnce(&mut T, &[u8]) -> RbResult<R>,
46
52
  {
47
53
  if release_gvl {
54
+ input.freeze_for_without_gvl(true)?;
48
55
  return rb::maybe_without_gvl(true, || {
49
56
  let mut guard = mutex
50
57
  .lock()
51
58
  .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
52
- func(&mut guard)
53
- });
59
+ func(&mut guard, input.as_slice())
60
+ })?;
54
61
  }
55
62
 
56
63
  match mutex.try_lock() {
57
- Ok(mut guard) => func(&mut guard),
58
- Err(TryLockError::WouldBlock) => rb::maybe_without_gvl(true, || {
59
- let mut guard = mutex
60
- .lock()
61
- .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
62
- func(&mut guard)
63
- }),
64
+ Ok(mut guard) => func(&mut guard, input.as_slice()),
65
+ Err(TryLockError::WouldBlock) => {
66
+ // Even a small input needs protection when contention releases GVL.
67
+ input.freeze_for_without_gvl(true)?;
68
+ rb::maybe_without_gvl(true, || {
69
+ let mut guard = mutex
70
+ .lock()
71
+ .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
72
+ func(&mut guard, input.as_slice())
73
+ })?
74
+ }
64
75
  Err(TryLockError::Poisoned(_)) => Err(RubyErr::runtime(format!("{name} mutex poisoned"))),
65
76
  }
66
77
  }
@@ -122,7 +133,7 @@ fn make_frame_codec_data_type() -> rb_data_type_t {
122
133
  },
123
134
  parent: std::ptr::null(),
124
135
  data: std::ptr::null_mut(),
125
- flags: 1,
136
+ flags: rb::frozen_shareable_flags(),
126
137
  }
127
138
  }
128
139
 
@@ -257,13 +268,17 @@ fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
257
268
  let rb_self = unsafe { block_codec_ref(rb_self)? };
258
269
  let mut input = rb::input_bytes(rb_input)?;
259
270
  let release_gvl = should_release_compress_gvl(input.len());
260
- input.lock_for_without_gvl(release_gvl)?;
271
+ input.freeze_for_without_gvl(release_gvl)?;
261
272
 
262
273
  let out = match &rb_self.compressor {
263
- None => rb::maybe_without_gvl(release_gvl, || Ok(block::compress(input.as_slice())))?,
264
- Some(comp) => with_mutex(comp, release_gvl, "BlockCodec compressor", |comp| {
265
- Ok(comp.compress(input.as_slice()))
266
- })?,
274
+ None => rb::maybe_without_gvl(release_gvl, || block::compress(input.as_slice()))?,
275
+ Some(comp) => with_mutex(
276
+ comp,
277
+ release_gvl,
278
+ "BlockCodec compressor",
279
+ &mut input,
280
+ |comp, input| Ok(comp.compress(input)),
281
+ )?,
267
282
  };
268
283
 
269
284
  rb::new_binary_string(&out)
@@ -275,14 +290,18 @@ fn block_codec_decompress_impl(
275
290
  decompressed_size: VALUE,
276
291
  ) -> RbResult<VALUE> {
277
292
  let rb_self = unsafe { block_codec_ref(rb_self)? };
278
- let compressed = rb::input_bytes(rb_input)?;
279
293
  let decompressed_size = rb::value_to_usize(decompressed_size)?;
294
+ let mut compressed = rb::input_bytes(rb_input)?;
280
295
 
281
296
  let result = match &rb_self.decompressor {
282
297
  None => block::decompress(compressed.as_slice(), decompressed_size),
283
- Some(decomp) => with_mutex(decomp, false, "BlockCodec decompressor", |decomp| {
284
- Ok(decomp.decompress(compressed.as_slice(), decompressed_size))
285
- })?,
298
+ Some(decomp) => with_mutex(
299
+ decomp,
300
+ false,
301
+ "BlockCodec decompressor",
302
+ &mut compressed,
303
+ |decomp, compressed| Ok(decomp.decompress(compressed, decompressed_size)),
304
+ )?,
286
305
  };
287
306
 
288
307
  match result {
@@ -331,32 +350,25 @@ struct DictBound {
331
350
 
332
351
  fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE) -> RbResult<VALUE> {
333
352
  let id = rb::value_to_u32(id)?;
334
- let dict = if rb_dict == rb::qnil() {
335
- None
336
- } else {
337
- let rb_dict = rb::string_value(rb_dict)?;
338
- rb::freeze_value(rb_dict)?;
339
- Some(DictBound {
340
- bytes: rb::value_to_bytes(rb_dict)?,
341
- id,
342
- })
343
- };
344
- unsafe {
353
+ let dict = rb::value_to_option_bytes(rb_dict)?.map(|bytes| DictBound { bytes, id });
354
+ let codec = unsafe {
345
355
  rb::wrap_typed_data(
346
356
  class,
347
357
  Box::new(FrameCodec { dict }),
348
358
  frame_codec_data_type(),
349
- )
350
- }
359
+ )?
360
+ };
361
+ rb::make_shareable(codec)?;
362
+ Ok(codec)
351
363
  }
352
364
 
353
365
  fn frame_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE> {
354
366
  let rb_self = unsafe { frame_codec_ref(rb_self)? };
355
367
  let mut input = rb::input_bytes(rb_input)?;
356
368
  let release_gvl = should_release_compress_gvl(input.len());
357
- input.lock_for_without_gvl(release_gvl)?;
369
+ input.freeze_for_without_gvl(release_gvl)?;
358
370
 
359
- let out = rb::maybe_without_gvl(release_gvl, || compress_frame(rb_self, input.as_slice()))
371
+ let out = rb::maybe_without_gvl(release_gvl, || compress_frame(rb_self, input.as_slice()))?
360
372
  .map_err(RubyErr::runtime)?;
361
373
 
362
374
  rb::new_binary_string(&out)
@@ -389,10 +401,8 @@ fn frame_codec_decompress_impl(
389
401
  max_decompressed_size: VALUE,
390
402
  ) -> RbResult<VALUE> {
391
403
  let rb_self = unsafe { frame_codec_ref(rb_self)? };
392
- let mut input = rb::input_bytes(rb_input)?;
393
404
  let max_decompressed_size = rb::value_to_option_usize(max_decompressed_size)?;
394
- let release_gvl = should_release_frame_decompress_gvl(input.len());
395
- input.lock_for_without_gvl(release_gvl)?;
405
+ let mut input = rb::input_bytes(rb_input)?;
396
406
 
397
407
  if input.len() < 4 || input.as_slice()[..4] != LZ4_FRAME_MAGIC {
398
408
  return Err(RubyErr::new(
@@ -401,9 +411,12 @@ fn frame_codec_decompress_impl(
401
411
  ));
402
412
  }
403
413
 
414
+ let release_gvl = should_release_frame_decompress_gvl(input.len());
415
+ input.freeze_for_without_gvl(release_gvl)?;
416
+
404
417
  let out = rb::maybe_without_gvl(release_gvl, || {
405
418
  decompress_frame(rb_self, input.as_slice(), max_decompressed_size)
406
- })
419
+ })?
407
420
  .map_err(|e| RubyErr::new(decompress_error(), e))?;
408
421
 
409
422
  rb::new_binary_string(&out)
@@ -496,6 +509,7 @@ fn dict_trainer_new_impl(class: VALUE, max_dict_size: VALUE) -> RbResult<VALUE>
496
509
  }
497
510
 
498
511
  fn dict_trainer_add_sample_impl(rb_self: VALUE, rb_data: VALUE) -> RbResult<VALUE> {
512
+ let data = rb::input_bytes(rb_data)?;
499
513
  let rb_self = unsafe { dict_trainer_ref(rb_self)? };
500
514
  let mut borrow = rb_self
501
515
  .inner
@@ -504,7 +518,6 @@ fn dict_trainer_add_sample_impl(rb_self: VALUE, rb_data: VALUE) -> RbResult<VALU
504
518
  let trainer = borrow
505
519
  .as_mut()
506
520
  .ok_or_else(|| RubyErr::runtime("DictTrainer already consumed by #train"))?;
507
- let data = rb::input_bytes(rb_data)?;
508
521
  let sample = if data.len() > rb_self.max_dict_size {
509
522
  &data.as_slice()[..rb_self.max_dict_size]
510
523
  } else {
data/ext/lz4rip/src/rb.rs CHANGED
@@ -1,6 +1,4 @@
1
1
  use std::ffi::{c_char, c_long, c_void, CStr, CString};
2
- #[cfg(ruby_engine = "mri")]
3
- use std::mem::MaybeUninit;
4
2
  use std::panic::{catch_unwind, AssertUnwindSafe};
5
3
  use std::ptr;
6
4
 
@@ -8,13 +6,6 @@ use rb_sys::{rb_data_type_t, VALUE};
8
6
 
9
7
  pub type RbResult<T = VALUE> = Result<T, RubyErr>;
10
8
 
11
- #[cfg(ruby_engine = "mri")]
12
- unsafe extern "C" {
13
- fn rb_obj_frozen_p(obj: VALUE) -> VALUE;
14
- fn rb_str_locktmp(str: VALUE) -> VALUE;
15
- fn rb_str_unlocktmp(str: VALUE) -> VALUE;
16
- }
17
-
18
9
  #[cfg(ruby_engine = "mri")]
19
10
  type RbWithoutGvlFunc = unsafe extern "C" fn(*mut c_void) -> *mut c_void;
20
11
  #[cfg(ruby_engine = "mri")]
@@ -32,7 +23,7 @@ unsafe extern "C" {
32
23
 
33
24
  #[derive(Debug)]
34
25
  pub enum RubyErr {
35
- Exception(VALUE),
26
+ Jump(i32),
36
27
  Error { class: VALUE, message: String },
37
28
  }
38
29
 
@@ -55,15 +46,6 @@ impl RubyErr {
55
46
  pub fn type_error(message: impl Into<String>) -> Self {
56
47
  Self::new(unsafe { rb_sys::rb_eTypeError }, message)
57
48
  }
58
-
59
- fn current_exception() -> Self {
60
- let err = unsafe { rb_sys::rb_errinfo() };
61
- if err == qnil() {
62
- Self::runtime("Ruby exception")
63
- } else {
64
- Self::Exception(err)
65
- }
66
- }
67
49
  }
68
50
 
69
51
  pub fn wrap<F>(f: F) -> VALUE
@@ -89,12 +71,15 @@ where
89
71
  }
90
72
 
91
73
  pub fn raise(err: RubyErr) -> ! {
92
- let exc = match err {
93
- RubyErr::Exception(exc) => exc,
94
- RubyErr::Error { class, message } => error_exception(class, message),
95
- };
96
-
97
- unsafe { rb_sys::rb_exc_raise(exc) }
74
+ match err {
75
+ // Preserve Ruby's tag and pending error info for Thread#kill and
76
+ // catch/throw, as well as ordinary exceptions.
77
+ RubyErr::Jump(state) => unsafe { rb_sys::rb_jump_tag(state) },
78
+ RubyErr::Error { class, message } => {
79
+ let exc = error_exception(class, message);
80
+ unsafe { rb_sys::rb_exc_raise(exc) }
81
+ }
82
+ }
98
83
  }
99
84
 
100
85
  fn error_exception(class: VALUE, message: String) -> VALUE {
@@ -145,7 +130,7 @@ where
145
130
  };
146
131
 
147
132
  if state != 0 {
148
- Err(RubyErr::current_exception())
133
+ Err(RubyErr::Jump(state))
149
134
  } else if data.panicked {
150
135
  Err(RubyErr::runtime("native Rust panic"))
151
136
  } else {
@@ -167,7 +152,7 @@ where
167
152
  #[cfg(ruby_engine = "mri")]
168
153
  struct WithoutGvlData<F, R> {
169
154
  func: Option<F>,
170
- output: MaybeUninit<R>,
155
+ output: Option<std::thread::Result<R>>,
171
156
  }
172
157
 
173
158
  #[cfg(ruby_engine = "mri")]
@@ -176,49 +161,55 @@ where
176
161
  F: FnOnce() -> R,
177
162
  {
178
163
  let data = unsafe { &mut *(data.cast::<WithoutGvlData<F, R>>()) };
179
- let func = data.func.take().expect("missing without-GVL function");
180
- data.output.write(func());
164
+ // Rust panics must be caught before returning through the C callback.
165
+ data.output = Some(catch_unwind(AssertUnwindSafe(|| {
166
+ data.func.take().expect("missing without-GVL function")()
167
+ })));
181
168
  ptr::null_mut()
182
169
  }
183
170
 
184
171
  #[cfg(ruby_engine = "mri")]
185
- fn without_gvl<F, R>(func: F) -> R
172
+ fn without_gvl<F, R>(func: F) -> RbResult<R>
186
173
  where
187
174
  F: FnOnce() -> R,
188
175
  {
189
176
  let mut data = WithoutGvlData {
190
177
  func: Some(func),
191
- output: MaybeUninit::uninit(),
178
+ output: None,
192
179
  };
193
- unsafe {
180
+ // Ruby checks interrupts before and after the callback. Protect the call
181
+ // so an exception still drops native output and borrowed strings.
182
+ protect_unit(|| unsafe {
194
183
  rb_thread_call_without_gvl(
195
184
  Some(without_gvl_trampoline::<F, R>),
196
185
  (&mut data as *mut WithoutGvlData<F, R>).cast::<c_void>(),
197
186
  None,
198
187
  ptr::null_mut(),
199
188
  );
200
- data.output.assume_init()
201
- }
189
+ })?;
190
+ data.output
191
+ .ok_or_else(|| RubyErr::runtime("without-GVL callback did not run"))?
192
+ .map_err(|_| RubyErr::runtime("native Rust panic"))
202
193
  }
203
194
 
204
195
  #[cfg(ruby_engine = "mri")]
205
- pub fn maybe_without_gvl<F, R>(release_gvl: bool, func: F) -> R
196
+ pub fn maybe_without_gvl<F, R>(release_gvl: bool, func: F) -> RbResult<R>
206
197
  where
207
198
  F: FnOnce() -> R,
208
199
  {
209
200
  if release_gvl {
210
201
  without_gvl(func)
211
202
  } else {
212
- func()
203
+ Ok(func())
213
204
  }
214
205
  }
215
206
 
216
207
  #[cfg(not(ruby_engine = "mri"))]
217
- pub fn maybe_without_gvl<F, R>(_release_gvl: bool, func: F) -> R
208
+ pub fn maybe_without_gvl<F, R>(_release_gvl: bool, func: F) -> RbResult<R>
218
209
  where
219
210
  F: FnOnce() -> R,
220
211
  {
221
- func()
212
+ Ok(func())
222
213
  }
223
214
 
224
215
  pub const fn qnil() -> VALUE {
@@ -255,8 +246,23 @@ pub fn string_value(value: VALUE) -> RbResult<VALUE> {
255
246
  protect_value(|| unsafe { rb_sys::rb_str_to_str(value) })
256
247
  }
257
248
 
258
- pub fn freeze_value(value: VALUE) -> RbResult<()> {
259
- protect_unit(|| unsafe { rb_sys::RB_OBJ_FREEZE(value) })
249
+ pub fn frozen_shareable_flags() -> VALUE {
250
+ #[cfg(ruby_engine = "mri")]
251
+ {
252
+ // RUBY_TYPED_FROZEN_SHAREABLE equals RUBY_FL_SHAREABLE in Ruby headers.
253
+ 1 | rb_sys::ruby_fl_type::RUBY_FL_SHAREABLE as VALUE
254
+ }
255
+ #[cfg(not(ruby_engine = "mri"))]
256
+ {
257
+ 1
258
+ }
259
+ }
260
+
261
+ pub fn make_shareable(value: VALUE) -> RbResult<()> {
262
+ protect_unit(|| unsafe { rb_sys::RB_OBJ_FREEZE(value) })?;
263
+ #[cfg(ruby_engine = "mri")]
264
+ protect_value(|| unsafe { rb_sys::rb_ractor_make_shareable(value) })?;
265
+ Ok(())
260
266
  }
261
267
 
262
268
  pub fn value_to_bytes(value: VALUE) -> RbResult<Vec<u8>> {
@@ -264,19 +270,19 @@ pub fn value_to_bytes(value: VALUE) -> RbResult<Vec<u8>> {
264
270
  bytes_from_string_value(string).map(|bytes| bytes.to_vec())
265
271
  }
266
272
 
267
- pub fn value_to_option_bytes(value: VALUE) -> RbResult<Option<Vec<u8>>> {
273
+ pub fn value_to_option_usize(value: VALUE) -> RbResult<Option<usize>> {
268
274
  if value == qnil() {
269
275
  Ok(None)
270
276
  } else {
271
- value_to_bytes(value).map(Some)
277
+ value_to_usize(value).map(Some)
272
278
  }
273
279
  }
274
280
 
275
- pub fn value_to_option_usize(value: VALUE) -> RbResult<Option<usize>> {
281
+ pub fn value_to_option_bytes(value: VALUE) -> RbResult<Option<Vec<u8>>> {
276
282
  if value == qnil() {
277
283
  Ok(None)
278
284
  } else {
279
- value_to_usize(value).map(Some)
285
+ value_to_bytes(value).map(Some)
280
286
  }
281
287
  }
282
288
 
@@ -301,14 +307,14 @@ impl InputBytes {
301
307
  self.as_slice().len()
302
308
  }
303
309
 
304
- pub fn lock_for_without_gvl(&mut self, release_gvl: bool) -> RbResult<()> {
310
+ pub fn freeze_for_without_gvl(&mut self, release_gvl: bool) -> RbResult<()> {
305
311
  if !release_gvl {
306
312
  return Ok(());
307
313
  }
308
314
 
309
315
  match self {
310
316
  #[cfg(ruby_engine = "mri")]
311
- Self::Borrowed(bytes) => bytes.lock_tmp(),
317
+ Self::Borrowed(bytes) => bytes.freeze(),
312
318
  #[cfg(not(ruby_engine = "mri"))]
313
319
  Self::Owned(_) => Ok(()),
314
320
  }
@@ -320,7 +326,7 @@ pub struct BorrowedStringBytes {
320
326
  value: VALUE,
321
327
  ptr: *const u8,
322
328
  len: usize,
323
- locked: bool,
329
+ frozen: bool,
324
330
  }
325
331
 
326
332
  #[cfg(ruby_engine = "mri")]
@@ -332,7 +338,7 @@ impl BorrowedStringBytes {
332
338
  value: string,
333
339
  ptr: bytes.as_ptr(),
334
340
  len: bytes.len(),
335
- locked: false,
341
+ frozen: false,
336
342
  })
337
343
  }
338
344
 
@@ -344,13 +350,20 @@ impl BorrowedStringBytes {
344
350
  }
345
351
  }
346
352
 
347
- fn lock_tmp(&mut self) -> RbResult<()> {
348
- if self.locked || unsafe { rb_obj_frozen_p(self.value) } == qtrue() {
353
+ // Borrow from a frozen copy before releasing the GVL. The copy shares the
354
+ // heap buffer, and a write to the caller's String copies that buffer first,
355
+ // so other threads may mutate or borrow the caller's String meanwhile.
356
+ fn freeze(&mut self) -> RbResult<()> {
357
+ if self.frozen {
349
358
  return Ok(());
350
359
  }
351
360
 
352
- protect_value(|| unsafe { rb_str_locktmp(self.value) })?;
353
- self.locked = true;
361
+ let frozen = protect_value(|| unsafe { rb_sys::rb_str_new_frozen(self.value) })?;
362
+ let bytes = bytes_from_string_value(frozen)?;
363
+ self.value = frozen;
364
+ self.ptr = bytes.as_ptr();
365
+ self.len = bytes.len();
366
+ self.frozen = true;
354
367
  Ok(())
355
368
  }
356
369
  }
@@ -358,11 +371,6 @@ impl BorrowedStringBytes {
358
371
  #[cfg(ruby_engine = "mri")]
359
372
  impl Drop for BorrowedStringBytes {
360
373
  fn drop(&mut self) {
361
- if self.locked {
362
- unsafe {
363
- rb_str_unlocktmp(self.value);
364
- }
365
- }
366
374
  let _ = rb_sys::rb_gc_guard!(self.value);
367
375
  }
368
376
  }
@@ -626,3 +634,42 @@ unsafe fn transmute_3(
626
634
  fn c_long_len(len: usize) -> RbResult<c_long> {
627
635
  c_long::try_from(len).map_err(|_| RubyErr::arg("length too large"))
628
636
  }
637
+
638
+ #[cfg(all(test, ruby_engine = "mri"))]
639
+ mod tests {
640
+ use super::*;
641
+
642
+ fn run_callback<F, R>(func: F) -> std::thread::Result<R>
643
+ where
644
+ F: FnOnce() -> R,
645
+ {
646
+ let mut data = WithoutGvlData {
647
+ func: Some(func),
648
+ output: None,
649
+ };
650
+ unsafe {
651
+ without_gvl_trampoline::<F, R>(
652
+ (&mut data as *mut WithoutGvlData<F, R>).cast::<c_void>(),
653
+ );
654
+ }
655
+ data.output.unwrap()
656
+ }
657
+
658
+ #[test]
659
+ fn callback_catches_panics_before_returning_to_c() {
660
+ let dropped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
661
+ struct OnDrop(std::sync::Arc<std::sync::atomic::AtomicBool>);
662
+ impl Drop for OnDrop {
663
+ fn drop(&mut self) {
664
+ self.0.store(true, std::sync::atomic::Ordering::SeqCst);
665
+ }
666
+ }
667
+ let captured = OnDrop(dropped.clone());
668
+ let result = run_callback(move || {
669
+ let _captured = captured;
670
+ panic!("callback panic");
671
+ });
672
+ assert!(result.is_err());
673
+ assert!(dropped.load(std::sync::atomic::Ordering::SeqCst));
674
+ }
675
+ }
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Lz4rip
4
- VERSION = "0.2.0"
4
+ VERSION = "0.2.2"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lz4rip
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.2.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger
@@ -16,6 +16,9 @@ dependencies:
16
16
  - - "~>"
17
17
  - !ruby/object:Gem::Version
18
18
  version: '0.9'
19
+ - - ">="
20
+ - !ruby/object:Gem::Version
21
+ version: 0.9.130
19
22
  type: :runtime
20
23
  prerelease: false
21
24
  version_requirements: !ruby/object:Gem::Requirement
@@ -23,6 +26,9 @@ dependencies:
23
26
  - - "~>"
24
27
  - !ruby/object:Gem::Version
25
28
  version: '0.9'
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 0.9.130
26
32
  description: Ruby bindings (via Rust/rb-sys) for lz4rip, a pure-Rust LZ4 implementation.
27
33
  Block-format and frame-format compress/decompress with optional dictionary support
28
34
  and COVER-based dictionary training. Ractor-safe.
@@ -54,7 +60,7 @@ licenses:
54
60
  - MIT
55
61
  metadata:
56
62
  homepage_uri: https://github.com/paddor/lz4rip-rb
57
- source_code_uri: https://github.com/paddor/lz4rip-rb
63
+ source_code_uri: https://github.com/paddor/lz4rip-rb/tree/main
58
64
  documentation_uri: https://rubydoc.info/gems/lz4rip
59
65
  changelog_uri: https://github.com/paddor/lz4rip-rb/blob/main/CHANGELOG.md
60
66
  rubygems_mfa_required: 'true'
@@ -72,7 +78,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
72
78
  - !ruby/object:Gem::Version
73
79
  version: '0'
74
80
  requirements: []
75
- rubygems_version: 4.0.16
81
+ rubygems_version: 4.0.20
76
82
  specification_version: 4
77
83
  summary: Ractor-safe LZ4 compression for Ruby
78
84
  test_files: []