ziperu 0.2.2 → 0.2.3

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: c150e0c8fc9674dbd9d76291707efdfab0904b3438ebe0c53c3f790db4fd8c81
4
- data.tar.gz: d149abb6aacaddc8f2992462225f5e16aa2ff5e32247d7488312c2e3a726acc7
3
+ metadata.gz: b5e977083967283ed8594aa131fccbbea2b8b766458c6e6fa8a3006356af57e1
4
+ data.tar.gz: 62d85e136fc36d7618c8b58aa2fb8ed910f403a994c9a6f1e06a1e812cd13310
5
5
  SHA512:
6
- metadata.gz: 2858d1912c604e90132efa21fc26cd73fcca7df0254b1a63d0183e2f4c41d313ce723bd3a4d5a56e358f9426ba9d3596279ba5fa9a302d459dba04f9fad2cb95
7
- data.tar.gz: eaaf2c7c5a217e17d705d5d72acef3d1af2631f77a9750207133883c92a78a84a83945a420e7e273b9805db43c0985324ee52bc419ee580e50e91a300a38cba5
6
+ metadata.gz: d57553d22be136d860dda97bade7f0a8bffe3ea28ab0f0befc2b7d2c14ef674dc219522bd02884bb62e556f5c77f93374ed3a25dd7cb2af8b54136616a2f96e1
7
+ data.tar.gz: 293a8363e37ac330bdf5bfef408d7b572f35d06254188a7e6795ce5da1cf64a01f18b45cc5434cf9a9c524b91d249599c3220fe67adbe06afafd80939cca6763
data/CHANGELOG.md CHANGED
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3 (2026-11-11)
4
+
5
+ Faster (Windows, against 0.2.2):
6
+
7
+ - Writing many small entries to a file: the header each entry patches
8
+ at its end is now still in the write buffer, so it costs no system
9
+ call. 1000 entries of 8 KB: 46 to 32 ms; 10,000 tiny entries: 315 to
10
+ 180 ms. A seekable Ruby IO (`write_buffer`) gets the same, in 64 KB
11
+ chunks.
12
+ - `File#get_output_stream` keeps an entry in memory until the commit
13
+ rather than opening a tempfile for each one; past 8 MB held between
14
+ an archive's pending entries, the rest go to tempfiles as before.
15
+ 1000 entries and a commit: 981 to 58 ms.
16
+ - `Entry#time` reads the modification time from the central directory,
17
+ as rubyzip does, rather than the entry's local header; the access and
18
+ creation times still come from there. Listing names and times of
19
+ 10,000 entries: 153 to 78 ms.
20
+ - Appending to a large archive no longer reads every entry's local
21
+ header, reads the central directory through a buffer, and keeps the
22
+ entries it had after the commit (same objects) rather than building
23
+ them all again. One entry added to a 10,000-entry archive: 337 to
24
+ 98 ms.
25
+ - `InputStream#get_next_entry` opens the entry's data when it is first
26
+ read, so walking only the names reads no local header: 103 to 40 ms
27
+ for 10,000 entries.
28
+ - Reading a whole entry of 64 KB or more (`File#read`, and
29
+ `get_input_stream`'s `read` of the rest of one, which is what roo and
30
+ caxlsx do) decompresses straight into the returned String: no second
31
+ copy, and half the peak memory. 64 MB: 58 to 17 ms; a 64 MB Stored
32
+ entry: 62 to 18 ms. An interrupted read rescued still loses nothing.
33
+ - Files added by path (`add`, `add_stored`, `replace`) are read by the
34
+ native core at commit instead of through Ruby: a 64 MB `add_stored`
35
+ and commit, 141 to 34 ms.
36
+
37
+ Fixed:
38
+
39
+ - Native work could not be interrupted, and kept every other thread
40
+ waiting, whenever Ruby declined to release the GVL for it because an
41
+ interrupt flag was set (often just its thread-scheduling timer): it
42
+ then ran to the end with the GVL held. Now a pending `Thread#raise`,
43
+ `Timeout` or Ctrl-C stops it at once, and otherwise the GVL is
44
+ released on another try.
45
+ - `get_input_stream.read` of an entry whose central record declares it
46
+ empty but gives a CRC of some data returned `""`; it raises, as
47
+ `File#read` does.
48
+
3
49
  ## 0.2.2 (2026-11-11)
