zrip 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: 50caa1679bd74290e01032b2564ab2ac083633f00ad7070f2e3e597572ffe22b
4
- data.tar.gz: d89a94b7221aba11a0084f8ffeab771428f682ddf19908a647c2bce862b43ffe
3
+ metadata.gz: 76111539af262f323eed635879fede0335f1ee43d0dad1fd1e133545c1196a37
4
+ data.tar.gz: '0650794dae17a3623f7be98c836439c946d0cafc69f5574f957f98405c4a5a8b'
5
5
  SHA512:
6
- metadata.gz: 74bc8d13edae353144da41a66e80d41440157dc11c9555726c2c01659d88a02c8ffd0a7410b0157fb011a45677c54448a808ed463a1f9b1d99bd9a2769e42926
7
- data.tar.gz: 91c282a2f5275e2e0cd72a9a2cf089a0582e47d256acce3c9bf67be6f494ab89a046bfece175d23f9543e7162b90b8bf66cc0dd97e5ebd5c9a695c3462e23d01
6
+ metadata.gz: 2f8e3cd002522f48aaf0644892fb7ced4fc595655d063d5766fa29909224249d53cc41bd7c66ff7ba3218a99d1b898ba9ede80bedf1a0873d7fb82fa8f333644
7
+ data.tar.gz: 7efb3e5cd0eb47480597c456d7da7e12803d6eed17e5135956434fbbf5223d154742c7133326ba39bef27c5ee36110807d400a889ae98d8326a6af22996ec81f
data/CHANGELOG.md CHANGED
@@ -2,6 +2,44 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.2.2] - 2026-11-26
6
+
7
+ - Update the `zrip` crate dependency to 0.8.29. Levels are retuned, so
8
+ compressed output differs from 0.2.1, and decoding rejects the frames C
9
+ zstd 1.6.0 rejects.
10
+ - `DictTrainer#train` fills `max_dict_size`. Dictionaries came out 110-150
11
+ bytes short. Sizes under 256 now count as 256, and `max_dict_size`
12
+ returns the size used. They gave a dictionary of padding only.
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
+ - `max_output_size: 0` now limits output to 0 bytes. It used to disable the
18
+ limit. Omit it or pass `nil` for no limit.
19
+ - Fail on a bad first frame header without releasing the GVL.
20
+ - Document that `BlockCodec` writes and reads Zstandard frames.
21
+
22
+ ## [0.2.1] - 2026-10-11
23
+
24
+ - Update the `zrip` crate dependency to 0.8.11 and `rb-sys` to 0.9.130.
25
+ - Make `FrameCodec` instances Ractor-shareable as documented, with native
26
+ dictionary copies that leave caller strings mutable.
27
+ - Unlock input strings and free native results when Ruby interrupts a call
28
+ that released the GVL.
29
+ - Protect mutable inputs when mutex contention releases the GVL, including
30
+ calls below the normal size threshold.
31
+ - Catch Rust panics inside native callbacks instead of aborting the process.
32
+ - Preserve Ruby exceptions, `Thread#kill`, and `catch`/`throw` through
33
+ protected native calls.
34
+ - Avoid trainer deadlocks during sample coercion and borrow decompression
35
+ input after size coercion.
36
+ - Enforce `max_output_size:` inside the native decoder across concatenated
37
+ frames, before allocating or decoding past the limit.
38
+ - Validate complete frame headers when reading frame content sizes.
39
+ - Correct the README compression level example to the supported maximum.
40
+ - Update GitHub Actions checkout to v7 and check Rust tests, formatting, and
41
+ Clippy in CI.
42
+
5
43
  ## [0.2.0] - 2026-08-07
6
44
 
7
45
  - 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,15 +63,15 @@ 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 = "fearless_simd"
72
- version = "0.6.0"
72
+ version = "1.3.0"
73
73
  source = "registry+https://github.com/rust-lang/crates.io-index"
74
- checksum = "e0f5f895dac0865bc235f1364793899569a7db538137f1024dccea56bf41c78d"
74
+ checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599"
75
75
 
76
76
  [[package]]
77
77
  name = "glob"
