lz4rip 0.2.2 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 67a8b9bf2a0abb6a7630773720ae606dc1729be0aa56bdf4b851bf523beb2d4f
4
- data.tar.gz: 55a3745ca8e940589a6659d68c41f2af81d82b3edf6a6ca22d9f496d4c331fd4
3
+ metadata.gz: 0be78a0755eec4e7af9fb1bd60e9f300acb7ebb1f985cabb74b9ddc58baa3caa
4
+ data.tar.gz: 1d55969e05addddaf4972dfe5164dc0ea8f9f8bc4c0217b3de64e6da32a129f6
5
5
  SHA512:
6
- metadata.gz: b56524f4b6c057d47a31f5e4e411c7e155a70d4027cb9de42b54e61d2d97c10a6aa94f31473d4ec73afa282eaef786e10497d9d1b73e6db5142a322eec1c4820
7
- data.tar.gz: 5e5a4186fcfbcfdfc254bc33768f63469868182ed898716ea7e6161f69ec744f9c285306810b982178e52d2d713b674a5fdd9b60f373607c29dceaf100b51961
6
+ metadata.gz: 340789f5f802bd244149a7346d998c9f175964a60788f7b872c00b313310e323e7589373b1d10afac140083c006fca90b9d7a877cb6561e3d4f718f2e154ff6c
7
+ data.tar.gz: 17cc18e51f08808a923ffd0093ff300e4a391d518c71e9004cb68d8af8552624dd341cd6ba212498a8b76ac27f82edd8b151af865640f6f451cdb2210888bf75
data/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.3.0] - 2026-11-26
6
+
7
+ - Update the `lz4rip` crate dependency to 0.12.9, for the ratio profile with
8
+ a dictionary and the compressors' heap sizes.
9
+ - `BlockCodec.new(profile: :ratio)`, with or without `dict:`, compresses to
10
+ smaller output with lz4rip's ratio profile. Any LZ4 decoder reads it. With
11
+ a dictionary, it hashes the dictionary once instead of for each message.
12
+ It releases the GVL from 128 KiB inputs instead of 256 KiB: it compresses
13
+ 1.4-10x slower per byte.
14
+ - `BlockCodec#decompress` raises `DecompressError` for a `decompressed_size:`
15
+ the block cannot decode to (more than 255 times its length) before
16
+ allocating, and takes an optional `max_decompressed_size:`, as
17
+ `FrameCodec#decompress` does.
18
+ - `BlockCodec` makes its compressor on its first `#compress`, so a codec
19
+ that only decompresses holds only its dictionary. A dictionary codec held
20
+ 16 KiB of compressor tables from the start.
21
+ - `BlockCodec#size` reports the bytes the codec holds: its compressor
22
+ tables, including those a ratio codec makes on first use, and its copies
23
+ of the dictionary. A dictionary codec reported one table and one copy.
24
+
5
25
  ## [0.2.2] - 2026-11-26
6
26
 
7
27
  - Update the `lz4rip` crate dependency to 0.12.7. Block decompression caps