4
50
 
5
51
  Fixed:
data/Cargo.lock CHANGED
@@ -879,7 +879,7 @@ dependencies = [
879
879
 
880
880
  [[package]]
881
881
  name = "ziperu"
882
- version = "0.2.2"
882
+ version = "0.2.3"
883
883
  dependencies = [
884
884
  "crc32fast",
885
885
  "flate2",
data/README.md CHANGED
@@ -19,6 +19,19 @@ the [`zip`](https://github.com/zip-rs/zip2) crate through
19
19
  [Magnus](https://github.com/matsadler/magnus). `require "zip"` aliases
20
20
  `Zip = Ziperu`, so existing code runs unchanged.
21
21
 
22
+ On GitHub's Linux runners (Ruby 3.4, median of 5), against rubyzip 3.7.0:
23
+
24
+ | scenario | rubyzip | ziperu | speedup |
25
+ |---|---:|---:|---:|
26
+ | read 1000 x 8 KB deflated entries | 80 ms | 14 ms | 5.8x |
27
+ | open and list 10000 entries | 135 ms | 58 ms | 2.3x |
28
+ | deflate one 64 MB entry | 188 ms | 77 ms | 2.4x |
29
+ | extract_all 1000 entries | 169 ms | 80 ms | 2.1x |
30
+ | add 1000 files from disk (`threads: 4`) | 214 ms | 60 ms | 3.6x |
31
+
32
+ macOS and Windows, every scenario, and which calls release the GVL (what
33
+ Puma users ask about) are in [docs/benchmarks.md](docs/benchmarks.md).
34
+
22
35
  - **Precompiled** for Linux (glibc and musl), macOS and Windows, Ruby 3.1 to 4.0. No toolchain, no runtime dependencies.
23
36
  - **Fast**: entries inflate and deflate in Rust with the GVL released, the central directory is parsed once, unchanged entries are copied byte for byte on commit, and a commit that only adds entries appends them in place.
24
37
  - **Reads everything**: Stored, Deflate, Deflate64, bzip2, zstd, LZMA, XZ, PPMd and the PKZIP 1.x methods; AES and ZipCrypto. Writes Deflate, Stored, bzip2, zstd, XZ, PPMd, AES and ZipCrypto.
@@ -40,25 +53,8 @@ Or on its own:
40
53
  gem install ziperu
41
54
  ```
42
55
 
43
- Bundler and `gem install` pick the precompiled gem for the platform
44
- (`x86_64-linux-gnu`, `x86_64-linux-musl`, `aarch64-linux-gnu`,
45
- `aarch64-linux-musl`, `arm-linux-musl`, `x86_64-darwin`, `arm64-darwin`,
46
- `x64-mingw-ucrt`, `aarch64-mingw-ucrt`), each holding the extension for
47
- Ruby 3.1 through 4.0. The glibc gems need RubyGems 3.3.22 or later (Ruby
48
- 3.1.4 ships it); the musl gems need `libgcc` (`apk add libgcc`, already in
49
- the `ruby:3.2-alpine` and later images). Anywhere else the source gem
50
- builds with Rust 1.88+.
51
-
52
- Which Rubies, and how firmly:
53
-
54
- | Ruby | Status |
55
- | --- | --- |
56
- | 3.3, 3.4, 4.0 | Supported. The suite runs on Linux, macOS and Windows on every change; binaries ship. |
57
- | 3.1, 3.2 | Best effort. Past end of life upstream; binaries still ship and the suite runs on 3.1, but a fix that needs a newer Ruby may drop them, in a minor release and with a changelog entry. |
58
- | ruby-head | Watched. A non-blocking CI job runs the suite nightly, so a new Ruby gets binaries the day it is released. |
59
-
60
- JRuby and TruffleRuby are not supported: the core is a native extension
61
- against the CRuby API. rubyzip remains the library for those.
56
+ Precompiled gems ship for Linux, macOS and Windows; see
57
+ [Platforms](#platforms) for the details.
62
58
 
63
59
  ## Quick start
64
60
 
@@ -284,18 +280,14 @@ dump, reads entries in large chunks, copies unchanged entries byte for
284
280
  byte on `commit`, and releases the GVL while inflating from a file or
285
281
  String buffer and while deflating to a file, so other Ruby threads keep running.
286
282
 
287
- On GitHub's Linux runners (Ruby 3.4, median of 5), against rubyzip 3.7.0:
283
+ ## Platforms
288
284
 
289
- | scenario | rubyzip | ziperu | speedup |
290
- |---|---:|---:|---:|
291
- | read 1000 x 8 KB deflated entries | 80 ms | 14 ms | 5.8x |
292
- | open and list 10000 entries | 135 ms | 58 ms | 2.3x |
293
- | deflate one 64 MB entry | 188 ms | 77 ms | 2.4x |
294
- | extract_all 1000 entries | 169 ms | 80 ms | 2.1x |
295
- | add 1000 files from disk (`threads: 4`) | 214 ms | 60 ms | 3.6x |
296
-
297
- macOS and Windows, every scenario, and which calls release the GVL (what
298
- Puma users ask about) are in [docs/benchmarks.md](docs/benchmarks.md).
285
+ - **Ruby 3.3 to 4.0** are supported and tested on Linux, macOS and Windows.
286
+ 3.1 and 3.2 still get binaries, best effort.
287
+ - **Precompiled** for x86_64 and aarch64 Linux (glibc and musl; musl needs
288
+ `libgcc`), Intel and Apple Silicon macOS, and x64 and arm64 Windows.
289
+ Elsewhere the source gem builds with Rust 1.88+.
290
+ - **CRuby only**: on JRuby or TruffleRuby, use rubyzip.
299
291
 
300
292
  ## Development
301
293
 
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ziperu"
3
- version = "0.2.2"
3
+ version = "0.2.3"
4
4
  edition = "2021"
5
5
  publish = false
6
6
  rust-version = "1.88"
@@ -19,7 +19,7 @@ use zip::ZipArchive;
19
19
 
20
20
  use crate::errors::{busy_error, header_error, read_error, zip_read_error, IntoRuby};
21
21
  use crate::gvl::{maybe_without_gvl, Cancellable};
22
- use crate::rb::bytes_of;
22
+ use crate::rb::{bytes_of, read_into_string, size_believable};
23
23
  use crate::reader::{open_local_entry, EntryInfo, EntryReader};
24
24
  use crate::source::Source;
25
25
 
@@ -422,7 +422,19 @@ impl Archive {
422
422
  // A clone (the central directory is shared behind an Arc) so the
423
423
  // borrow is released before the GVL is.
424
424
  let mut archive = rb_self.archive(ruby)?.clone();
425
+ let data_end = archive.central_directory_start();
425
426
  let mut entry = archive.by_index(index).rb(ruby)?;
427
+ let size = entry.size();
428
+ let method = compression_code(entry.compression());
429
+ if !entry.encrypted() && size_believable(method, size, entry.compressed_size(), data_end) {
430
+ return read_into_string(
431
+ ruby,
432
+ rb_self.needs_gvl,
433
+ size as usize,
434
+ &mut Cancellable(&mut entry),
435
+ )
436
+ .map_err(|e| read_error(ruby, e));
437
+ }
426
438
  // A hint only: the declared size is untrusted and may be a lie.
427
439
  let mut buf = Vec::with_capacity(entry.size().min(CAPACITY_HINT_MAX) as usize);
428
440
  maybe_without_gvl(rb_self.needs_gvl, || {
@@ -227,6 +227,9 @@ pub fn read_error(ruby: &Ruby, err: io::Error) -> Error {
227
227
  /// caller should see. Should there be none, a plain `Ziperu::Error`.
228
228
  pub fn interrupted(ruby: &Ruby) -> Error {
229
229
  use magnus::rb_sys::AsRawValue;
230
+ if let Some(raised) = crate::gvl::take_raised() {
231
+ return raised;
232
+ }
230
233
  let nil = ruby.qnil().as_raw();
231
234
  // SAFETY: called with the GVL held; `protect` turns the exception that
232
235
  // `rb_thread_check_ints` raises into an `Err` rather than a longjmp
@@ -156,21 +156,42 @@ pub fn without_gvl<F: FnOnce() -> R, R>(f: F) -> R {
156
156
  // `Cancelled` error our loops return gets the interrupt raised the
157
157
  // safe way (`errors::interrupted`), or Ruby raises it at its next
158
158
  // check once we are back in Ruby code.
159
- unsafe {
160
- rb_sys::rb_thread_call_without_gvl2(
161
- Some(trampoline_for(&call)),
162
- &mut call as *mut _ as *mut c_void,
163
- Some(unblock),
164
- Arc::as_ptr(&flag) as *mut c_void,
165
- );
166
- }
167
- if let Some(run) = call.f.take() {
168
- // Ruby returned without running `f`: some interrupt flag was set,
169
- // which includes its routine thread-scheduling timer, not only a
170
- // `Thread#raise` or a signal. Run `f` here with the GVL held, as
171
- // if it had to keep it; a real interrupt is raised once we are
172
- // back in Ruby code.
173
- return run();
159
+ // SAFETY (each call): `call` and `flag` outlive it, and the unblock
160
+ // function only stores to the flag.
161
+ let mut refusals = 0;
162
+ loop {
163
+ unsafe {
164
+ rb_sys::rb_thread_call_without_gvl2(
165
+ Some(trampoline_for(&call)),
166
+ &mut call as *mut _ as *mut c_void,
167
+ Some(unblock),
168
+ Arc::as_ptr(&flag) as *mut c_void,
169
+ );
170
+ }
171
+ let Some(run) = call.f.take() else { break };
172
+ // Ruby returned without running `f`: an interrupt flag was set.
173
+ // Often that is only its routine thread-scheduling timer; running
174
+ // `f` with the GVL held then would make it impossible to
175
+ // interrupt and keep every other thread waiting. So: with an
176
+ // exception queued for this thread (`Thread#raise`, `Timeout`,
177
+ // Ctrl-C), `f` runs already cancelled, stops at its first check,
178
+ // and the exception is raised the usual way (`errors::interrupted`,
179
+ // or Ruby's next check). Otherwise Ruby handles what is pending and
180
+ // the GVL is released on another try.
181
+ if exception_pending() {
182
+ flag.store(true, Ordering::Release);
183
+ return run();
184
+ }
185
+ refusals += 1;
186
+ if refusals > 3 {
187
+ // Refused again and again: run it here, as it always could.
188
+ return run();
189
+ }
190
+ if !handle_routine_interrupts() {
191
+ flag.store(true, Ordering::Release);
192
+ return run();
193
+ }
194
+ call.f = Some(run);
174
195
  }
175
196
  match call.out.take().expect("trampoline ran") {
176
197
  Ok(r) => r,
@@ -178,6 +199,56 @@ pub fn without_gvl<F: FnOnce() -> R, R>(f: F) -> R {
178
199
  }
179
200
  }
180
201
 
202
+ /// Whether an exception is queued for this thread, waiting for its next
203
+ /// interrupt check: `Thread#pending_interrupt?`, which leaves it queued.
204
+ fn exception_pending() -> bool {
205
+ use magnus::prelude::*;
206
+ let Ok(ruby) = magnus::Ruby::get() else {
207
+ return false;
208
+ };
209
+ ruby.thread_current()
210
+ .funcall::<_, _, bool>("pending_interrupt?", ())
211
+ .unwrap_or(false)
212
+ }
213
+
214
+ /// Lets Ruby handle the interrupts it has pending for this thread, none of
215
+ /// them an exception queued for it (`exception_pending` said so): thread
216
+ /// scheduling, finalizers, signal traps. False if one of those raised
217
+ /// after all (a trap handler, say); that exception is kept for
218
+ /// `errors::interrupted` to raise.
219
+ fn handle_routine_interrupts() -> bool {
220
+ let Ok(ruby) = magnus::Ruby::get() else {
221
+ return false;
222
+ };
223
+ use magnus::rb_sys::AsRawValue;
224
+ let nil = ruby.qnil().as_raw();
225
+ // SAFETY: the GVL is held; `protect` turns what `rb_thread_check_ints`
226
+ // raises into an `Err` rather than a longjmp through Rust frames.
227
+ let result = magnus::rb_sys::protect(|| {
228
+ unsafe { rb_sys::rb_thread_check_ints() };
229
+ nil
230
+ });
231
+ match result {
232
+ Ok(_) => true,
233
+ Err(e) => {
234
+ RAISED.with(|r| *r.borrow_mut() = Some(e));
235
+ false
236
+ }
237
+ }
238
+ }
239
+
240
+ thread_local! {
241
+ /// An exception that handling routine interrupts raised, for
242
+ /// `errors::interrupted` to raise in its place. It is the thread's
243
+ /// `$!` meanwhile, which keeps it alive.
244
+ static RAISED: RefCell<Option<magnus::Error>> = const { RefCell::new(None) };
245
+ }
246
+
247
+ /// The exception `handle_routine_interrupts` caught, if any; taken.
248
+ pub fn take_raised() -> Option<magnus::Error> {
249
+ RAISED.with(|r| r.borrow_mut().take())
250
+ }
251
+
181
252
  /// `without_gvl` unless the work needs the interpreter (a Ruby-backed
182
253
  /// source), in which case `f` simply runs inline.
183
254
  pub fn maybe_without_gvl<F: FnOnce() -> R, R>(needs_gvl: bool, f: F) -> R {
@@ -93,6 +93,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
93
93
  writer.define_method("add_directory", method!(writer::Writer::add_directory, 2))?;
94
94
  writer.define_method("add_symlink", method!(writer::Writer::add_symlink, 3))?;
95
95
  writer.define_method("write", method!(writer::Writer::write, 1))?;
96
+ writer.define_method("write_file", method!(writer::Writer::write_file, 1))?;
96
97
  writer.define_method("raw_copy", method!(writer::Writer::raw_copy, 4))?;
97
98
  writer.define_method("copy_zipcrypto", method!(writer::Writer::copy_zipcrypto, 4))?;
98
99
  writer.define_method("comment=", method!(writer::Writer::set_comment, 1))?;
data/ext/ziperu/src/rb.rs CHANGED
@@ -1,5 +1,7 @@
1
1
  //! Small helpers for crossing between Ruby values and Rust ones.
2
2
 
3
+ use std::io;
4
+
3
5
  use magnus::{prelude::*, Error, RHash, RString, Ruby, TryConvert};
4
6
 
5
7
  /// A copy of the String's bytes. Ruby strings can move (compaction) or be
@@ -19,3 +21,115 @@ pub(crate) fn field<T: TryConvert>(ruby: &Ruby, h: RHash, key: &str) -> Result<O
19
21
  .map(T::try_convert)
20
22
  .transpose()
21
23
  }
24
+
25
+ /// Entries at least this large are read straight into their String's
26
+ /// buffer (see `fill_new_string`); below it a copy costs nothing.
27
+ pub(crate) const DIRECT_READ_MIN: u64 = 64 * 1024;
28
+
29
+ /// How much of the buffer one read fills.
30
+ const DIRECT_READ_STEP: usize = 1 << 20;
31
+
32
+ /// The largest declared size read straight into a String of that size.
33
+ const DIRECT_READ_MAX: u64 = 1 << 30;
34
+
35
+ /// Whether an entry's declared `size` can be allocated before its data is
36
+ /// read. The declaration is untrusted, so it must be backed by compressed
37
+ /// bytes that are really there (`compressed`, at most `data_end`, where
38
+ /// the central directory starts) and by a ratio the method can reach:
39
+ /// Stored is 1:1, Deflate at most 1032:1, and the other methods go the
40
+ /// long way. A lie then costs no more memory than the truth could.
41
+ pub(crate) fn size_believable(method: u16, size: u64, compressed: u64, data_end: u64) -> bool {
42
+ let ratio_ok = match method {
43
+ 0 => size == compressed,
44
+ 8 => size <= compressed.saturating_mul(1032),
45
+ _ => false,
46
+ };
47
+ ratio_ok && compressed <= data_end && (DIRECT_READ_MIN..=DIRECT_READ_MAX).contains(&size)
48
+ }
49
+
50
+ /// Reads up to `size` bytes from `reader` straight into a new binary
51
+ /// String's buffer rather than into a Vec copied over afterwards, then,
52
+ /// if all `size` came, runs `tail` on the reader (still without the GVL).
53
+ /// The String is returned in every case, holding what was read: on an
54
+ /// error, what came before it.
55
+ ///
56
+ /// The String stays alive and in place while the GVL is released: it is
57
+ /// on this thread's stack, which the GC scans conservatively (pinning
58
+ /// what it finds), and at `DIRECT_READ_MIN` bytes or more its buffer is a
59
+ /// heap allocation that neither compaction nor anything else moves while
60
+ /// no Ruby code holds the String. Zeroing and reading go a step at a
61
+ /// time, so an interrupt (which `reader` checks for) is seen between
62
+ /// steps rather than after the whole entry.
63
+ pub(crate) fn fill_new_string<R: io::Read, T>(
64
+ ruby: &Ruby,
65
+ needs_gvl: bool,
66
+ size: usize,
67
+ reader: &mut R,
68
+ tail: impl FnOnce(&mut R) -> io::Result<T>,
69
+ ) -> (RString, io::Result<(usize, Option<T>)>) {
70
+ use magnus::rb_sys::AsRawValue;
71
+
72
+ let out = ruby.str_buf_new(size);
73
+ if out.capacity() < size {
74
+ return (out, Err(io::Error::other("could not allocate the String")));
75
+ }
76
+ // The String is new and unshared, with room for `size` bytes.
77
+ let base = unsafe { rb_sys::RSTRING_PTR(out.as_raw()) as usize };
78
+ let mut filled = 0usize;
79
+ let result = crate::gvl::maybe_without_gvl(needs_gvl, || -> io::Result<Option<T>> {
80
+ while filled < size {
81
+ let step = (size - filled).min(DIRECT_READ_STEP);
82
+ // SAFETY: bytes `filled..filled + step` lie within the
83
+ // String's buffer and are zeroed before a slice is made of
84
+ // them.
85
+ let dst = unsafe {
86
+ let ptr = (base as *mut u8).add(filled);
87
+ std::ptr::write_bytes(ptr, 0, step);
88
+ std::slice::from_raw_parts_mut(ptr, step)
89
+ };
90
+ let mut got = 0;
91
+ while got < step {
92
+ match reader.read(&mut dst[got..]) {
93
+ Ok(0) => {
94
+ filled += got;
95
+ return Ok(None);
96
+ }
97
+ Ok(k) => got += k,
98
+ Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
99
+ Err(e) => {
100
+ filled += got;
101
+ return Err(e);
102
+ }
103
+ }
104
+ }
105
+ filled += step;
106
+ }
107
+ tail(reader).map(Some)
108
+ });
109
+ let filled = std::hint::black_box(filled);
110
+ // SAFETY: `filled` bytes of the buffer were written; the length never
111
+ // exceeds the capacity.
112
+ unsafe { rb_sys::rb_str_set_len(out.as_raw(), filled as _) };
113
+ (std::hint::black_box(out), result.map(|t| (filled, t)))
114
+ }
115
+
116
+ /// Reads `reader` to its end into a new binary String, the first `size`
117
+ /// bytes (the declared size) straight into its buffer (`fill_new_string`)
118
+ /// and anything past them appended once the GVL is back.
119
+ pub(crate) fn read_into_string<R: io::Read>(
120
+ ruby: &Ruby,
121
+ needs_gvl: bool,
122
+ size: usize,
123
+ reader: &mut R,
124
+ ) -> io::Result<RString> {
125
+ let (out, result) = fill_new_string(ruby, needs_gvl, size, reader, |r| {
126
+ let mut rest = Vec::new();
127
+ r.read_to_end(&mut rest).map(|_| rest)
128
+ });
129
+ if let (_, Some(rest)) = result? {
130
+ if !rest.is_empty() {
131
+ out.cat(&rest);
132
+ }
133
+ }
134
+ Ok(out)
135
+ }
@@ -192,6 +192,9 @@ struct Inner {
192
192
  /// position of the next byte, and of the end of the data. A read
193
193
  /// this way checks no CRC (only reading from the start can).
194
194
  raw: Option<(u64, u64)>,
195
+ /// Whether a read of the rest of the entry may go straight into a
196
+ /// String of the declared size (`rb::size_believable`).
197
+ direct: bool,
195
198
  }
196
199
 
197
200
  #[derive(TypedData)]
@@ -337,12 +340,22 @@ impl EntryReader {
337
340
  needs_gvl: bool,
338
341
  io: Option<Opaque<Value>>,
339
342
  ) -> Result<Self, Error> {
343
+ let direct = enforce_size
344
+ && password.is_none()
345
+ && info.method.is_some_and(|m| {
346
+ crate::rb::size_believable(
347
+ m,
348
+ info.size,
349
+ info.compressed_size,
350
+ archive.central_directory_start(),
351
+ )
352
+ });
340
353
  let entry = OwnedEntry::open(archive, enforce_size, password, &info).rb(ruby)?;
341
354
  let size = enforce_size.then_some(info.size);
342
- // Nothing to read only when there is no data either: an entry
343
- // declared empty but holding data is a lie the crate's size check
344
- // should catch.
345
- let finished = size == Some(0) && info.compressed_size == 0;
355
+ // Nothing to read only when there is no data either, and the CRC
356
+ // is that of no data: an entry declared empty but holding data, or
357
+ // with another CRC, is a lie the crate's checks should catch.
358
+ let finished = size == Some(0) && info.compressed_size == 0 && info.crc32 == 0;
346
359
  Ok(Self {
347
360
  inner: RefCell::new(Inner {
348
361
  entry: Some(entry),
@@ -356,6 +369,7 @@ impl EntryReader {
356
369
  raw_source: None,
357
370
  data_start: None,
358
371
  raw: None,
372
+ direct,
359
373
  }),
360
374
  io,
361
375
  })
@@ -431,6 +445,9 @@ impl EntryReader {
431
445
  inner.consumed += want;
432
446
  return Ok(Some(ruby.str_from_slice(&buf)));
433
447
  }
448
+ if buf.is_empty() && probe && inner.direct && want >= crate::rb::DIRECT_READ_MIN {
449
+ return Self::read_direct(ruby, &mut inner, want as usize);
450
+ }
434
451
  let Inner {
435
452
  entry, finished, ..
436
453
  } = &mut *inner;
@@ -484,6 +501,52 @@ impl EntryReader {
484
501
  Ok(Some(ruby.str_from_slice(&buf)))
485
502
  }
486
503
 
504
+ /// The rest of the entry, `want` bytes to its declared size, read
505
+ /// straight into the String handed back (see `rb::fill_new_string`),
506
+ /// with the same outcomes as the chunked way: an interrupt leaves what
507
+ /// was read pending for the next read, any other error poisons the
508
+ /// reader, and data past the declared size is a size-limit error.
509
+ fn read_direct(ruby: &Ruby, inner: &mut Inner, want: usize) -> Result<Option<RString>, Error> {
510
+ let needs_gvl = inner.needs_gvl;
511
+ if inner.finished {
512
+ return Ok(None);
513
+ }
514
+ let Some(file) = inner.entry.as_mut().and_then(|e| e.file.as_mut()) else {
515
+ return Ok(None);
516
+ };
517
+ let (out, result) = crate::rb::fill_new_string(
518
+ ruby,
519
+ needs_gvl,
520
+ want,
521
+ &mut crate::gvl::Cancellable(file),
522
+ |r| {
523
+ let mut extra = [0u8; 1];
524
+ r.read(&mut extra).map(|n| n != 0)
525
+ },
526
+ );
527
+ match result {
528
+ Ok((filled, oversize)) => {
529
+ inner.consumed += filled as u64;
530
+ if filled < want || oversize.is_some() {
531
+ inner.finished = true;
532
+ }
533
+ if oversize == Some(true) {
534
+ return Err(size_limit_error(ruby));
535
+ }
536
+ Ok((filled > 0).then_some(out))
537
+ }
538
+ Err(e) => {
539
+ if crate::gvl::is_cancelled(&e) {
540
+ // SAFETY: copied out at once, with the GVL held.
541
+ inner.pending = unsafe { out.as_slice() }.to_vec();
542
+ } else {
543
+ inner.failed = Some(e.to_string());
544
+ }
545
+ Err(read_error(ruby, e))
546
+ }
547
+ }
548
+ }
549
+
487
550
  pub fn rewind(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
488
551
  let mut inner = rb_self.inner(ruby)?;
489
552
  let Inner {
@@ -504,7 +567,7 @@ impl EntryReader {
504
567
  return Err(zip_error(ruby, e));
505
568
  }
506
569
  *consumed = 0;
507
- *finished = *size == Some(0) && info.compressed_size == 0;
570
+ *finished = *size == Some(0) && info.compressed_size == 0 && info.crc32 == 0;
508
571
  inner.pending.clear();
509
572
  inner.failed = None;
510
573
  inner.raw = None;