@@ -90,15 +90,15 @@ dependencies = [
90
90
 
91
91
  [[package]]
92
92
  name = "lazy_static"
93
- version = "1.5.0"
93
+ version = "1.5.1"
94
94
  source = "registry+https://github.com/rust-lang/crates.io-index"
95
- checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
95
+ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
96
96
 
97
97
  [[package]]
98
98
  name = "libc"
99
- version = "0.2.189"
99
+ version = "0.2.191"
100
100
  source = "registry+https://github.com/rust-lang/crates.io-index"
101
- checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
101
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
102
102
 
103
103
  [[package]]
104
104
  name = "libloading"
@@ -152,18 +152,18 @@ dependencies = [
152
152
 
153
153
  [[package]]
154
154
  name = "rb-sys"
155
- version = "0.9.128"
155
+ version = "0.9.130"
156
156
  source = "registry+https://github.com/rust-lang/crates.io-index"
157
- checksum = "45ca28513560e56cfb79a62b1fce363c73af170a182024ce880c77ee9429920a"
157
+ checksum = "02faf625bb10ba893e3ae620f19c9fb1b5f8fcae0fe4eb86bb3f2230fad75edb"
158
158
  dependencies = [
159
159
  "rb-sys-build",
160
160
  ]
161
161
 
162
162
  [[package]]
163
163
  name = "rb-sys-build"
164
- version = "0.9.128"
164
+ version = "0.9.130"
165
165
  source = "registry+https://github.com/rust-lang/crates.io-index"
166
- checksum = "ce04b2c55eff3a21aaa623fcc655d94373238e72cac6b3e1a3641ff31649f99a"
166
+ checksum = "05be6f9c86fe5482808162826f6c047d093b3670582296c770de1d94f8066694"
167
167
  dependencies = [
168
168
  "bindgen",
169
169
  "lazy_static",
@@ -176,9 +176,9 @@ dependencies = [
176
176
 
177
177
  [[package]]
178
178
  name = "regex"
179
- version = "1.13.1"
179
+ version = "1.13.2"
180
180
  source = "registry+https://github.com/rust-lang/crates.io-index"
181
- checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
181
+ checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
182
182
  dependencies = [
183
183
  "aho-corasick",
184
184
  "memchr",
@@ -188,9 +188,9 @@ dependencies = [
188
188
 
189
189
  [[package]]
190
190
  name = "regex-automata"
191
- version = "0.4.18"
191
+ version = "0.4.19"
192
192
  source = "registry+https://github.com/rust-lang/crates.io-index"
193
- checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
193
+ checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
194
194
  dependencies = [
195
195
  "aho-corasick",
196
196
  "memchr",
@@ -199,9 +199,9 @@ dependencies = [
199
199
 
200
200
  [[package]]
201
201
  name = "regex-syntax"
202
- version = "0.8.11"
202
+ version = "0.8.12"
203
203
  source = "registry+https://github.com/rust-lang/crates.io-index"
204
- checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
204
+ checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
205
205
 
206
206
  [[package]]
207
207
  name = "rustc-hash"
@@ -234,9 +234,9 @@ dependencies = [
234
234
 
235
235
  [[package]]
236
236
  name = "unicode-ident"
237
- version = "1.0.24"
237
+ version = "1.0.27"
238
238
  source = "registry+https://github.com/rust-lang/crates.io-index"
239
- checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
239
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
240
240
 
241
241
  [[package]]
242
242
  name = "windows-link"
@@ -246,17 +246,17 @@ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
246
246
 
247
247
  [[package]]
248
248
  name = "zrip"
249
- version = "0.1.2"
249
+ version = "0.2.2"
250
250
  dependencies = [
251
251
  "rb-sys",
252
- "zrip 0.8.5",
252
+ "zrip 0.8.29",
253
253
  ]
254
254
 
255
255
  [[package]]
256
256
  name = "zrip"
257
- version = "0.8.5"
257
+ version = "0.8.29"
258
258
  source = "registry+https://github.com/rust-lang/crates.io-index"
259
- checksum = "fa05c09787b3aaaaa57870dca9fd9f3b4934018cbb5dde1b112017e2e70ec491"
259
+ checksum = "d886ee8c071aed87a037634815bf1b77d66ec90e02122bc031166f4b218bb291"
260
260
  dependencies = [
261
261
  "zrip-core",
262
262
  "zrip-decode",
@@ -265,15 +265,15 @@ dependencies = [
265
265
 
266
266
  [[package]]
267
267
  name = "zrip-core"
268
- version = "0.9.1"
268
+ version = "0.14.4"
269
269
  source = "registry+https://github.com/rust-lang/crates.io-index"
270
- checksum = "9335acd94c1f09f729178fc339f9d49790254c1e98ba076f88df3a3f534c4e7d"
270
+ checksum = "5f6ea7ccd7799d815353fb360e6d2d21207001d58f0a7c02ec9e45d95fe60ae4"
271
271
 
272
272
  [[package]]
273
273
  name = "zrip-decode"
274
- version = "0.8.5"
274
+ version = "0.8.22"
275
275
  source = "registry+https://github.com/rust-lang/crates.io-index"
276
- checksum = "1801cd8b5d374e2bc31cd8a231182dd47e621492fa0bf68ca7d3033e001cd06b"
276
+ checksum = "89ced3ea49c7e49b32b675294304987c3481f2f7b19f3c60ff6b1e4b73eb2ffd"
277
277
  dependencies = [
278
278
  "fearless_simd",
279
279
  "zrip-core",
@@ -281,9 +281,10 @@ dependencies = [
281
281
 
282
282
  [[package]]
283
283
  name = "zrip-encode"
284
- version = "0.8.4"
284
+ version = "0.10.6"
285
285
  source = "registry+https://github.com/rust-lang/crates.io-index"
286
- checksum = "38e7e22b665b947f0240b44805713e87a15c34e86d0891cbe2856c575c5cda1d"
286
+ checksum = "26cf89a0e00fb1e421a0e1b911cdf593178affc2cbcffae62b6dea25089e6fca"
287
287
  dependencies = [
288
+ "fearless_simd",
288
289
  "zrip-core",
289
290
  ]
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"
data/README.md CHANGED
@@ -58,7 +58,7 @@ original = codec.decompress(compressed)
58
58
 
59
59
  ```ruby
60
60
  fast = Zrip::FrameCodec.new(level: -3) # negative = faster
61
- strong = Zrip::FrameCodec.new(level: 19) # higher = smaller output
61
+ strong = Zrip::FrameCodec.new(level: 4) # highest supported level
62
62
  ```
63
63
 
64
64
  ### Bounded decompression
data/ext/zrip/Cargo.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "zrip"
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 = "zrip"
9
9
  crate-type = ["cdylib", "rlib"]
10
10
 
11
11
  [dependencies]
12
- zstd = { version = "0.8.5", package = "zrip", features = ["frame", "dict_builder"] }
13
- rb-sys = "0.9"
12
+ zstd = { version = "0.8.29", package = "zrip", features = ["frame", "dict_builder"] }
13
+ rb-sys = "0.9.130"
14
14
 
15
15
  [build-dependencies]
16
- rb-sys = "0.9"
16
+ rb-sys = "0.9.130"
data/ext/zrip/src/lib.rs CHANGED
@@ -1,7 +1,6 @@
1
1
  mod rb;
2
2
 
3
3
  use std::ffi::c_void;
4
- use std::io::Read;
5
4
  use std::panic::{catch_unwind, AssertUnwindSafe};
6
5
  use std::sync::{Mutex, OnceLock, TryLockError};
7
6
 
@@ -18,7 +17,6 @@ static OUTPUT_SIZE_LIMIT_ERROR: OnceLock<GlobalValue> = OnceLock::new();
18
17
 
19
18
  const GVL_COMPRESS_THRESHOLD: usize = 64 * 1024;
20
19
  const GVL_FRAME_DECOMPRESS_THRESHOLD: usize = 64 * 1024;
21
- const DECOMPRESS_READ_CHUNK: usize = 16 * 1024;
22
20
 
23
21
  #[derive(Copy, Clone)]
24
22
  struct GlobalValue(VALUE);
@@ -52,27 +50,38 @@ fn should_release_frame_decompress_gvl(output_len: usize) -> bool {
52
50
  output_len >= GVL_FRAME_DECOMPRESS_THRESHOLD
53
51
  }
54
52
 
55
- fn with_mutex<T, R, F>(mutex: &Mutex<T>, release_gvl: bool, name: &str, func: F) -> RbResult<R>
53
+ fn with_mutex<T, R, F>(
54
+ mutex: &Mutex<T>,
55
+ release_gvl: bool,
56
+ name: &str,
57
+ input: &mut rb::InputBytes,
58
+ func: F,
59
+ ) -> RbResult<R>
56
60
  where
57
- F: FnOnce(&mut T) -> RbResult<R>,
61
+ F: FnOnce(&mut T, &[u8]) -> RbResult<R>,
58
62
  {
59
63
  if release_gvl {
64
+ input.freeze_for_without_gvl(true)?;
60
65
  return rb::maybe_without_gvl(true, || {
61
66
  let mut guard = mutex
62
67
  .lock()
63
68
  .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
64
- func(&mut guard)
65
- });
69
+ func(&mut guard, input.as_slice())
70
+ })?;
66
71
  }
67
72
 
68
73
  match mutex.try_lock() {
69
- Ok(mut guard) => func(&mut guard),
70
- Err(TryLockError::WouldBlock) => rb::maybe_without_gvl(true, || {
71
- let mut guard = mutex
72
- .lock()
73
- .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
74
- func(&mut guard)
75
- }),
74
+ Ok(mut guard) => func(&mut guard, input.as_slice()),
75
+ Err(TryLockError::WouldBlock) => {
76
+ // Even a small input needs protection when contention releases GVL.
77
+ input.freeze_for_without_gvl(true)?;
78
+ rb::maybe_without_gvl(true, || {
79
+ let mut guard = mutex
80
+ .lock()
81
+ .map_err(|_| RubyErr::runtime(format!("{name} mutex poisoned")))?;
82
+ func(&mut guard, input.as_slice())
83
+ })?
84
+ }
76
85
  Err(TryLockError::Poisoned(_)) => Err(RubyErr::runtime(format!("{name} mutex poisoned"))),
77
86
  }
78
87
  }
@@ -89,126 +98,41 @@ enum BoundedError {
89
98
  }
90
99
 
91
100
  fn parse_frame_content_size(input: &[u8]) -> Result<Option<u64>, BoundedError> {
92
- if input.len() < 5 {
93
- return Err(BoundedError::BadMagic);
94
- }
95
- if input[..4] != ZSTD_FRAME_MAGIC {
96
- return Err(BoundedError::BadMagic);
97
- }
98
- let fhd = input[4];
99
- let fcs_flag = (fhd >> 6) & 3;
100
- let single_segment = (fhd >> 5) & 1;
101
- let dict_id_flag = fhd & 3;
102
-
103
- let window_desc_size = if single_segment == 0 { 1usize } else { 0 };
104
- let dict_id_size = [0usize, 1, 2, 4][dict_id_flag as usize];
105
- let fcs_field_size = match fcs_flag {
106
- 0 => {
107
- if single_segment == 1 {
108
- 1usize
109
- } else {
110
- return Ok(None);
111
- }
112
- }
113
- 1 => 2,
114
- 2 => 4,
115
- 3 => 8,
116
- _ => unreachable!(),
117
- };
118
-
119
- let fcs_offset = 5 + window_desc_size + dict_id_size;
120
- if input.len() < fcs_offset + fcs_field_size {
121
- return Err(BoundedError::BadMagic);
122
- }
123
-
124
- let fcs_bytes = &input[fcs_offset..fcs_offset + fcs_field_size];
125
- let value = match fcs_field_size {
126
- 1 => fcs_bytes[0] as u64,
127
- 2 => u16::from_le_bytes([fcs_bytes[0], fcs_bytes[1]]) as u64 + 256,
128
- 4 => u32::from_le_bytes([fcs_bytes[0], fcs_bytes[1], fcs_bytes[2], fcs_bytes[3]]) as u64,
129
- 8 => u64::from_le_bytes(fcs_bytes.try_into().unwrap()),
130
- _ => unreachable!(),
131
- };
132
-
133
- Ok(Some(value))
134
- }
135
-
136
- fn io_error_is_output_too_small(err: &std::io::Error) -> bool {
137
- matches!(
138
- err.get_ref()
139
- .and_then(|inner| inner.downcast_ref::<zstd::error::DecompressError>()),
140
- Some(zstd::error::DecompressError::OutputTooSmall)
141
- )
142
- }
143
-
144
- fn read_decoder_bounded<R: Read>(
145
- decoder: &mut R,
146
- max_output: usize,
147
- ) -> Result<Vec<u8>, BoundedError> {
148
- let mut output = Vec::new();
149
- let mut buf = [0u8; DECOMPRESS_READ_CHUNK];
150
-
151
- loop {
152
- let n = decoder.read(&mut buf).map_err(|e| {
153
- if io_error_is_output_too_small(&e) {
154
- BoundedError::OutputSizeLimit {
155
- limit: max_output as u64,
156
- }
157
- } else {
158
- BoundedError::DecoderFailed(format!("{e}"))
159
- }
160
- })?;
161
- if n == 0 {
162
- return Ok(output);
163
- }
164
-
165
- let Some(next_len) = output.len().checked_add(n) else {
166
- return Err(BoundedError::OutputSizeLimit {
167
- limit: max_output as u64,
168
- });
169
- };
170
- if next_len > max_output {
171
- return Err(BoundedError::OutputSizeLimit {
172
- limit: max_output as u64,
173
- });
174
- }
175
-
176
- output.extend_from_slice(&buf[..n]);
177
- }
101
+ zstd::frame::header::parse_frame_header(input)
102
+ .map(|header| header.frame_content_size)
103
+ .map_err(|err| match err {
104
+ zstd::DecompressError::BadMagic => BoundedError::BadMagic,
105
+ _ => BoundedError::DecoderFailed(err.to_string()),
106
+ })
178
107
  }
179
108
 
180
109
  fn decompress_bounded(
181
110
  compressed: &[u8],
182
- max_output: usize,
111
+ max_output: Option<usize>,
183
112
  dctx: &mut DecompressContext,
184
- dict: Option<&Dictionary>,
185
113
  ) -> Result<Vec<u8>, BoundedError> {
186
114
  if compressed.len() < ZSTD_FRAME_MAGIC.len() || compressed[..4] != ZSTD_FRAME_MAGIC {
187
115
  return Err(BoundedError::BadMagic);
188
116
  }
189
117
 
190
- let result = if max_output == 0 {
191
- dctx.decompress_with_limit(compressed, usize::MAX)
192
- .map(|out| out.into_owned())
193
- .map_err(|e| BoundedError::DecoderFailed(format!("{e}")))?
194
- } else {
195
- let mut decoder = match dict {
196
- Some(dict) => {
197
- zstd::FrameDecoder::with_dict_and_limit(compressed, dict.clone(), usize::MAX)
198
- }
199
- None => zstd::FrameDecoder::with_limit(compressed, usize::MAX),
200
- };
201
- read_decoder_bounded(&mut decoder, max_output)?
202
- };
203
-
204
- Ok(result)
118
+ let limit = max_output.unwrap_or(usize::MAX);
119
+ dctx.decompress_with_limit(compressed, limit)
120
+ .map(|out| out.into_owned())
121
+ .map_err(|err| match err {
122
+ zstd::DecompressError::OutputTooSmall => BoundedError::OutputSizeLimit {
123
+ limit: limit as u64,
124
+ },
125
+ _ => BoundedError::DecoderFailed(err.to_string()),
126
+ })
205
127
  }
206
128
 
207
- fn decompress_work_size(compressed: &[u8], max_output: usize) -> usize {
129
+ fn decompress_work_size(compressed: &[u8], max_output: Option<usize>) -> usize {
130
+ let limit = max_output.unwrap_or(usize::MAX);
208
131
  match parse_frame_content_size(compressed) {
209
- Ok(Some(n)) => usize::try_from(n).unwrap_or(usize::MAX),
210
- Ok(None) if max_output != 0 => max_output,
211
- _ => compressed.len(),
132
+ Ok(Some(n)) => usize::try_from(n).unwrap_or(usize::MAX).min(limit),
133
+ Ok(None) => max_output.unwrap_or(compressed.len()),
134
+ // The decoder rejects the first frame header without decoding.
135
+ Err(_) => 0,
212
136
  }
213
137
  }
214
138
 
@@ -277,7 +201,7 @@ fn make_frame_codec_data_type() -> rb_data_type_t {
277
201
  },
278
202
  parent: std::ptr::null(),
279
203
  data: std::ptr::null_mut(),
280
- flags: 1,
204
+ flags: rb::frozen_shareable_flags(),
281
205
  }
282
206
  }
283
207
 
@@ -372,7 +296,6 @@ unsafe fn dict_trainer_ref(value: VALUE) -> RbResult<&'static RbDictTrainer> {
372
296
  struct FrameCodec {
373
297
  dict_len: usize,
374
298
  dict_id: Option<u32>,
375
- dict: Option<Dictionary>,
376
299
  level: i32,
377
300
  cctx: Mutex<CompressContext>,
378
301
  dctx: Mutex<DecompressContext>,
@@ -382,16 +305,10 @@ unsafe impl Send for FrameCodec {}
382
305
  unsafe impl Sync for FrameCodec {}
383
306
 
384
307
  fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -> RbResult<VALUE> {
385
- let rb_dict = if rb_dict == rb::qnil() {
386
- None
387
- } else {
388
- let rb_dict = rb::string_value(rb_dict)?;
389
- rb::freeze_value(rb_dict)?;
390
- Some(rb::value_to_bytes(rb_dict)?)
391
- };
308
+ let rb_dict = rb::value_to_option_bytes(rb_dict)?;
392
309
  let id = rb::value_to_u32(id)?;
393
310
  let level = rb::value_to_i32(level)?;
394
- let (dict_len, dict_id, dict, cctx, dctx) = match rb_dict {
311
+ let (dict_len, dict_id, cctx, dctx) = match rb_dict {
395
312
  None => {
396
313
  let cctx = CompressContext::new(level).map_err(|e| {
397
314
  RubyErr::new(
@@ -399,7 +316,7 @@ fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
399
316
  format!("CompressContext::new failed: {e}"),
400
317
  )
401
318
  })?;
402
- (0, None, None, cctx, DecompressContext::new())
319
+ (0, None, cctx, DecompressContext::new())
403
320
  }
404
321
  Some(bytes) => {
405
322
  let dict = load_dict(&bytes)?;
@@ -411,36 +328,42 @@ fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
411
328
  )
412
329
  })?;
413
330
  let dctx = DecompressContext::with_dict(dict.clone());
414
- (dl, Some(id), Some(dict), cctx, dctx)
331
+ (dl, Some(id), cctx, dctx)
415
332
  }
416
333
  };
417
334
 
418
- unsafe {
335
+ let codec = unsafe {
419
336
  rb::wrap_typed_data(
420
337
  class,
421
338
  Box::new(FrameCodec {
422
339
  dict_len,
423
340
  dict_id,
424
- dict,
425
341
  level,
426
342
  cctx: Mutex::new(cctx),
427
343
  dctx: Mutex::new(dctx),
428
344
  }),
429
345
  frame_codec_data_type(),
430
- )
431
- }
346
+ )?
347
+ };
348
+ rb::make_shareable(codec)?;
349
+ Ok(codec)
432
350
  }
433
351
 
434
352
  fn frame_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE> {
435
353
  let rb_self = unsafe { frame_codec_ref(rb_self)? };
436
354
  let mut input = rb::input_bytes(rb_input)?;
437
355
  let release_gvl = should_release_compress_gvl(input.len());
438
- input.lock_for_without_gvl(release_gvl)?;
439
- let out = with_mutex(&rb_self.cctx, release_gvl, "FrameCodec CCtx", |cctx| {
440
- cctx.compress(input.as_slice())
441
- .map(|out| out.into_owned())
442
- .map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
443
- })?;
356
+ let out = with_mutex(
357
+ &rb_self.cctx,
358
+ release_gvl,
359
+ "FrameCodec CCtx",
360
+ &mut input,
361
+ |cctx, input| {
362
+ cctx.compress(input)
363
+ .map(|out| out.into_owned())
364
+ .map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
365
+ },
366
+ )?;
444
367
  rb::new_binary_string(&out)
445
368
  }
446
369
 
@@ -450,18 +373,22 @@ fn frame_codec_decompress_impl(
450
373
  max_output: VALUE,
451
374
  ) -> RbResult<VALUE> {
452
375
  let rb_self = unsafe { frame_codec_ref(rb_self)? };
376
+ let max_output = rb::value_to_option_usize(max_output)?;
453
377
  let mut compressed = rb::input_bytes(rb_input)?;
454
- let max_output = rb::value_to_usize(max_output)?;
455
378
  let release_gvl = should_release_frame_decompress_gvl(decompress_work_size(
456
379
  compressed.as_slice(),
457
380
  max_output,
458
381
  ));
459
- compressed.lock_for_without_gvl(release_gvl)?;
460
- let dict = rb_self.dict.clone();
461
- let out = with_mutex(&rb_self.dctx, release_gvl, "FrameCodec DCtx", |dctx| {
462
- decompress_bounded(compressed.as_slice(), max_output, dctx, dict.as_ref())
463
- .map_err(|e| bounded_err(e, "zstd frame decode failed"))
464
- })?;
382
+ let out = with_mutex(
383
+ &rb_self.dctx,
384
+ release_gvl,
385
+ "FrameCodec DCtx",
386
+ &mut compressed,
387
+ |dctx, compressed| {
388
+ decompress_bounded(compressed, max_output, dctx)
389
+ .map_err(|e| bounded_err(e, "zstd frame decode failed"))
390
+ },
391
+ )?;
465
392
  rb::new_binary_string(&out)
466
393
  }
467
394
 
@@ -543,7 +470,6 @@ unsafe extern "C" fn frame_codec_get_frame_content_size(_class: VALUE, rb_input:
543
470
  struct BlockCodec {
544
471
  dict_len: usize,
545
472
  dict_id: Option<u32>,
546
- dict: Option<Dictionary>,
547
473
  level: i32,
548
474
  cctx: Mutex<CompressContext>,
549
475
  dctx: Mutex<DecompressContext>,
@@ -553,7 +479,7 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
553
479
  let rb_dict = rb::value_to_option_bytes(rb_dict)?;
554
480
  let id = rb::value_to_u32(id)?;
555
481
  let level = rb::value_to_i32(level)?;
556
- let (dict_len, dict_id, dict, cctx, dctx) = match rb_dict {
482
+ let (dict_len, dict_id, cctx, dctx) = match rb_dict {
557
483
  None => {
558
484
  let cctx = CompressContext::new(level).map_err(|e| {
559
485
  RubyErr::new(
@@ -561,7 +487,7 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
561
487
  format!("CompressContext::new failed: {e}"),
562
488
  )
563
489
  })?;
564
- (0, None, None, cctx, DecompressContext::new())
490
+ (0, None, cctx, DecompressContext::new())
565
491
  }
566
492
  Some(bytes) => {
567
493
  let dict = load_dict(&bytes)?;
@@ -573,7 +499,7 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
573
499
  )
574
500
  })?;
575
501
  let dctx = DecompressContext::with_dict(dict.clone());
576
- (dl, Some(id), Some(dict), cctx, dctx)
502
+ (dl, Some(id), cctx, dctx)
577
503
  }
578
504
  };
579
505
 
@@ -583,7 +509,6 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
583
509
  Box::new(BlockCodec {
584
510
  dict_len,
585
511
  dict_id,
586
- dict,
587
512
  level,
588
513
  cctx: Mutex::new(cctx),
589
514
  dctx: Mutex::new(dctx),
@@ -597,12 +522,17 @@ fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
597
522
  let rb_self = unsafe { block_codec_ref(rb_self)? };
598
523
  let mut input = rb::input_bytes(rb_input)?;
599
524
  let release_gvl = should_release_compress_gvl(input.len());
600
- input.lock_for_without_gvl(release_gvl)?;
601
- let out = with_mutex(&rb_self.cctx, release_gvl, "BlockCodec CCtx", |cctx| {
602
- cctx.compress(input.as_slice())
603
- .map(|out| out.into_owned())
604
- .map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
605
- })?;
525
+ let out = with_mutex(
526
+ &rb_self.cctx,
527
+ release_gvl,
528
+ "BlockCodec CCtx",
529
+ &mut input,
530
+ |cctx, input| {
531
+ cctx.compress(input)
532
+ .map(|out| out.into_owned())
533
+ .map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
534
+ },
535
+ )?;
606
536
  rb::new_binary_string(&out)
607
537
  }
608
538
 
@@ -612,17 +542,18 @@ fn block_codec_decompress_impl(
612
542
  max_output: VALUE,
613
543
  ) -> RbResult<VALUE> {
614
544
  let rb_self = unsafe { block_codec_ref(rb_self)? };
615
- let compressed = rb::input_bytes(rb_input)?;
616
- let max_output = rb::value_to_usize(max_output)?;
617
- let out = with_mutex(&rb_self.dctx, false, "BlockCodec DCtx", |dctx| {
618
- decompress_bounded(
619
- compressed.as_slice(),
620
- max_output,
621
- dctx,
622
- rb_self.dict.as_ref(),
623
- )
624
- .map_err(|e| bounded_err(e, "zstd block decode failed"))
625
- })?;
545
+ let max_output = rb::value_to_option_usize(max_output)?;
546
+ let mut compressed = rb::input_bytes(rb_input)?;
547
+ let out = with_mutex(
548
+ &rb_self.dctx,
549
+ false,
550
+ "BlockCodec DCtx",
551
+ &mut compressed,
552
+ |dctx, compressed| {
553
+ decompress_bounded(compressed, max_output, dctx)
554
+ .map_err(|e| bounded_err(e, "zstd block decode failed"))
555
+ },
556
+ )?;
626
557
  rb::new_binary_string(&out)
627
558
  }
628
559
 
@@ -687,7 +618,8 @@ struct TrainerState {
687
618
  }
688
619
 
689
620
  fn dict_trainer_new_impl(class: VALUE, max_dict_size: VALUE) -> RbResult<VALUE> {
690
- let max_dict_size = rb::value_to_usize(max_dict_size)?;
621
+ // The trainer gives a MIN_DICT_SIZE dict for smaller sizes.
622
+ let max_dict_size = rb::value_to_usize(max_dict_size)?.max(zstd::dict::MIN_DICT_SIZE);
691
623
  unsafe {
692
624
  rb::wrap_typed_data(
693
625
  class,
@@ -704,6 +636,7 @@ fn dict_trainer_new_impl(class: VALUE, max_dict_size: VALUE) -> RbResult<VALUE>
704
636
  }
705
637
 
706
638
  fn dict_trainer_add_sample_impl(rb_self: VALUE, rb_data: VALUE) -> RbResult<VALUE> {
639
+ let data = rb::value_to_bytes(rb_data)?;
707
640
  let rb_self = unsafe { dict_trainer_ref(rb_self)? };
708
641
  let mut borrow = rb_self
709
642
  .inner
@@ -712,7 +645,6 @@ fn dict_trainer_add_sample_impl(rb_self: VALUE, rb_data: VALUE) -> RbResult<VALU
712
645
  let state = borrow
713
646
  .as_mut()
714
647
  .ok_or_else(|| RubyErr::runtime("DictTrainer already consumed by #train"))?;
715
- let data = rb::value_to_bytes(rb_data)?;
716
648
  if data.len() < 4 {
717
649
  return Ok(rb::qnil());
718
650
  }
@@ -960,14 +892,30 @@ mod tests {
960
892
  compressed.extend_from_slice(&zstd::compress(&[b'b'; 100], 1).unwrap());
961
893
 
962
894
  assert!(matches!(
963
- decompress_bounded(&compressed, 199, &mut dctx, None),
895
+ decompress_bounded(&compressed, Some(199), &mut dctx),
964
896
  Err(BoundedError::OutputSizeLimit { .. })
965
897
  ));
966
898
  assert_eq!(
967
- decompress_bounded(&compressed, 200, &mut dctx, None)
899
+ decompress_bounded(&compressed, Some(200), &mut dctx)
968
900
  .unwrap()
969
901
  .len(),
970
902
  200
971
903
  );
972
904
  }
905
+
906
+ #[test]
907
+ fn bounded_decompress_treats_zero_as_limit() {
908
+ let mut dctx = DecompressContext::new();
909
+ let empty = zstd::compress(b"", 1).unwrap();
910
+ let one = zstd::compress(b"a", 1).unwrap();
911
+
912
+ assert!(decompress_bounded(&empty, Some(0), &mut dctx)
913
+ .unwrap()
914
+ .is_empty());
915
+ assert!(matches!(
916
+ decompress_bounded(&one, Some(0), &mut dctx),
917
+ Err(BoundedError::OutputSizeLimit { limit: 0 })
918
+ ));
919
+ assert_eq!(decompress_bounded(&one, None, &mut dctx).unwrap(), b"a");
920
+ }
973
921
  }
data/ext/zrip/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,6 +270,14 @@ 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
 
273
+ pub fn value_to_option_usize(value: VALUE) -> RbResult<Option<usize>> {
274
+ if value == qnil() {
275
+ Ok(None)
276
+ } else {
277
+ value_to_usize(value).map(Some)
278
+ }
279
+ }
280
+
267
281
  pub fn value_to_option_bytes(value: VALUE) -> RbResult<Option<Vec<u8>>> {
268
282
  if value == qnil() {
269
283
  Ok(None)
@@ -293,14 +307,14 @@ impl InputBytes {
293
307
  self.as_slice().len()
294
308
  }
295
309
 
296
- 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<()> {
297
311
  if !release_gvl {
298
312
  return Ok(());
299
313
  }
300
314
 
301
315
  match self {
302
316
  #[cfg(ruby_engine = "mri")]
303
- Self::Borrowed(bytes) => bytes.lock_tmp(),
317
+ Self::Borrowed(bytes) => bytes.freeze(),
304
318
  #[cfg(not(ruby_engine = "mri"))]
305
319
  Self::Owned(_) => Ok(()),
306
320
  }
@@ -312,7 +326,7 @@ pub struct BorrowedStringBytes {
312
326
  value: VALUE,
313
327
  ptr: *const u8,
314
328
  len: usize,
315
- locked: bool,
329
+ frozen: bool,
316
330
  }
317
331
 
318
332
  #[cfg(ruby_engine = "mri")]
@@ -324,7 +338,7 @@ impl BorrowedStringBytes {
324
338
  value: string,
325
339
  ptr: bytes.as_ptr(),
326
340
  len: bytes.len(),
327
- locked: false,
341
+ frozen: false,
328
342
  })
329
343
  }
330
344
 
@@ -336,13 +350,20 @@ impl BorrowedStringBytes {
336
350
  }
337
351
  }
338
352
 
339
- fn lock_tmp(&mut self) -> RbResult<()> {
340
- 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 {
341
358
  return Ok(());
342
359
  }
343
360
 
344
- protect_value(|| unsafe { rb_str_locktmp(self.value) })?;
345
- 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;
346
367
  Ok(())
347
368
  }
348
369
  }
@@ -350,11 +371,6 @@ impl BorrowedStringBytes {
350
371
  #[cfg(ruby_engine = "mri")]
351
372
  impl Drop for BorrowedStringBytes {
352
373
  fn drop(&mut self) {
353
- if self.locked {
354
- unsafe {
355
- rb_str_unlocktmp(self.value);
356
- }
357
- }
358
374
  let _ = rb_sys::rb_gc_guard!(self.value);
359
375
  }
360
376
  }
@@ -401,6 +417,7 @@ pub fn value_to_u32(value: VALUE) -> RbResult<u32> {
401
417
  u32::try_from(value_to_usize(value)?).map_err(|_| RubyErr::arg("integer too large"))
402
418
  }
403
419
 
420
+ #[allow(dead_code)]
404
421
  pub fn value_to_i32(value: VALUE) -> RbResult<i32> {
405
422
  let mut out = 0i64;
406
423
  protect_value(|| {
@@ -414,10 +431,12 @@ pub fn usize_value(value: usize) -> RbResult<VALUE> {
414
431
  protect_value(|| unsafe { rb_sys::rb_ull2inum(value as u64) })
415
432
  }
416
433
 
434
+ #[allow(dead_code)]
417
435
  pub fn i32_value(value: i32) -> VALUE {
418
436
  unsafe { rb_sys::rb_int2inum(value as isize) }
419
437
  }
420
438
 
439
+ #[allow(dead_code)]
421
440
  pub fn u64_option_value(value: Option<u64>) -> RbResult<VALUE> {
422
441
  match value {
423
442
  Some(value) => protect_value(|| unsafe { rb_sys::rb_ull2inum(value) }),
@@ -527,6 +546,7 @@ pub unsafe fn define_singleton_method_2(
527
546
  })
528
547
  }
529
548
 
549
+ #[allow(dead_code)]
530
550
  pub unsafe fn define_singleton_method_3(
531
551
  object: VALUE,
532
552
  name: &CStr,
@@ -599,6 +619,7 @@ unsafe fn transmute_2(
599
619
  }
600
620
  }
601
621
 
622
+ #[allow(dead_code)]
602
623
  unsafe fn transmute_3(
603
624
  func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE) -> VALUE,
604
625
  ) -> unsafe extern "C" fn() -> VALUE {
@@ -613,3 +634,42 @@ unsafe fn transmute_3(
613
634
  fn c_long_len(len: usize) -> RbResult<c_long> {
614
635
  c_long::try_from(len).map_err(|_| RubyErr::arg("length too large"))
615
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
+ }
@@ -3,7 +3,7 @@
3
3
  require_relative "dictionary"
4
4
 
5
5
  module Zrip
6
- # Zstandard block-format codec.
6
+ # Zstandard codec for per-Ractor use.
7
7
  #
8
8
  # `BlockCodec` keeps mutable native context state and is intended to be used
9
9
  # per Ractor.
@@ -23,14 +23,14 @@ module Zrip
23
23
  # @raise [CompressError]
24
24
  #
25
25
  # @!method compress(bytes)
26
- # Compress bytes to a Zstandard block.
26
+ # Compress bytes to a Zstandard frame.
27
27
  # @param bytes [String] uncompressed bytes
28
28
  # @return [String]
29
29
  # @raise [CompressError]
30
30
  #
31
31
  # @!method decompress(bytes, max_output_size: nil)
32
- # Decompress a Zstandard block.
33
- # @param bytes [String] compressed Zstandard block
32
+ # Decompress a Zstandard frame.
33
+ # @param bytes [String] compressed Zstandard frame
34
34
  # @param max_output_size [Integer, nil] optional output byte limit
35
35
  # @return [String]
36
36
  # @raise [DecompressError]
@@ -38,8 +38,8 @@ module Zrip
38
38
  #
39
39
  # @!method _native_decompress(bytes, max_output_size)
40
40
  # Native decompression entry used by #decompress.
41
- # @param bytes [String] compressed Zstandard block
42
- # @param max_output_size [Integer] output byte limit, or `0` for unbounded
41
+ # @param bytes [String] compressed Zstandard frame
42
+ # @param max_output_size [Integer, nil] output byte limit, or `nil` for unbounded
43
43
  # @return [String]
44
44
  # @raise [DecompressError]
45
45
  # @raise [OutputSizeLimitError]
@@ -69,7 +69,7 @@ module Zrip
69
69
 
70
70
 
71
71
  def decompress(bytes, max_output_size: nil)
72
- _native_decompress(bytes, Integer(max_output_size || 0))
72
+ _native_decompress(bytes, max_output_size && Integer(max_output_size))
73
73
  end
74
74
  end
75
75
  end
@@ -5,12 +5,14 @@ module Zrip
5
5
  #
6
6
  # @!method self.new(max_dict_size)
7
7
  # Create a dictionary trainer.
8
- # @param max_dict_size [Integer] maximum dictionary size in bytes
8
+ # @param max_dict_size [Integer] maximum dictionary size in bytes;
9
+ # sizes under 256 count as 256
9
10
  # @return [DictTrainer]
10
11
  #
11
12
  # @!method self._native_new(max_dict_size)
12
13
  # Native constructor used by `.new`.
13
- # @param max_dict_size [Integer] maximum dictionary size in bytes
14
+ # @param max_dict_size [Integer] maximum dictionary size in bytes;
15
+ # sizes under 256 count as 256
14
16
  # @return [DictTrainer]
15
17
  #
16
18
  # @!method add_sample(bytes)
@@ -32,7 +34,7 @@ module Zrip
32
34
  # @return [Boolean]
33
35
  #
34
36
  # @!method max_dict_size
35
- # @return [Integer] configured maximum dictionary size
37
+ # @return [Integer] maximum dictionary size, at least 256
36
38
  class DictTrainer
37
39
  def self.new(max_dict_size)
38
40
  _native_new(max_dict_size)
@@ -45,7 +45,7 @@ module Zrip
45
45
  # @!method _native_decompress(bytes, max_output_size)
46
46
  # Native decompression entry used by #decompress.
47
47
  # @param bytes [String] compressed Zstandard frame
48
- # @param max_output_size [Integer] output byte limit, or `0` for unbounded
48
+ # @param max_output_size [Integer, nil] output byte limit, or `nil` for unbounded
49
49
  # @return [String]
50
50
  # @raise [DecompressError]
51
51
  # @raise [OutputSizeLimitError]
@@ -78,7 +78,7 @@ module Zrip
78
78
 
79
79
 
80
80
  def decompress(bytes, max_output_size: nil)
81
- _native_decompress(bytes, Integer(max_output_size || 0))
81
+ _native_decompress(bytes, max_output_size && Integer(max_output_size))
82
82
  end
83
83
  end
84
84
  end
data/lib/zrip/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Zrip
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: zrip
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 zrip, a pure-Rust Zstandard implementation.
27
33
  Frame-format and block-format compress/decompress with optional dictionary support,
28
34
  configurable compression levels, and FastCOVER-based dictionary training. Ractor-safe.
@@ -54,7 +60,7 @@ licenses:
54
60
  - MIT
55
61
  metadata:
56
62
  homepage_uri: https://github.com/paddor/zrip-rb
57
- source_code_uri: https://github.com/paddor/zrip-rb
63
+ source_code_uri: https://github.com/paddor/zrip-rb/tree/main
58
64
  documentation_uri: https://rubydoc.info/gems/zrip
59
65
  changelog_uri: https://github.com/paddor/zrip-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 Zstandard bindings for Ruby (pure-Rust zrip backend)
78
84
  test_files: []