data/Cargo.lock CHANGED
@@ -106,17 +106,17 @@ dependencies = [
106
106
 
107
107
  [[package]]
108
108
  name = "lz4rip"
109
- version = "0.2.2"
109
+ version = "0.3.0"
110
110
  dependencies = [
111
- "lz4rip 0.12.7",
111
+ "lz4rip 0.12.9",
112
112
  "rb-sys",
113
113
  ]
114
114
 
115
115
  [[package]]
116
116
  name = "lz4rip"
117
- version = "0.12.7"
117
+ version = "0.12.9"
118
118
  source = "registry+https://github.com/rust-lang/crates.io-index"
119
- checksum = "ba714cda4452679bec0dd3910f3979a3a803d51dbb490c237aa15dcb95432dd1"
119
+ checksum = "4dd27acb1a4d2b823738e9b3e63e1ddba5d24f52e97de40834c59d728e8bcfc9"
120
120
  dependencies = [
121
121
  "lz4rip-core",
122
122
  "lz4rip-decode",
@@ -132,18 +132,18 @@ checksum = "052afa89a977207a207f3e074b1518b0fb5767dab3274464fd1ee5fc7699a30b"
132
132
 
133
133
  [[package]]
134
134
  name = "lz4rip-decode"
135
- version = "0.11.2"
135
+ version = "0.11.3"
136
136
  source = "registry+https://github.com/rust-lang/crates.io-index"
137
- checksum = "1b0652316d9108ecf75802ddc55f4174a836f2c93c3ab3b06ed009e211d9f9c7"
137
+ checksum = "45f2489cd1216c98522f01f257b2e7dd09d1ba964f2498ce239387fd8fee6aca"
138
138
  dependencies = [
139
139
  "lz4rip-core",
140
140
  ]
141
141
 
142
142
  [[package]]
143
143
  name = "lz4rip-encode"
144
- version = "0.10.17"
144
+ version = "0.10.18"
145
145
  source = "registry+https://github.com/rust-lang/crates.io-index"
146
- checksum = "ff6d1b221814509df4735ac32847dc169e6a8b0375683e6c5bc8139c4dd620c2"
146
+ checksum = "ba7a8cdade339cca4b0f1c1d334edd1b36a01ebe6976940ede6eea7a3e28e8e6"
147
147
  dependencies = [
148
148
  "lz4rip-core",
149
149
  ]
data/README.md CHANGED
@@ -54,7 +54,25 @@ original = codec.decompress(compressed, decompressed_size: 12_000)
54
54
  ```
55
55
 
56
56
  Block decompression requires the original size up front. This is by design: LZ4
57
- block format does not store it, so the caller must track it.
57
+ block format does not store it, so the caller must track it. A size the block
58
+ cannot decode to (more than 255 times its length) raises `DecompressError`
59
+ before anything is allocated, and `max_decompressed_size:` sets a lower limit, as
60
+ for `FrameCodec`:
61
+
62
+ ```ruby
63
+ codec.decompress(compressed, decompressed_size: peer_size, max_decompressed_size: 1 << 20)
64
+ ```
65
+
66
+ `profile: :ratio` compresses to smaller output, more slowly. Any LZ4 decoder
67
+ reads it, so only the sender needs it. It holds an 8 KB table, plus 64 KB from
68
+ its first input above 4 KiB; with a dictionary, 16 KB of tables while input and
69
+ dictionary stay within 4 KiB, 64 KB more for larger inputs. A codec makes its
70
+ compressor on its first `#compress`, so one that only decompresses holds only
71
+ its dictionary. `#size` reports the bytes a codec holds.
72
+
73
+ ```ruby
74
+ codec = Lz4rip::BlockCodec.new(profile: :ratio, dict: dict)
75
+ ```
58
76
 
59
77
  ### Dictionary compression
60
78
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "lz4rip"
3
- version = "0.2.2"
3
+ version = "0.3.0"
4
4
  edition = "2021"
5
5
  build = "build.rs"
6
6
 
@@ -9,7 +9,7 @@ name = "lz4rip"
9
9
  crate-type = ["cdylib", "rlib"]
10
10
 
11
11
  [dependencies]
12
- lz4 = { version = "0.12.7", package = "lz4rip" }
12
+ lz4 = { version = "0.12.9", package = "lz4rip" }
13
13
  rb-sys = "0.9.130"
14
14
 
15
15
  [build-dependencies]
@@ -3,9 +3,12 @@ mod rb;
3
3
  use std::ffi::c_void;
4
4
  use std::io::{Cursor, Read, Write};
5
5
  use std::panic::{catch_unwind, AssertUnwindSafe};
6
+ use std::sync::atomic::{AtomicUsize, Ordering};
6
7
  use std::sync::{Mutex, OnceLock, TryLockError};
7
8
 
8
- use lz4::block::{self, Decompressor, DictCompressor, DictTrainer};
9
+ use lz4::block::{
10
+ self, Decompressor, DictCompressor, DictTrainer, RatioCompressor, RatioDictCompressor,
11
+ };
9
12
  use lz4::frame::{BlockMode, FrameDecoder, FrameDecoderOptions, FrameEncoder, FrameInfo};
10
13
  use rb_sys::{rb_data_type_struct__bindgen_ty_1, rb_data_type_t, size_t, VALUE};
11
14
 
@@ -15,6 +18,9 @@ const COMPRESSOR_HEAP_SIZE: usize = 8192;
15
18
 
16
19
  const LZ4_FRAME_MAGIC: [u8; 4] = [0x04, 0x22, 0x4d, 0x18];
17
20
  const GVL_COMPRESS_THRESHOLD: usize = 256 * 1024;
21
+ /// The ratio profile compresses 128 KiB about as slowly as the fast one
22
+ /// compresses 256 KiB, or slower (Silesia text, binaries, x-ray).
23
+ const GVL_RATIO_COMPRESS_THRESHOLD: usize = 128 * 1024;
18
24
  const GVL_FRAME_DECOMPRESS_THRESHOLD: usize = 256 * 1024;
19
25
 
20
26
  static DECOMPRESS_ERROR: OnceLock<GlobalValue> = OnceLock::new();
@@ -227,24 +233,101 @@ unsafe extern "C" fn lz4rip_block_stream_size(_module: VALUE) -> VALUE {
227
233
 
228
234
  // ---------- BlockCodec ----------
229
235
 
236
+ /// A block codec's compressor state. The fast profile without a dictionary
237
+ /// keeps none: it compresses with `block::compress`.
238
+ enum BlockCompressor {
239
+ Dict(DictCompressor),
240
+ Ratio(RatioCompressor),
241
+ RatioDict(RatioDictCompressor),
242
+ }
243
+
244
+ impl BlockCompressor {
245
+ fn compress(&mut self, input: &[u8]) -> Vec<u8> {
246
+ match self {
247
+ Self::Dict(comp) => comp.compress(input),
248
+ Self::Ratio(comp) => comp.compress(input),
249
+ Self::RatioDict(comp) => comp.compress(input),
250
+ }
251
+ }
252
+
253
+ fn heap_size(&self) -> usize {
254
+ match self {
255
+ Self::Dict(comp) => comp.heap_size(),
256
+ Self::Ratio(comp) => comp.heap_size(),
257
+ Self::RatioDict(comp) => comp.heap_size(),
258
+ }
259
+ }
260
+ }
261
+
262
+ /// A codec's compressor, made by its first `compress`: a codec that only
263
+ /// decompresses, as a receiving connection's does, holds no tables.
264
+ enum CompressorSlot {
265
+ /// The dictionary to make it with, if any.
266
+ Unmade(Option<Vec<u8>>),
267
+ Made(Box<BlockCompressor>),
268
+ }
269
+
270
+ impl CompressorSlot {
271
+ fn get(&mut self, ratio: bool) -> &mut BlockCompressor {
272
+ if let Self::Unmade(dict) = self {
273
+ let compressor = match (dict.take(), ratio) {
274
+ (None, _) => BlockCompressor::Ratio(RatioCompressor::new()),
275
+ (Some(bytes), false) => BlockCompressor::Dict(DictCompressor::new(&bytes)),
276
+ (Some(bytes), true) => BlockCompressor::RatioDict(RatioDictCompressor::new(&bytes)),
277
+ };
278
+ *self = Self::Made(Box::new(compressor));
279
+ }
280
+ match self {
281
+ Self::Made(compressor) => compressor,
282
+ Self::Unmade(_) => unreachable!("made above"),
283
+ }
284
+ }
285
+
286
+ fn heap_size(&self) -> usize {
287
+ match self {
288
+ Self::Unmade(dict) => dict.as_ref().map_or(0, Vec::capacity),
289
+ Self::Made(compressor) => compressor.heap_size(),
290
+ }
291
+ }
292
+ }
293
+
230
294
  struct BlockCodec {
231
- compressor: Option<Mutex<DictCompressor>>,
295
+ /// None for the fast profile without a dictionary, which compresses
296
+ /// with `block::compress`.
297
+ compressor: Option<Mutex<CompressorSlot>>,
232
298
  decompressor: Option<Mutex<Decompressor>>,
233
- dict_len: usize,
299
+ /// The ratio profile, which releases the GVL from a smaller input.
300
+ ratio: bool,
301
+ /// The compressor's heap bytes, kept up to date by `compress` so `#size`
302
+ /// never waits on a compression that released the GVL.
303
+ compressor_heap: AtomicUsize,
304
+ /// The decompressor's heap bytes: its copy of the dictionary.
305
+ decompressor_heap: usize,
306
+ }
307
+
308
+ impl BlockCodec {
309
+ /// Whether compressing `input_len` bytes takes long enough to release
310
+ /// the GVL for.
311
+ fn should_release_compress_gvl(&self, input_len: usize) -> bool {
312
+ if self.ratio {
313
+ input_len >= GVL_RATIO_COMPRESS_THRESHOLD
314
+ } else {
315
+ should_release_compress_gvl(input_len)
316
+ }
317
+ }
234
318
  }
235
319
 
236
- fn block_codec_new_impl(class: VALUE, rb_dict: VALUE) -> RbResult<VALUE> {
237
- let codec = match rb::value_to_option_bytes(rb_dict)? {
238
- None => BlockCodec {
239
- compressor: None,
240
- decompressor: None,
241
- dict_len: 0,
242
- },
243
- Some(bytes) => BlockCodec {
244
- compressor: Some(Mutex::new(DictCompressor::new(&bytes))),
245
- decompressor: Some(Mutex::new(Decompressor::with_dict(&bytes))),
246
- dict_len: bytes.len(),
247
- },
320
+ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE, rb_ratio: VALUE) -> RbResult<VALUE> {
321
+ let ratio = rb_ratio == rb::qtrue();
322
+ let dict = rb::value_to_option_bytes(rb_dict)?;
323
+ let decompressor = dict.as_deref().map(Decompressor::with_dict);
324
+ let compressor = (dict.is_some() || ratio).then_some(CompressorSlot::Unmade(dict));
325
+ let codec = BlockCodec {
326
+ compressor_heap: AtomicUsize::new(compressor.as_ref().map_or(0, CompressorSlot::heap_size)),
327
+ decompressor_heap: decompressor.as_ref().map_or(0, Decompressor::heap_size),
328
+ compressor: compressor.map(Mutex::new),
329
+ decompressor: decompressor.map(Mutex::new),
330
+ ratio,
248
331
  };
249
332
 
250
333
  unsafe { rb::wrap_typed_data(class, Box::new(codec), block_codec_data_type()) }
@@ -252,22 +335,18 @@ fn block_codec_new_impl(class: VALUE, rb_dict: VALUE) -> RbResult<VALUE> {
252
335
 
253
336
  fn block_codec_size_impl(rb_self: VALUE) -> RbResult<VALUE> {
254
337
  let rb_self = unsafe { block_codec_ref(rb_self)? };
255
- if rb_self.compressor.is_some() {
256
- rb::usize_value(COMPRESSOR_HEAP_SIZE + rb_self.dict_len)
257
- } else {
258
- rb::usize_value(0)
259
- }
338
+ rb::usize_value(rb_self.compressor_heap.load(Ordering::Relaxed) + rb_self.decompressor_heap)
260
339
  }
261
340
 
262
341
  fn block_codec_has_dict_impl(rb_self: VALUE) -> RbResult<VALUE> {
263
342
  let rb_self = unsafe { block_codec_ref(rb_self)? };
264
- Ok(rb::bool_value(rb_self.compressor.is_some()))
343
+ Ok(rb::bool_value(rb_self.decompressor.is_some()))
265
344
  }
266
345
 
267
346
  fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE> {
268
347
  let rb_self = unsafe { block_codec_ref(rb_self)? };
269
348
  let mut input = rb::input_bytes(rb_input)?;
270
- let release_gvl = should_release_compress_gvl(input.len());
349
+ let release_gvl = rb_self.should_release_compress_gvl(input.len());
271
350
  input.freeze_for_without_gvl(release_gvl)?;
272
351
 
273
352
  let out = match &rb_self.compressor {
@@ -277,7 +356,15 @@ fn block_codec_compress_impl(rb_self: VALUE, rb_input: VALUE) -> RbResult<VALUE>
277
356
  release_gvl,
278
357
  "BlockCodec compressor",
279
358
  &mut input,
280
- |comp, input| Ok(comp.compress(input)),
359
+ |slot, input| {
360
+ let out = slot.get(rb_self.ratio).compress(input);
361
+ // The first call makes the compressor, and a ratio one makes
362
+ // its larger tables on first use.
363
+ rb_self
364
+ .compressor_heap
365
+ .store(slot.heap_size(), Ordering::Relaxed);
366
+ Ok(out)
367
+ },
281
368
  )?,
282
369
  };
283
370
 
@@ -292,6 +379,17 @@ fn block_codec_decompress_impl(
292
379
  let rb_self = unsafe { block_codec_ref(rb_self)? };
293
380
  let decompressed_size = rb::value_to_usize(decompressed_size)?;
294
381
  let mut compressed = rb::input_bytes(rb_input)?;
382
+ // The size comes from a peer: refuse one the input cannot decode to
383
+ // before the decoder allocates for it.
384
+ if decompressed_size > compressed.len().saturating_mul(LZ4_MAX_EXPANSION) {
385
+ return Err(RubyErr::new(
386
+ decompress_error(),
387
+ format!(
388
+ "lz4 block of {} bytes cannot decode to {decompressed_size} bytes",
389
+ compressed.len()
390
+ ),
391
+ ));
392
+ }
295
393
 
296
394
  let result = match &rb_self.decompressor {
297
395
  None => block::decompress(compressed.as_slice(), decompressed_size),
@@ -313,8 +411,8 @@ fn block_codec_decompress_impl(
313
411
  }
314
412
  }
315
413
 
316
- unsafe extern "C" fn block_codec_new(class: VALUE, rb_dict: VALUE) -> VALUE {
317
- rb::wrap(|| block_codec_new_impl(class, rb_dict))
414
+ unsafe extern "C" fn block_codec_new(class: VALUE, rb_dict: VALUE, rb_ratio: VALUE) -> VALUE {
415
+ rb::wrap(|| block_codec_new_impl(class, rb_dict, rb_ratio))
318
416
  }
319
417
 
320
418
  unsafe extern "C" fn block_codec_size(rb_self: VALUE) -> VALUE {
@@ -488,6 +586,10 @@ unsafe extern "C" fn frame_codec_id(rb_self: VALUE) -> VALUE {
488
586
 
489
587
  const LZ4_MAX_DISTANCE: usize = 65535;
490
588
 
589
+ /// The most bytes one byte of an LZ4 block decodes to: a match length
590
+ /// extension byte adds up to 255.
591
+ const LZ4_MAX_EXPANSION: usize = 255;
592
+
491
593
  struct RbDictTrainer {
492
594
  inner: Mutex<Option<DictTrainer>>,
493
595
  max_dict_size: usize,
@@ -641,7 +743,7 @@ fn init() -> RbResult<()> {
641
743
  let codec_class = unsafe { rb::define_class_under(module, c"BlockCodec", rb_sys::rb_cObject)? };
642
744
  unsafe {
643
745
  rb::undef_alloc_func(codec_class)?;
644
- rb::define_singleton_method_1(codec_class, c"_native_new", block_codec_new)?;
746
+ rb::define_singleton_method_2(codec_class, c"_native_new", block_codec_new)?;
645
747
  rb::define_method_0(codec_class, c"size", block_codec_size)?;
646
748
  rb::define_method_0(codec_class, c"has_dict?", block_codec_has_dict)?;
647
749
  rb::define_method_1(codec_class, c"compress", block_codec_compress)?;
@@ -8,14 +8,10 @@ module Lz4rip
8
8
  # `BlockCodec` keeps mutable native scratch state and is intended to be used
9
9
  # per Ractor.
10
10
  #
11
- # @!method self.new(dict: nil)
12
- # Create a block codec.
13
- # @param dict [Dictionary, String, nil] optional LZ4 dictionary
14
- # @return [BlockCodec]
15
- #
16
- # @!method self._native_new(dict)
11
+ # @!method self._native_new(dict, ratio)
17
12
  # Native constructor used by `.new`.
18
13
  # @param dict [String, nil] dictionary bytes
14
+ # @param ratio [Boolean] use the ratio profile
19
15
  # @return [BlockCodec]
20
16
  #
21
17
  # @!method compress(bytes)
@@ -23,13 +19,6 @@ module Lz4rip
23
19
  # @param bytes [String] uncompressed bytes
24
20
  # @return [String]
25
21
  #
26
- # @!method decompress(bytes, decompressed_size:)
27
- # Decompress a raw LZ4 block.
28
- # @param bytes [String] compressed LZ4 block
29
- # @param decompressed_size [Integer] original byte size
30
- # @return [String]
31
- # @raise [DecompressError]
32
- #
33
22
  # @!method _decompress(bytes, decompressed_size)
34
23
  # Native decompression entry used by #decompress.
35
24
  # @param bytes [String] compressed LZ4 block
@@ -41,15 +30,56 @@ module Lz4rip
41
30
  # @return [Boolean]
42
31
  #
43
32
  # @!method size
44
- # @return [Integer] internal state size in bytes
33
+ # Bytes the codec holds natively: its compressor tables made so far and
34
+ # its copies of the dictionary.
35
+ # @return [Integer]
45
36
  class BlockCodec
46
- def self.new(dict: nil)
47
- _native_new(Dictionary === dict ? dict.bytes : dict)
37
+ PROFILES = %i[fast ratio].freeze
38
+
39
+
40
+ # Create a block codec.
41
+ #
42
+ # The `:ratio` profile compresses to smaller output, more slowly, and
43
+ # decodes with any LZ4 decoder. It holds an 8 KB table, plus 64 KB from
44
+ # its first input above 4 KiB. With a dictionary it hashes the dictionary
45
+ # once and holds 16 KB of tables while input and dictionary stay within
46
+ # 4 KiB, 64 KB more for larger inputs. Either profile makes its compressor
47
+ # on the first `#compress`, so a codec that only decompresses holds only
48
+ # its dictionary.
49
+ #
50
+ # @param dict [Dictionary, String, nil] optional LZ4 dictionary
51
+ # @param profile [Symbol] `:fast` or `:ratio`
52
+ # @return [BlockCodec]
53
+ # @raise [ArgumentError] on an unknown profile
54
+ def self.new(dict: nil, profile: :fast)
55
+ unless PROFILES.include?(profile)
56
+ raise ArgumentError, "profile must be :fast or :ratio, got #{profile.inspect}"
57
+ end
58
+
59
+ _native_new(Dictionary === dict ? dict.bytes : dict, profile == :ratio)
48
60
  end
49
61
 
50
62
 
51
- def decompress(bytes, decompressed_size:)
63
+ # Decompress a raw LZ4 block.
64
+ #
65
+ # `decompressed_size` is the original size, often declared by a peer. A
66
+ # size the block cannot decode to (more than 255 times its length), or
67
+ # above `max_decompressed_size`, raises before anything is allocated for
68
+ # it.
69
+ #
70
+ # @param bytes [String] compressed LZ4 block
71
+ # @param decompressed_size [Integer] original byte size
72
+ # @param max_decompressed_size [Integer, nil] largest size to accept
73
+ # @return [String]
74
+ # @raise [DecompressError]
75
+ def decompress(bytes, decompressed_size:, max_decompressed_size: nil)
76
+ if max_decompressed_size && decompressed_size > max_decompressed_size
77
+ raise DecompressError,
78
+ "decompressed size #{decompressed_size} exceeds max_decompressed_size #{max_decompressed_size}"
79
+ end
80
+
52
81
  _decompress(bytes, decompressed_size)
53
82
  end
83
+
54
84
  end
55
85
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Lz4rip
4
- VERSION = "0.2.2"
4
+ VERSION = "0.3.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lz4rip
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.2
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Patrik Wenger