zrip 0.2.1 → 0.3.0
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 +4 -4
- data/CHANGELOG.md +32 -0
- data/Cargo.lock +22 -22
- data/README.md +17 -0
- data/ext/zrip/Cargo.toml +2 -2
- data/ext/zrip/src/adaptive.rs +150 -0
- data/ext/zrip/src/lib.rs +165 -36
- data/ext/zrip/src/rb.rs +62 -21
- data/lib/zrip/adaptive_level.rb +56 -0
- data/lib/zrip/block_codec.rb +25 -7
- data/lib/zrip/dict_trainer.rb +5 -3
- data/lib/zrip/frame_codec.rb +20 -2
- data/lib/zrip/version.rb +1 -1
- data/lib/zrip.rb +1 -0
- metadata +3 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 7d15447bc566dfc7a7043bd366103ca041245cc7e8c62adf4968414c8ad196a1
|
|
4
|
+
data.tar.gz: fe0f8ed6916f89ef2663f828a5f21e108d03005e1f9dfa5b090af40def53b9f6
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 263643a0dfbbb4a7000c308ebd37f71727e25c25dbdfba0828e50c450bf5e2dfb3a18f591e2bbd71d7facefae81bf53394a1f32bfd88a49f4ff37972a3892c4f
|
|
7
|
+
data.tar.gz: 37beca4c7901d474ee31713ceb0ef7a414a87f6623afa9c56acdc8216395a0166ca5768de6679385e872945282c3a80e39b4ac128874879b346dab307a850921
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,38 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.3.0] - 2026-11-26
|
|
6
|
+
|
|
7
|
+
- `FrameCodec#level=` and `BlockCodec#level=` switch later frames to a new
|
|
8
|
+
level. A dictionary stays loaded; zrip prepares it again for the level.
|
|
9
|
+
- `FrameCodec#take_stats` and `BlockCodec#take_stats` return the bytes in
|
|
10
|
+
and out and the time spent compressing since the last call. The time is
|
|
11
|
+
measured natively around each compression, so it leaves out waits for the
|
|
12
|
+
GVL and the codec lock.
|
|
13
|
+
- `Zrip::AdaptiveLevel.new(range, start: -1)` wraps zrip's adaptive level:
|
|
14
|
+
`#update(plain:, compressed:, busy:, bottleneck: nil)` takes one window's
|
|
15
|
+
stats and what limited the sender, and returns the next level.
|
|
16
|
+
- `FrameCodec#decompress` and `BlockCodec#decompress` decode into a new
|
|
17
|
+
buffer per call. The codec kept a buffer the size of its largest frame
|
|
18
|
+
for its lifetime, and copied each frame out of it.
|
|
19
|
+
|
|
20
|
+
## [0.2.2] - 2026-11-26
|
|
21
|
+
|
|
22
|
+
- Update the `zrip` crate dependency to 0.8.29. Levels are retuned, so
|
|
23
|
+
compressed output differs from 0.2.1, and decoding rejects the frames C
|
|
24
|
+
zstd 1.6.0 rejects.
|
|
25
|
+
- `DictTrainer#train` fills `max_dict_size`. Dictionaries came out 110-150
|
|
26
|
+
bytes short. Sizes under 256 now count as 256, and `max_dict_size`
|
|
27
|
+
returns the size used. They gave a dictionary of padding only.
|
|
28
|
+
- Let several threads compress or decompress one mutable String at once.
|
|
29
|
+
Calls that release the GVL now borrow a frozen copy of the input instead
|
|
30
|
+
of locking it, so they no longer raise `RuntimeError` when another call
|
|
31
|
+
holds the same String, and the caller may modify it meanwhile.
|
|
32
|
+
- `max_output_size: 0` now limits output to 0 bytes. It used to disable the
|
|
33
|
+
limit. Omit it or pass `nil` for no limit.
|
|
34
|
+
- Fail on a bad first frame header without releasing the GVL.
|
|
35
|
+
- Document that `BlockCodec` writes and reads Zstandard frames.
|
|
36
|
+
|
|
5
37
|
## [0.2.1] - 2026-10-11
|
|
6
38
|
|
|
7
39
|
- Update the `zrip` crate dependency to 0.8.11 and `rb-sys` to 0.9.130.
|
data/Cargo.lock
CHANGED
|
@@ -69,9 +69,9 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
|
|
|
69
69
|
|
|
70
70
|
[[package]]
|
|
71
71
|
name = "fearless_simd"
|
|
72
|
-
version = "1.
|
|
72
|
+
version = "1.3.0"
|
|
73
73
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
74
|
-
checksum = "
|
|
74
|
+
checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599"
|
|
75
75
|
|
|
76
76
|
[[package]]
|
|
77
77
|
name = "glob"
|
|
@@ -96,9 +96,9 @@ checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
|
|
|
96
96
|
|
|
97
97
|
[[package]]
|
|
98
98
|
name = "libc"
|
|
99
|
-
version = "0.2.
|
|
99
|
+
version = "0.2.191"
|
|
100
100
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
101
|
-
checksum = "
|
|
101
|
+
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
|
102
102
|
|
|
103
103
|
[[package]]
|
|
104
104
|
name = "libloading"
|
|
@@ -176,9 +176,9 @@ dependencies = [
|
|
|
176
176
|
|
|
177
177
|
[[package]]
|
|
178
178
|
name = "regex"
|
|
179
|
-
version = "1.13.
|
|
179
|
+
version = "1.13.2"
|
|
180
180
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
181
|
-
checksum = "
|
|
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.
|
|
191
|
+
version = "0.4.19"
|
|
192
192
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
193
|
-
checksum = "
|
|
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.
|
|
202
|
+
version = "0.8.12"
|
|
203
203
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
204
|
-
checksum = "
|
|
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.
|
|
237
|
+
version = "1.0.27"
|
|
238
238
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
239
|
-
checksum = "
|
|
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.
|
|
249
|
+
version = "0.3.0"
|
|
250
250
|
dependencies = [
|
|
251
251
|
"rb-sys",
|
|
252
|
-
"zrip 0.8.
|
|
252
|
+
"zrip 0.8.29",
|
|
253
253
|
]
|
|
254
254
|
|
|
255
255
|
[[package]]
|
|
256
256
|
name = "zrip"
|
|
257
|
-
version = "0.8.
|
|
257
|
+
version = "0.8.29"
|
|
258
258
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
259
|
-
checksum = "
|
|
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.
|
|
268
|
+
version = "0.14.4"
|
|
269
269
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
270
|
-
checksum = "
|
|
270
|
+
checksum = "5f6ea7ccd7799d815353fb360e6d2d21207001d58f0a7c02ec9e45d95fe60ae4"
|
|
271
271
|
|
|
272
272
|
[[package]]
|
|
273
273
|
name = "zrip-decode"
|
|
274
|
-
version = "0.8.
|
|
274
|
+
version = "0.8.22"
|
|
275
275
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
276
|
-
checksum = "
|
|
276
|
+
checksum = "89ced3ea49c7e49b32b675294304987c3481f2f7b19f3c60ff6b1e4b73eb2ffd"
|
|
277
277
|
dependencies = [
|
|
278
278
|
"fearless_simd",
|
|
279
279
|
"zrip-core",
|
|
@@ -281,9 +281,9 @@ dependencies = [
|
|
|
281
281
|
|
|
282
282
|
[[package]]
|
|
283
283
|
name = "zrip-encode"
|
|
284
|
-
version = "0.
|
|
284
|
+
version = "0.10.6"
|
|
285
285
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
286
|
-
checksum = "
|
|
286
|
+
checksum = "26cf89a0e00fb1e421a0e1b911cdf593178affc2cbcffae62b6dea25089e6fca"
|
|
287
287
|
dependencies = [
|
|
288
288
|
"fearless_simd",
|
|
289
289
|
"zrip-core",
|
data/README.md
CHANGED
|
@@ -59,6 +59,23 @@ original = codec.decompress(compressed)
|
|
|
59
59
|
```ruby
|
|
60
60
|
fast = Zrip::FrameCodec.new(level: -3) # negative = faster
|
|
61
61
|
strong = Zrip::FrameCodec.new(level: 4) # highest supported level
|
|
62
|
+
fast.level = 1 # later frames; a dictionary stays loaded
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Adaptive level
|
|
66
|
+
|
|
67
|
+
`AdaptiveLevel` walks the levels of a range, one step per window of work,
|
|
68
|
+
toward ratio when output stalls or the CPU idles and toward speed when the CPU
|
|
69
|
+
is the limit. `#take_stats` reports a codec's work since the last call, with
|
|
70
|
+
the compression time measured natively, so waits for the GVL don't count.
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
codec = Zrip::FrameCodec.new(level: -1)
|
|
74
|
+
adaptive = Zrip::AdaptiveLevel.new(-7..4, start: -1)
|
|
75
|
+
|
|
76
|
+
# once per window, e.g. every 100 ms
|
|
77
|
+
stats = codec.take_stats #=> {plain: 1048576, compressed: 312000, busy: 0.004}
|
|
78
|
+
codec.level = adaptive.update(**stats, bottleneck: :output) # or :cpu, :input, nil
|
|
62
79
|
```
|
|
63
80
|
|
|
64
81
|
### Bounded decompression
|
data/ext/zrip/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "zrip"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.3.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
build = "build.rs"
|
|
6
6
|
|
|
@@ -9,7 +9,7 @@ name = "zrip"
|
|
|
9
9
|
crate-type = ["cdylib", "rlib"]
|
|
10
10
|
|
|
11
11
|
[dependencies]
|
|
12
|
-
zstd = { version = "0.8.
|
|
12
|
+
zstd = { version = "0.8.29", package = "zrip", features = ["frame", "dict_builder"] }
|
|
13
13
|
rb-sys = "0.9.130"
|
|
14
14
|
|
|
15
15
|
[build-dependencies]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
//! `Zrip::AdaptiveLevel`: zrip's hill climb over compression levels.
|
|
2
|
+
|
|
3
|
+
use std::ffi::c_void;
|
|
4
|
+
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
5
|
+
use std::sync::{Mutex, OnceLock};
|
|
6
|
+
use std::time::Duration;
|
|
7
|
+
|
|
8
|
+
use rb_sys::{rb_data_type_struct__bindgen_ty_1, rb_data_type_t, size_t, VALUE};
|
|
9
|
+
use zstd::adaptive::{AdaptiveLevel, Bottleneck, CompressStats};
|
|
10
|
+
|
|
11
|
+
use crate::rb::{self, RbResult, RubyErr};
|
|
12
|
+
|
|
13
|
+
/// Lowest and highest level `AdaptiveLevel` accepts in a range: -8 runs as
|
|
14
|
+
/// -7, and 0 as the default level.
|
|
15
|
+
const RANGE_MIN: i32 = -8;
|
|
16
|
+
const RANGE_MAX: i32 = 4;
|
|
17
|
+
|
|
18
|
+
struct NativeDataType(rb_data_type_t);
|
|
19
|
+
|
|
20
|
+
unsafe impl Send for NativeDataType {}
|
|
21
|
+
unsafe impl Sync for NativeDataType {}
|
|
22
|
+
|
|
23
|
+
static DATA_TYPE: OnceLock<NativeDataType> = OnceLock::new();
|
|
24
|
+
|
|
25
|
+
fn data_type() -> *const rb_data_type_t {
|
|
26
|
+
&DATA_TYPE
|
|
27
|
+
.get_or_init(|| {
|
|
28
|
+
NativeDataType(rb_data_type_t {
|
|
29
|
+
wrap_struct_name: c"zrip_adaptive_level".as_ptr(),
|
|
30
|
+
function: rb_data_type_struct__bindgen_ty_1 {
|
|
31
|
+
dmark: None,
|
|
32
|
+
dfree: Some(free),
|
|
33
|
+
dsize: Some(native_size),
|
|
34
|
+
dcompact: None,
|
|
35
|
+
reserved: [std::ptr::null_mut(); 1],
|
|
36
|
+
},
|
|
37
|
+
parent: std::ptr::null(),
|
|
38
|
+
data: std::ptr::null_mut(),
|
|
39
|
+
flags: 1,
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
.0
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/// The controller. Ruby calls hold the GVL, so the mutex never waits.
|
|
46
|
+
struct RbAdaptiveLevel(Mutex<AdaptiveLevel>);
|
|
47
|
+
|
|
48
|
+
unsafe extern "C" fn free(ptr: *mut c_void) {
|
|
49
|
+
if ptr.is_null() {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let _ = catch_unwind(AssertUnwindSafe(|| unsafe {
|
|
54
|
+
drop(Box::from_raw(ptr as *mut RbAdaptiveLevel));
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
unsafe extern "C" fn native_size(_ptr: *const c_void) -> size_t {
|
|
59
|
+
std::mem::size_of::<RbAdaptiveLevel>() as size_t
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
unsafe fn adaptive_ref(value: VALUE) -> RbResult<&'static RbAdaptiveLevel> {
|
|
63
|
+
unsafe { rb::typed_data_ref(value, data_type(), "Zrip::AdaptiveLevel") }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
fn with_level<R>(rb_self: VALUE, func: impl FnOnce(&mut AdaptiveLevel) -> R) -> RbResult<R> {
|
|
67
|
+
let rb_self = unsafe { adaptive_ref(rb_self)? };
|
|
68
|
+
let mut guard = rb_self
|
|
69
|
+
.0
|
|
70
|
+
.lock()
|
|
71
|
+
.map_err(|_| RubyErr::runtime("AdaptiveLevel mutex poisoned"))?;
|
|
72
|
+
Ok(func(&mut guard))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
fn new_impl(class: VALUE, min: VALUE, max: VALUE, start: VALUE) -> RbResult<VALUE> {
|
|
76
|
+
let min = rb::value_to_i32(min)?;
|
|
77
|
+
let max = rb::value_to_i32(max)?;
|
|
78
|
+
let start = rb::value_to_i32(start)?;
|
|
79
|
+
if min > max || max < RANGE_MIN || min > RANGE_MAX {
|
|
80
|
+
return Err(RubyErr::arg(format!(
|
|
81
|
+
"{min}..{max} holds no zrip level ({RANGE_MIN}..{RANGE_MAX})"
|
|
82
|
+
)));
|
|
83
|
+
}
|
|
84
|
+
let level = AdaptiveLevel::new(min..=max, start);
|
|
85
|
+
unsafe {
|
|
86
|
+
rb::wrap_typed_data(
|
|
87
|
+
class,
|
|
88
|
+
Box::new(RbAdaptiveLevel(Mutex::new(level))),
|
|
89
|
+
data_type(),
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// `bottleneck` is -1 (none), 0 (output), 1 (CPU) or 2 (input).
|
|
95
|
+
fn update_impl(
|
|
96
|
+
rb_self: VALUE,
|
|
97
|
+
plain: VALUE,
|
|
98
|
+
compressed: VALUE,
|
|
99
|
+
busy_ns: VALUE,
|
|
100
|
+
bottleneck: VALUE,
|
|
101
|
+
) -> RbResult<VALUE> {
|
|
102
|
+
let stats = CompressStats {
|
|
103
|
+
plain: rb::value_to_u64(plain)?,
|
|
104
|
+
compressed: rb::value_to_u64(compressed)?,
|
|
105
|
+
busy: Duration::from_nanos(rb::value_to_u64(busy_ns)?),
|
|
106
|
+
};
|
|
107
|
+
let bottleneck = match rb::value_to_i32(bottleneck)? {
|
|
108
|
+
-1 => None,
|
|
109
|
+
0 => Some(Bottleneck::Output),
|
|
110
|
+
1 => Some(Bottleneck::Cpu),
|
|
111
|
+
2 => Some(Bottleneck::Input),
|
|
112
|
+
code => return Err(RubyErr::arg(format!("unknown bottleneck code {code}"))),
|
|
113
|
+
};
|
|
114
|
+
let level = with_level(rb_self, |level| level.update(stats, bottleneck))?;
|
|
115
|
+
Ok(rb::i32_value(level))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
fn level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
119
|
+
Ok(rb::i32_value(with_level(rb_self, |level| level.level())?))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
unsafe extern "C" fn adaptive_new(class: VALUE, min: VALUE, max: VALUE, start: VALUE) -> VALUE {
|
|
123
|
+
rb::wrap(|| new_impl(class, min, max, start))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
unsafe extern "C" fn adaptive_update(
|
|
127
|
+
rb_self: VALUE,
|
|
128
|
+
plain: VALUE,
|
|
129
|
+
compressed: VALUE,
|
|
130
|
+
busy_ns: VALUE,
|
|
131
|
+
bottleneck: VALUE,
|
|
132
|
+
) -> VALUE {
|
|
133
|
+
rb::wrap(|| update_impl(rb_self, plain, compressed, busy_ns, bottleneck))
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
unsafe extern "C" fn adaptive_level(rb_self: VALUE) -> VALUE {
|
|
137
|
+
rb::wrap(|| level_impl(rb_self))
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/// Defines `Zrip::AdaptiveLevel` under `module`.
|
|
141
|
+
pub fn define(module: VALUE) -> RbResult<()> {
|
|
142
|
+
let class = unsafe { rb::define_class_under(module, c"AdaptiveLevel", rb_sys::rb_cObject)? };
|
|
143
|
+
unsafe {
|
|
144
|
+
rb::undef_alloc_func(class)?;
|
|
145
|
+
rb::define_singleton_method_3(class, c"_native_new", adaptive_new)?;
|
|
146
|
+
rb::define_method_4(class, c"_update", adaptive_update)?;
|
|
147
|
+
rb::define_method_0(class, c"level", adaptive_level)?;
|
|
148
|
+
}
|
|
149
|
+
Ok(())
|
|
150
|
+
}
|
data/ext/zrip/src/lib.rs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
mod adaptive;
|
|
1
2
|
mod rb;
|
|
2
3
|
|
|
3
4
|
use std::ffi::c_void;
|
|
4
5
|
use std::panic::{catch_unwind, AssertUnwindSafe};
|
|
6
|
+
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
|
|
5
7
|
use std::sync::{Mutex, OnceLock, TryLockError};
|
|
8
|
+
use std::time::{Duration, Instant};
|
|
6
9
|
|
|
7
10
|
use rb_sys::{rb_data_type_struct__bindgen_ty_1, rb_data_type_t, size_t, VALUE};
|
|
8
11
|
use zstd::dict::fastcover::FastCoverParams;
|
|
@@ -61,7 +64,7 @@ where
|
|
|
61
64
|
F: FnOnce(&mut T, &[u8]) -> RbResult<R>,
|
|
62
65
|
{
|
|
63
66
|
if release_gvl {
|
|
64
|
-
input.
|
|
67
|
+
input.freeze_for_without_gvl(true)?;
|
|
65
68
|
return rb::maybe_without_gvl(true, || {
|
|
66
69
|
let mut guard = mutex
|
|
67
70
|
.lock()
|
|
@@ -74,7 +77,7 @@ where
|
|
|
74
77
|
Ok(mut guard) => func(&mut guard, input.as_slice()),
|
|
75
78
|
Err(TryLockError::WouldBlock) => {
|
|
76
79
|
// Even a small input needs protection when contention releases GVL.
|
|
77
|
-
input.
|
|
80
|
+
input.freeze_for_without_gvl(true)?;
|
|
78
81
|
rb::maybe_without_gvl(true, || {
|
|
79
82
|
let mut guard = mutex
|
|
80
83
|
.lock()
|
|
@@ -86,6 +89,76 @@ where
|
|
|
86
89
|
}
|
|
87
90
|
}
|
|
88
91
|
|
|
92
|
+
/// Compression work since the last `#take_stats`. `busy` is measured around
|
|
93
|
+
/// the compression itself, so it leaves out waits for the GVL and the lock.
|
|
94
|
+
#[derive(Default)]
|
|
95
|
+
struct CompressStats {
|
|
96
|
+
plain: AtomicU64,
|
|
97
|
+
compressed: AtomicU64,
|
|
98
|
+
busy_ns: AtomicU64,
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
impl CompressStats {
|
|
102
|
+
fn record(&self, plain: usize, compressed: usize, busy: Duration) {
|
|
103
|
+
self.plain.fetch_add(plain as u64, Ordering::Relaxed);
|
|
104
|
+
self.compressed
|
|
105
|
+
.fetch_add(compressed as u64, Ordering::Relaxed);
|
|
106
|
+
let busy_ns = u64::try_from(busy.as_nanos()).unwrap_or(u64::MAX);
|
|
107
|
+
self.busy_ns.fetch_add(busy_ns, Ordering::Relaxed);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/// Returns `[plain, compressed, busy_ns]` and resets them.
|
|
111
|
+
fn take(&self) -> RbResult<VALUE> {
|
|
112
|
+
rb::new_array(&[
|
|
113
|
+
rb::u64_value(self.plain.swap(0, Ordering::Relaxed))?,
|
|
114
|
+
rb::u64_value(self.compressed.swap(0, Ordering::Relaxed))?,
|
|
115
|
+
rb::u64_value(self.busy_ns.swap(0, Ordering::Relaxed))?,
|
|
116
|
+
])
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/// Compresses `input` and records the work in `stats`.
|
|
121
|
+
fn compress_recorded(
|
|
122
|
+
cctx: &mut CompressContext,
|
|
123
|
+
stats: &CompressStats,
|
|
124
|
+
input: &[u8],
|
|
125
|
+
) -> RbResult<Vec<u8>> {
|
|
126
|
+
let start = Instant::now();
|
|
127
|
+
let frame = cctx
|
|
128
|
+
.compress(input)
|
|
129
|
+
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))?;
|
|
130
|
+
let busy = start.elapsed();
|
|
131
|
+
stats.record(input.len(), frame.len(), busy);
|
|
132
|
+
Ok(frame.into_owned())
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Switches `cctx` to `rb_level` for later frames. A dictionary stays loaded;
|
|
136
|
+
/// zrip prepares it again for the new level.
|
|
137
|
+
fn set_level(
|
|
138
|
+
cctx: &Mutex<CompressContext>,
|
|
139
|
+
level: &AtomicI32,
|
|
140
|
+
rb_level: VALUE,
|
|
141
|
+
name: &str,
|
|
142
|
+
) -> RbResult<VALUE> {
|
|
143
|
+
let new_level = rb::value_to_i32(rb_level)?;
|
|
144
|
+
let apply = |cctx: &mut CompressContext| {
|
|
145
|
+
cctx.set_level(new_level)
|
|
146
|
+
.map_err(|e| RubyErr::arg(format!("zrip level {new_level}: {e}")))
|
|
147
|
+
};
|
|
148
|
+
let poisoned = || RubyErr::runtime(format!("{name} mutex poisoned"));
|
|
149
|
+
match cctx.try_lock() {
|
|
150
|
+
Ok(mut guard) => apply(&mut guard)?,
|
|
151
|
+
// A compression holds it without the GVL: wait without it as well.
|
|
152
|
+
Err(TryLockError::WouldBlock) => rb::maybe_without_gvl(true, || {
|
|
153
|
+
let mut guard = cctx.lock().map_err(|_| poisoned())?;
|
|
154
|
+
apply(&mut guard)
|
|
155
|
+
})??,
|
|
156
|
+
Err(TryLockError::Poisoned(_)) => return Err(poisoned()),
|
|
157
|
+
}
|
|
158
|
+
level.store(new_level, Ordering::Relaxed);
|
|
159
|
+
Ok(rb::i32_value(new_level))
|
|
160
|
+
}
|
|
161
|
+
|
|
89
162
|
// ---------- frame header parsing ----------
|
|
90
163
|
|
|
91
164
|
const ZSTD_FRAME_MAGIC: [u8; 4] = [0x28, 0xB5, 0x2F, 0xFD];
|
|
@@ -108,33 +181,34 @@ fn parse_frame_content_size(input: &[u8]) -> Result<Option<u64>, BoundedError> {
|
|
|
108
181
|
|
|
109
182
|
fn decompress_bounded(
|
|
110
183
|
compressed: &[u8],
|
|
111
|
-
max_output: usize
|
|
184
|
+
max_output: Option<usize>,
|
|
112
185
|
dctx: &mut DecompressContext,
|
|
113
186
|
) -> Result<Vec<u8>, BoundedError> {
|
|
114
187
|
if compressed.len() < ZSTD_FRAME_MAGIC.len() || compressed[..4] != ZSTD_FRAME_MAGIC {
|
|
115
188
|
return Err(BoundedError::BadMagic);
|
|
116
189
|
}
|
|
117
190
|
|
|
118
|
-
let limit =
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
.map(|out| out.into_owned())
|
|
191
|
+
let limit = max_output.unwrap_or(usize::MAX);
|
|
192
|
+
// A fresh buffer per frame: the context's own one would keep the largest
|
|
193
|
+
// frame's size for the codec's lifetime.
|
|
194
|
+
let mut out = Vec::new();
|
|
195
|
+
dctx.decompress_into_with_limit(compressed, &mut out, limit)
|
|
196
|
+
.map(|_| out)
|
|
125
197
|
.map_err(|err| match err {
|
|
126
198
|
zstd::DecompressError::OutputTooSmall => BoundedError::OutputSizeLimit {
|
|
127
|
-
limit:
|
|
199
|
+
limit: limit as u64,
|
|
128
200
|
},
|
|
129
201
|
_ => BoundedError::DecoderFailed(err.to_string()),
|
|
130
202
|
})
|
|
131
203
|
}
|
|
132
204
|
|
|
133
|
-
fn decompress_work_size(compressed: &[u8], max_output: usize) -> usize {
|
|
205
|
+
fn decompress_work_size(compressed: &[u8], max_output: Option<usize>) -> usize {
|
|
206
|
+
let limit = max_output.unwrap_or(usize::MAX);
|
|
134
207
|
match parse_frame_content_size(compressed) {
|
|
135
|
-
Ok(Some(n)) => usize::try_from(n).unwrap_or(usize::MAX),
|
|
136
|
-
Ok(None)
|
|
137
|
-
|
|
208
|
+
Ok(Some(n)) => usize::try_from(n).unwrap_or(usize::MAX).min(limit),
|
|
209
|
+
Ok(None) => max_output.unwrap_or(compressed.len()),
|
|
210
|
+
// The decoder rejects the first frame header without decoding.
|
|
211
|
+
Err(_) => 0,
|
|
138
212
|
}
|
|
139
213
|
}
|
|
140
214
|
|
|
@@ -298,9 +372,10 @@ unsafe fn dict_trainer_ref(value: VALUE) -> RbResult<&'static RbDictTrainer> {
|
|
|
298
372
|
struct FrameCodec {
|
|
299
373
|
dict_len: usize,
|
|
300
374
|
dict_id: Option<u32>,
|
|
301
|
-
level:
|
|
375
|
+
level: AtomicI32,
|
|
302
376
|
cctx: Mutex<CompressContext>,
|
|
303
377
|
dctx: Mutex<DecompressContext>,
|
|
378
|
+
stats: CompressStats,
|
|
304
379
|
}
|
|
305
380
|
|
|
306
381
|
unsafe impl Send for FrameCodec {}
|
|
@@ -340,9 +415,10 @@ fn frame_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
|
|
|
340
415
|
Box::new(FrameCodec {
|
|
341
416
|
dict_len,
|
|
342
417
|
dict_id,
|
|
343
|
-
level,
|
|
418
|
+
level: AtomicI32::new(level),
|
|
344
419
|
cctx: Mutex::new(cctx),
|
|
345
420
|
dctx: Mutex::new(dctx),
|
|
421
|
+
stats: CompressStats::default(),
|
|
346
422
|
}),
|
|
347
423
|
frame_codec_data_type(),
|
|
348
424
|
)?
|
|
@@ -360,11 +436,7 @@ fn frame_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
|
|
|
360
436
|
release_gvl,
|
|
361
437
|
"FrameCodec CCtx",
|
|
362
438
|
&mut input,
|
|
363
|
-
|cctx, input|
|
|
364
|
-
cctx.compress(input)
|
|
365
|
-
.map(|out| out.into_owned())
|
|
366
|
-
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
|
|
367
|
-
},
|
|
439
|
+
|cctx, input| compress_recorded(cctx, &rb_self.stats, input),
|
|
368
440
|
)?;
|
|
369
441
|
rb::new_binary_string(&out)
|
|
370
442
|
}
|
|
@@ -375,7 +447,7 @@ fn frame_codec_decompress_impl(
|
|
|
375
447
|
max_output: VALUE,
|
|
376
448
|
) -> RbResult<VALUE> {
|
|
377
449
|
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
378
|
-
let max_output = rb::
|
|
450
|
+
let max_output = rb::value_to_option_usize(max_output)?;
|
|
379
451
|
let mut compressed = rb::input_bytes(rb_input)?;
|
|
380
452
|
let release_gvl = should_release_frame_decompress_gvl(decompress_work_size(
|
|
381
453
|
compressed.as_slice(),
|
|
@@ -411,7 +483,7 @@ fn frame_codec_id_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
|
411
483
|
|
|
412
484
|
fn frame_codec_level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
413
485
|
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
414
|
-
Ok(rb::i32_value(rb_self.level))
|
|
486
|
+
Ok(rb::i32_value(rb_self.level.load(Ordering::Relaxed)))
|
|
415
487
|
}
|
|
416
488
|
|
|
417
489
|
fn frame_codec_get_frame_content_size_impl(rb_input: VALUE) -> RbResult<VALUE> {
|
|
@@ -459,6 +531,24 @@ unsafe extern "C" fn frame_codec_id(rb_self: VALUE) -> VALUE {
|
|
|
459
531
|
rb::wrap(|| frame_codec_id_impl(rb_self))
|
|
460
532
|
}
|
|
461
533
|
|
|
534
|
+
fn frame_codec_set_level_impl(rb_self: VALUE, rb_level: VALUE) -> RbResult<VALUE> {
|
|
535
|
+
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
536
|
+
set_level(&rb_self.cctx, &rb_self.level, rb_level, "FrameCodec CCtx")
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
fn frame_codec_take_stats_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
540
|
+
let rb_self = unsafe { frame_codec_ref(rb_self)? };
|
|
541
|
+
rb_self.stats.take()
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
unsafe extern "C" fn frame_codec_set_level(rb_self: VALUE, rb_level: VALUE) -> VALUE {
|
|
545
|
+
rb::wrap(|| frame_codec_set_level_impl(rb_self, rb_level))
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
unsafe extern "C" fn frame_codec_take_stats(rb_self: VALUE) -> VALUE {
|
|
549
|
+
rb::wrap(|| frame_codec_take_stats_impl(rb_self))
|
|
550
|
+
}
|
|
551
|
+
|
|
462
552
|
unsafe extern "C" fn frame_codec_level(rb_self: VALUE) -> VALUE {
|
|
463
553
|
rb::wrap(|| frame_codec_level_impl(rb_self))
|
|
464
554
|
}
|
|
@@ -472,9 +562,10 @@ unsafe extern "C" fn frame_codec_get_frame_content_size(_class: VALUE, rb_input:
|
|
|
472
562
|
struct BlockCodec {
|
|
473
563
|
dict_len: usize,
|
|
474
564
|
dict_id: Option<u32>,
|
|
475
|
-
level:
|
|
565
|
+
level: AtomicI32,
|
|
476
566
|
cctx: Mutex<CompressContext>,
|
|
477
567
|
dctx: Mutex<DecompressContext>,
|
|
568
|
+
stats: CompressStats,
|
|
478
569
|
}
|
|
479
570
|
|
|
480
571
|
fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -> RbResult<VALUE> {
|
|
@@ -511,9 +602,10 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, id: VALUE, level: VALUE) -
|
|
|
511
602
|
Box::new(BlockCodec {
|
|
512
603
|
dict_len,
|
|
513
604
|
dict_id,
|
|
514
|
-
level,
|
|
605
|
+
level: AtomicI32::new(level),
|
|
515
606
|
cctx: Mutex::new(cctx),
|
|
516
607
|
dctx: Mutex::new(dctx),
|
|
608
|
+
stats: CompressStats::default(),
|
|
517
609
|
}),
|
|
518
610
|
block_codec_data_type(),
|
|
519
611
|
)
|
|
@@ -529,11 +621,7 @@ fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
|
|
|
529
621
|
release_gvl,
|
|
530
622
|
"BlockCodec CCtx",
|
|
531
623
|
&mut input,
|
|
532
|
-
|cctx, input|
|
|
533
|
-
cctx.compress(input)
|
|
534
|
-
.map(|out| out.into_owned())
|
|
535
|
-
.map_err(|e| RubyErr::new(compress_error(), format!("zstd compress failed: {e}")))
|
|
536
|
-
},
|
|
624
|
+
|cctx, input| compress_recorded(cctx, &rb_self.stats, input),
|
|
537
625
|
)?;
|
|
538
626
|
rb::new_binary_string(&out)
|
|
539
627
|
}
|
|
@@ -544,7 +632,7 @@ fn block_codec_decompress_impl(
|
|
|
544
632
|
max_output: VALUE,
|
|
545
633
|
) -> RbResult<VALUE> {
|
|
546
634
|
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
547
|
-
let max_output = rb::
|
|
635
|
+
let max_output = rb::value_to_option_usize(max_output)?;
|
|
548
636
|
let mut compressed = rb::input_bytes(rb_input)?;
|
|
549
637
|
let out = with_mutex(
|
|
550
638
|
&rb_self.dctx,
|
|
@@ -571,7 +659,7 @@ fn block_codec_has_dict_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
|
571
659
|
|
|
572
660
|
fn block_codec_level_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
573
661
|
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
574
|
-
Ok(rb::i32_value(rb_self.level))
|
|
662
|
+
Ok(rb::i32_value(rb_self.level.load(Ordering::Relaxed)))
|
|
575
663
|
}
|
|
576
664
|
|
|
577
665
|
unsafe extern "C" fn block_codec_new(
|
|
@@ -603,6 +691,24 @@ unsafe extern "C" fn block_codec_has_dict(rb_self: VALUE) -> VALUE {
|
|
|
603
691
|
rb::wrap(|| block_codec_has_dict_impl(rb_self))
|
|
604
692
|
}
|
|
605
693
|
|
|
694
|
+
fn block_codec_set_level_impl(rb_self: VALUE, rb_level: VALUE) -> RbResult<VALUE> {
|
|
695
|
+
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
696
|
+
set_level(&rb_self.cctx, &rb_self.level, rb_level, "BlockCodec CCtx")
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
fn block_codec_take_stats_impl(rb_self: VALUE) -> RbResult<VALUE> {
|
|
700
|
+
let rb_self = unsafe { block_codec_ref(rb_self)? };
|
|
701
|
+
rb_self.stats.take()
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
unsafe extern "C" fn block_codec_set_level(rb_self: VALUE, rb_level: VALUE) -> VALUE {
|
|
705
|
+
rb::wrap(|| block_codec_set_level_impl(rb_self, rb_level))
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
unsafe extern "C" fn block_codec_take_stats(rb_self: VALUE) -> VALUE {
|
|
709
|
+
rb::wrap(|| block_codec_take_stats_impl(rb_self))
|
|
710
|
+
}
|
|
711
|
+
|
|
606
712
|
unsafe extern "C" fn block_codec_level(rb_self: VALUE) -> VALUE {
|
|
607
713
|
rb::wrap(|| block_codec_level_impl(rb_self))
|
|
608
714
|
}
|
|
@@ -620,7 +726,8 @@ struct TrainerState {
|
|
|
620
726
|
}
|
|
621
727
|
|
|
622
728
|
fn dict_trainer_new_impl(class: VALUE, max_dict_size: VALUE) -> RbResult<VALUE> {
|
|
623
|
-
|
|
729
|
+
// The trainer gives a MIN_DICT_SIZE dict for smaller sizes.
|
|
730
|
+
let max_dict_size = rb::value_to_usize(max_dict_size)?.max(zstd::dict::MIN_DICT_SIZE);
|
|
624
731
|
unsafe {
|
|
625
732
|
rb::wrap_typed_data(
|
|
626
733
|
class,
|
|
@@ -813,6 +920,8 @@ fn init() -> RbResult<()> {
|
|
|
813
920
|
rb::define_method_0(frame_codec_class, c"has_dict?", frame_codec_has_dict)?;
|
|
814
921
|
rb::define_method_0(frame_codec_class, c"id", frame_codec_id)?;
|
|
815
922
|
rb::define_method_0(frame_codec_class, c"level", frame_codec_level)?;
|
|
923
|
+
rb::define_method_1(frame_codec_class, c"level=", frame_codec_set_level)?;
|
|
924
|
+
rb::define_method_0(frame_codec_class, c"_take_stats", frame_codec_take_stats)?;
|
|
816
925
|
}
|
|
817
926
|
|
|
818
927
|
let block_codec_class =
|
|
@@ -829,8 +938,12 @@ fn init() -> RbResult<()> {
|
|
|
829
938
|
rb::define_method_0(block_codec_class, c"size", block_codec_size)?;
|
|
830
939
|
rb::define_method_0(block_codec_class, c"has_dict?", block_codec_has_dict)?;
|
|
831
940
|
rb::define_method_0(block_codec_class, c"level", block_codec_level)?;
|
|
941
|
+
rb::define_method_1(block_codec_class, c"level=", block_codec_set_level)?;
|
|
942
|
+
rb::define_method_0(block_codec_class, c"_take_stats", block_codec_take_stats)?;
|
|
832
943
|
}
|
|
833
944
|
|
|
945
|
+
adaptive::define(module)?;
|
|
946
|
+
|
|
834
947
|
let trainer_class =
|
|
835
948
|
unsafe { rb::define_class_under(module, c"DictTrainer", rb_sys::rb_cObject)? };
|
|
836
949
|
unsafe {
|
|
@@ -893,14 +1006,30 @@ mod tests {
|
|
|
893
1006
|
compressed.extend_from_slice(&zstd::compress(&[b'b'; 100], 1).unwrap());
|
|
894
1007
|
|
|
895
1008
|
assert!(matches!(
|
|
896
|
-
decompress_bounded(&compressed, 199, &mut dctx),
|
|
1009
|
+
decompress_bounded(&compressed, Some(199), &mut dctx),
|
|
897
1010
|
Err(BoundedError::OutputSizeLimit { .. })
|
|
898
1011
|
));
|
|
899
1012
|
assert_eq!(
|
|
900
|
-
decompress_bounded(&compressed, 200, &mut dctx)
|
|
1013
|
+
decompress_bounded(&compressed, Some(200), &mut dctx)
|
|
901
1014
|
.unwrap()
|
|
902
1015
|
.len(),
|
|
903
1016
|
200
|
|
904
1017
|
);
|
|
905
1018
|
}
|
|
1019
|
+
|
|
1020
|
+
#[test]
|
|
1021
|
+
fn bounded_decompress_treats_zero_as_limit() {
|
|
1022
|
+
let mut dctx = DecompressContext::new();
|
|
1023
|
+
let empty = zstd::compress(b"", 1).unwrap();
|
|
1024
|
+
let one = zstd::compress(b"a", 1).unwrap();
|
|
1025
|
+
|
|
1026
|
+
assert!(decompress_bounded(&empty, Some(0), &mut dctx)
|
|
1027
|
+
.unwrap()
|
|
1028
|
+
.is_empty());
|
|
1029
|
+
assert!(matches!(
|
|
1030
|
+
decompress_bounded(&one, Some(0), &mut dctx),
|
|
1031
|
+
Err(BoundedError::OutputSizeLimit { limit: 0 })
|
|
1032
|
+
));
|
|
1033
|
+
assert_eq!(decompress_bounded(&one, None, &mut dctx).unwrap(), b"a");
|
|
1034
|
+
}
|
|
906
1035
|
}
|
data/ext/zrip/src/rb.rs
CHANGED
|
@@ -6,13 +6,6 @@ use rb_sys::{rb_data_type_t, VALUE};
|
|
|
6
6
|
|
|
7
7
|
pub type RbResult<T = VALUE> = Result<T, RubyErr>;
|
|
8
8
|
|
|
9
|
-
#[cfg(ruby_engine = "mri")]
|
|
10
|
-
unsafe extern "C" {
|
|
11
|
-
fn rb_obj_frozen_p(obj: VALUE) -> VALUE;
|
|
12
|
-
fn rb_str_locktmp(str: VALUE) -> VALUE;
|
|
13
|
-
fn rb_str_unlocktmp(str: VALUE) -> VALUE;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
9
|
#[cfg(ruby_engine = "mri")]
|
|
17
10
|
type RbWithoutGvlFunc = unsafe extern "C" fn(*mut c_void) -> *mut c_void;
|
|
18
11
|
#[cfg(ruby_engine = "mri")]
|
|
@@ -185,7 +178,7 @@ where
|
|
|
185
178
|
output: None,
|
|
186
179
|
};
|
|
187
180
|
// Ruby checks interrupts before and after the callback. Protect the call
|
|
188
|
-
// so an exception still drops native output and
|
|
181
|
+
// so an exception still drops native output and borrowed strings.
|
|
189
182
|
protect_unit(|| unsafe {
|
|
190
183
|
rb_thread_call_without_gvl(
|
|
191
184
|
Some(without_gvl_trampoline::<F, R>),
|
|
@@ -277,6 +270,14 @@ pub fn value_to_bytes(value: VALUE) -> RbResult<Vec<u8>> {
|
|
|
277
270
|
bytes_from_string_value(string).map(|bytes| bytes.to_vec())
|
|
278
271
|
}
|
|
279
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
|
+
|
|
280
281
|
pub fn value_to_option_bytes(value: VALUE) -> RbResult<Option<Vec<u8>>> {
|
|
281
282
|
if value == qnil() {
|
|
282
283
|
Ok(None)
|
|
@@ -306,14 +307,14 @@ impl InputBytes {
|
|
|
306
307
|
self.as_slice().len()
|
|
307
308
|
}
|
|
308
309
|
|
|
309
|
-
pub fn
|
|
310
|
+
pub fn freeze_for_without_gvl(&mut self, release_gvl: bool) -> RbResult<()> {
|
|
310
311
|
if !release_gvl {
|
|
311
312
|
return Ok(());
|
|
312
313
|
}
|
|
313
314
|
|
|
314
315
|
match self {
|
|
315
316
|
#[cfg(ruby_engine = "mri")]
|
|
316
|
-
Self::Borrowed(bytes) => bytes.
|
|
317
|
+
Self::Borrowed(bytes) => bytes.freeze(),
|
|
317
318
|
#[cfg(not(ruby_engine = "mri"))]
|
|
318
319
|
Self::Owned(_) => Ok(()),
|
|
319
320
|
}
|
|
@@ -325,7 +326,7 @@ pub struct BorrowedStringBytes {
|
|
|
325
326
|
value: VALUE,
|
|
326
327
|
ptr: *const u8,
|
|
327
328
|
len: usize,
|
|
328
|
-
|
|
329
|
+
frozen: bool,
|
|
329
330
|
}
|
|
330
331
|
|
|
331
332
|
#[cfg(ruby_engine = "mri")]
|
|
@@ -337,7 +338,7 @@ impl BorrowedStringBytes {
|
|
|
337
338
|
value: string,
|
|
338
339
|
ptr: bytes.as_ptr(),
|
|
339
340
|
len: bytes.len(),
|
|
340
|
-
|
|
341
|
+
frozen: false,
|
|
341
342
|
})
|
|
342
343
|
}
|
|
343
344
|
|
|
@@ -349,13 +350,20 @@ impl BorrowedStringBytes {
|
|
|
349
350
|
}
|
|
350
351
|
}
|
|
351
352
|
|
|
352
|
-
|
|
353
|
-
|
|
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 {
|
|
354
358
|
return Ok(());
|
|
355
359
|
}
|
|
356
360
|
|
|
357
|
-
protect_value(|| unsafe {
|
|
358
|
-
|
|
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;
|
|
359
367
|
Ok(())
|
|
360
368
|
}
|
|
361
369
|
}
|
|
@@ -363,11 +371,6 @@ impl BorrowedStringBytes {
|
|
|
363
371
|
#[cfg(ruby_engine = "mri")]
|
|
364
372
|
impl Drop for BorrowedStringBytes {
|
|
365
373
|
fn drop(&mut self) {
|
|
366
|
-
if self.locked {
|
|
367
|
-
unsafe {
|
|
368
|
-
rb_str_unlocktmp(self.value);
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
374
|
let _ = rb_sys::rb_gc_guard!(self.value);
|
|
372
375
|
}
|
|
373
376
|
}
|
|
@@ -414,6 +417,7 @@ pub fn value_to_u32(value: VALUE) -> RbResult<u32> {
|
|
|
414
417
|
u32::try_from(value_to_usize(value)?).map_err(|_| RubyErr::arg("integer too large"))
|
|
415
418
|
}
|
|
416
419
|
|
|
420
|
+
#[allow(dead_code)]
|
|
417
421
|
pub fn value_to_i32(value: VALUE) -> RbResult<i32> {
|
|
418
422
|
let mut out = 0i64;
|
|
419
423
|
protect_value(|| {
|
|
@@ -423,14 +427,28 @@ pub fn value_to_i32(value: VALUE) -> RbResult<i32> {
|
|
|
423
427
|
i32::try_from(out).map_err(|_| RubyErr::arg("integer too large"))
|
|
424
428
|
}
|
|
425
429
|
|
|
430
|
+
pub fn value_to_u64(value: VALUE) -> RbResult<u64> {
|
|
431
|
+
Ok(value_to_usize(value)? as u64)
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
pub fn u64_value(value: u64) -> RbResult<VALUE> {
|
|
435
|
+
protect_value(|| unsafe { rb_sys::rb_ull2inum(value) })
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
pub fn new_array(values: &[VALUE]) -> RbResult<VALUE> {
|
|
439
|
+
protect_value(|| unsafe { rb_sys::rb_ary_new_from_values(values.len() as _, values.as_ptr()) })
|
|
440
|
+
}
|
|
441
|
+
|
|
426
442
|
pub fn usize_value(value: usize) -> RbResult<VALUE> {
|
|
427
443
|
protect_value(|| unsafe { rb_sys::rb_ull2inum(value as u64) })
|
|
428
444
|
}
|
|
429
445
|
|
|
446
|
+
#[allow(dead_code)]
|
|
430
447
|
pub fn i32_value(value: i32) -> VALUE {
|
|
431
448
|
unsafe { rb_sys::rb_int2inum(value as isize) }
|
|
432
449
|
}
|
|
433
450
|
|
|
451
|
+
#[allow(dead_code)]
|
|
434
452
|
pub fn u64_option_value(value: Option<u64>) -> RbResult<VALUE> {
|
|
435
453
|
match value {
|
|
436
454
|
Some(value) => protect_value(|| unsafe { rb_sys::rb_ull2inum(value) }),
|
|
@@ -540,6 +558,7 @@ pub unsafe fn define_singleton_method_2(
|
|
|
540
558
|
})
|
|
541
559
|
}
|
|
542
560
|
|
|
561
|
+
#[allow(dead_code)]
|
|
543
562
|
pub unsafe fn define_singleton_method_3(
|
|
544
563
|
object: VALUE,
|
|
545
564
|
name: &CStr,
|
|
@@ -580,6 +599,27 @@ pub unsafe fn define_method_2(
|
|
|
580
599
|
})
|
|
581
600
|
}
|
|
582
601
|
|
|
602
|
+
pub unsafe fn define_method_4(
|
|
603
|
+
class: VALUE,
|
|
604
|
+
name: &CStr,
|
|
605
|
+
func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
606
|
+
) -> RbResult<()> {
|
|
607
|
+
protect_unit(|| unsafe {
|
|
608
|
+
rb_sys::rb_define_method(class, name.as_ptr(), Some(transmute_4(func)), 4)
|
|
609
|
+
})
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
unsafe fn transmute_4(
|
|
613
|
+
func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
614
|
+
) -> unsafe extern "C" fn() -> VALUE {
|
|
615
|
+
unsafe {
|
|
616
|
+
std::mem::transmute::<
|
|
617
|
+
unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
618
|
+
unsafe extern "C" fn() -> VALUE,
|
|
619
|
+
>(func)
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
583
623
|
unsafe fn transmute_0(
|
|
584
624
|
func: unsafe extern "C" fn(VALUE) -> VALUE,
|
|
585
625
|
) -> unsafe extern "C" fn() -> VALUE {
|
|
@@ -612,6 +652,7 @@ unsafe fn transmute_2(
|
|
|
612
652
|
}
|
|
613
653
|
}
|
|
614
654
|
|
|
655
|
+
#[allow(dead_code)]
|
|
615
656
|
unsafe fn transmute_3(
|
|
616
657
|
func: unsafe extern "C" fn(VALUE, VALUE, VALUE, VALUE) -> VALUE,
|
|
617
658
|
) -> unsafe extern "C" fn() -> VALUE {
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Zrip
|
|
4
|
+
# Picks a compression level per window of work: zrip's hill climb over the
|
|
5
|
+
# levels of a range. Feed it each window's stats (see `FrameCodec#take_stats`)
|
|
6
|
+
# and what limited the sender, and compress at the level it returns.
|
|
7
|
+
#
|
|
8
|
+
# Not Ractor-shareable: use one per connection.
|
|
9
|
+
#
|
|
10
|
+
# @!method level
|
|
11
|
+
# @return [Integer] the level to compress at
|
|
12
|
+
class AdaptiveLevel
|
|
13
|
+
BOTTLENECKS = { output: 0, cpu: 1, input: 2 }.freeze
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# @param range [Range<Integer>] levels to walk, within -8..4
|
|
17
|
+
# @param start [Integer] start at the first level of the range not below
|
|
18
|
+
# it; -1 by default, as omq.rs
|
|
19
|
+
# @raise [ArgumentError] if the range holds no zrip level
|
|
20
|
+
def self.new(range, start: -1)
|
|
21
|
+
unless Range === range && Integer === range.begin && Integer === range.end
|
|
22
|
+
raise ArgumentError, "range must be a Range of Integers, got #{range.inspect}"
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
min = range.min
|
|
26
|
+
max = range.max
|
|
27
|
+
raise ArgumentError, "#{range.inspect} is empty" if min.nil?
|
|
28
|
+
|
|
29
|
+
_native_new(min, max, Integer(start))
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# Records one window at the current level and returns the next level.
|
|
34
|
+
#
|
|
35
|
+
# @param plain [Integer] input bytes compressed in the window
|
|
36
|
+
# @param compressed [Integer] compressed bytes
|
|
37
|
+
# @param busy [Float] seconds spent compressing
|
|
38
|
+
# @param bottleneck [Symbol, nil] `:output` (writes stalled), `:cpu`
|
|
39
|
+
# (input waited while output kept up), `:input` (nothing waited), or nil
|
|
40
|
+
# (the default) when unclear; the level then holds
|
|
41
|
+
# @return [Integer]
|
|
42
|
+
# @raise [ArgumentError] on an unknown bottleneck
|
|
43
|
+
def update(plain:, compressed:, busy:, bottleneck: nil)
|
|
44
|
+
code = if bottleneck.nil?
|
|
45
|
+
-1
|
|
46
|
+
else
|
|
47
|
+
BOTTLENECKS.fetch(bottleneck) do
|
|
48
|
+
raise ArgumentError, "bottleneck must be :output, :cpu, :input or nil, got #{bottleneck.inspect}"
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
_update(Integer(plain), Integer(compressed), (Float(busy) * 1e9).round, code)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
end
|
|
56
|
+
end
|
data/lib/zrip/block_codec.rb
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
require_relative "dictionary"
|
|
4
4
|
|
|
5
5
|
module Zrip
|
|
6
|
-
# Zstandard
|
|
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,20 @@ module Zrip
|
|
|
23
23
|
# @raise [CompressError]
|
|
24
24
|
#
|
|
25
25
|
# @!method compress(bytes)
|
|
26
|
-
# Compress bytes to a Zstandard
|
|
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
|
+
# @!method level=(level)
|
|
32
|
+
# Compress later frames at `level`. A dictionary stays loaded.
|
|
33
|
+
# @param level [Integer] compression level
|
|
34
|
+
# @return [Integer]
|
|
35
|
+
# @raise [ArgumentError] for a level zrip lacks
|
|
36
|
+
#
|
|
31
37
|
# @!method decompress(bytes, max_output_size: nil)
|
|
32
|
-
# Decompress a Zstandard
|
|
33
|
-
# @param bytes [String] compressed Zstandard
|
|
38
|
+
# Decompress a Zstandard frame.
|
|
39
|
+
# @param bytes [String] compressed Zstandard frame
|
|
34
40
|
# @param max_output_size [Integer, nil] optional output byte limit
|
|
35
41
|
# @return [String]
|
|
36
42
|
# @raise [DecompressError]
|
|
@@ -38,8 +44,8 @@ module Zrip
|
|
|
38
44
|
#
|
|
39
45
|
# @!method _native_decompress(bytes, max_output_size)
|
|
40
46
|
# Native decompression entry used by #decompress.
|
|
41
|
-
# @param bytes [String] compressed Zstandard
|
|
42
|
-
# @param max_output_size [Integer] output byte limit, or `
|
|
47
|
+
# @param bytes [String] compressed Zstandard frame
|
|
48
|
+
# @param max_output_size [Integer, nil] output byte limit, or `nil` for unbounded
|
|
43
49
|
# @return [String]
|
|
44
50
|
# @raise [DecompressError]
|
|
45
51
|
# @raise [OutputSizeLimitError]
|
|
@@ -69,7 +75,19 @@ module Zrip
|
|
|
69
75
|
|
|
70
76
|
|
|
71
77
|
def decompress(bytes, max_output_size: nil)
|
|
72
|
-
_native_decompress(bytes, Integer(max_output_size
|
|
78
|
+
_native_decompress(bytes, max_output_size && Integer(max_output_size))
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Returns the compression work since the last call and resets it.
|
|
83
|
+
# `busy` is the time spent compressing, measured natively, so it leaves
|
|
84
|
+
# out waits for the GVL.
|
|
85
|
+
#
|
|
86
|
+
# @return [Hash{Symbol => Numeric}] `{plain:, compressed:, busy:}` in
|
|
87
|
+
# bytes and seconds
|
|
88
|
+
def take_stats
|
|
89
|
+
plain, compressed, busy_ns = _take_stats
|
|
90
|
+
{ plain: plain, compressed: compressed, busy: busy_ns / 1e9 }
|
|
73
91
|
end
|
|
74
92
|
end
|
|
75
93
|
end
|
data/lib/zrip/dict_trainer.rb
CHANGED
|
@@ -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]
|
|
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)
|
data/lib/zrip/frame_codec.rb
CHANGED
|
@@ -34,6 +34,12 @@ module Zrip
|
|
|
34
34
|
# @return [String]
|
|
35
35
|
# @raise [CompressError]
|
|
36
36
|
#
|
|
37
|
+
# @!method level=(level)
|
|
38
|
+
# Compress later frames at `level`. A dictionary stays loaded.
|
|
39
|
+
# @param level [Integer] compression level
|
|
40
|
+
# @return [Integer]
|
|
41
|
+
# @raise [ArgumentError] for a level zrip lacks
|
|
42
|
+
#
|
|
37
43
|
# @!method decompress(bytes, max_output_size: nil)
|
|
38
44
|
# Decompress a Zstandard frame.
|
|
39
45
|
# @param bytes [String] compressed Zstandard frame
|
|
@@ -45,7 +51,7 @@ module Zrip
|
|
|
45
51
|
# @!method _native_decompress(bytes, max_output_size)
|
|
46
52
|
# Native decompression entry used by #decompress.
|
|
47
53
|
# @param bytes [String] compressed Zstandard frame
|
|
48
|
-
# @param max_output_size [Integer] output byte limit, or `
|
|
54
|
+
# @param max_output_size [Integer, nil] output byte limit, or `nil` for unbounded
|
|
49
55
|
# @return [String]
|
|
50
56
|
# @raise [DecompressError]
|
|
51
57
|
# @raise [OutputSizeLimitError]
|
|
@@ -78,7 +84,19 @@ module Zrip
|
|
|
78
84
|
|
|
79
85
|
|
|
80
86
|
def decompress(bytes, max_output_size: nil)
|
|
81
|
-
_native_decompress(bytes, Integer(max_output_size
|
|
87
|
+
_native_decompress(bytes, max_output_size && Integer(max_output_size))
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Returns the compression work since the last call and resets it.
|
|
92
|
+
# `busy` is the time spent compressing, measured natively, so it leaves
|
|
93
|
+
# out waits for the GVL.
|
|
94
|
+
#
|
|
95
|
+
# @return [Hash{Symbol => Numeric}] `{plain:, compressed:, busy:}` in
|
|
96
|
+
# bytes and seconds
|
|
97
|
+
def take_stats
|
|
98
|
+
plain, compressed, busy_ns = _take_stats
|
|
99
|
+
{ plain: plain, compressed: compressed, busy: busy_ns / 1e9 }
|
|
82
100
|
end
|
|
83
101
|
end
|
|
84
102
|
end
|
data/lib/zrip/version.rb
CHANGED
data/lib/zrip.rb
CHANGED
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.
|
|
4
|
+
version: 0.3.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Patrik Wenger
|
|
@@ -47,9 +47,11 @@ files:
|
|
|
47
47
|
- ext/zrip/Cargo.toml
|
|
48
48
|
- ext/zrip/build.rs
|
|
49
49
|
- ext/zrip/extconf.rb
|
|
50
|
+
- ext/zrip/src/adaptive.rs
|
|
50
51
|
- ext/zrip/src/lib.rs
|
|
51
52
|
- ext/zrip/src/rb.rs
|
|
52
53
|
- lib/zrip.rb
|
|
54
|
+
- lib/zrip/adaptive_level.rb
|
|
53
55
|
- lib/zrip/block_codec.rb
|
|
54
56
|
- lib/zrip/dict_trainer.rb
|
|
55
57
|
- lib/zrip/dictionary.rb
|