A drop-in replacement for rubyzip with a Rust core.
Same Ziperu::File / Entry / InputStream / OutputStream API, backed by
the zip crate through
Magnus. require "zip" aliases
Zip = Ziperu, so existing code runs unchanged.
It also reads, extracts and writes tar archives (.tar, .tar.gz,
.tar.zst, .tar.xz, .tar.bz2), extracting under the same safety
rules, so one gem unpacks whatever was uploaded:
Ziperu.extract(upload, "out").
Measured with ziperu 0.2.3 against rubyzip 3.7.0 on GitHub's Linux runners (Ruby 3.4, median of 5 runs):
| scenario | rubyzip | ziperu | speedup |
|---|---|---|---|
| read 1000 x 8 KB deflated entries | 110 ms | 18 ms | 6.1x |
| inflate one 64 MB entry | 112 ms | 38 ms | 3.0x |
| open and list 10000 entries | 184 ms | 75 ms | 2.5x |
| deflate one 64 MB entry | 323 ms | 101 ms | 3.2x |
get_output_stream 1000 entries and commit |
310 ms | 84 ms | 3.7x |
| append one entry to a 10000-entry archive | 1.16 s | 148 ms | 7.8x |
add 1000 files from disk (threads: 4) |
348 ms | 89 ms | 3.9x |
Results for macOS and Windows, and the rest of the scenarios, are in docs/benchmarks.md. It also lists which calls release the GVL, so other threads (other Puma requests, say) keep running.
- Precompiled for Linux (glibc and musl), macOS and Windows, on Ruby 3.3 to 4.0, with binaries for 3.1 and 3.2 as well. No toolchain, no runtime dependencies.
- 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.
- 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.
- Tar as well:
Ziperu::Tarreads and extracts v7, ustar, GNU and PAX archives, plain or compressed with gzip, zstd, xz or bzip2, from a path or any IO including a pipe, and writes them too. See docs/tar.md. - Safe by default: no entry inflates past its declared size, extraction skips names that resolve outside the destination and never writes through a link already on disk, symlinks are opt-in, and limits on entry count, entry size, total size and compression ratio can be set up front. SECURITY.md has the details.
- Friendlier than rubyzip where it costs nothing: a password on the archive (
File.open(path, password: ...)),addfrom an IO, Pathname arguments,File#verify, progress callbacks, and errors that fail at the call site. - Checked against the field: rubyzip's own test suite, differential fuzzing against Python's
zipfileand rubyzip, interoperability runs with Info-ZIP, 7-Zip, Python, GNU tar and bsdtar, and the test suites of gems built on rubyzip (roo, caxlsx, rubyXL, docx, write_xlsx, sablon, gepub) run with ziperu in its place.
In the Gemfile, in place of rubyzip:
gem "ziperu"Or on its own:
gem install ziperurequire "ziperu" # or require "zip" for the Zip alias
Ziperu::File.open("archive.zip") do |zf|
zf.each { |entry| puts "#{entry.name} (#{entry.size} bytes)" }
puts zf.read("README.txt")
zf.extract_all("out/")
end
Ziperu::File.open("new.zip", create: true) do |zf|
zf.add("report.pdf", "tmp/report.pdf")
zf.get_output_stream("notes.txt") { |io| io.puts "written at #{Time.now}" }
endStreaming, passwords, limits and the rest are in the cookbook below.
Zip a directory, unzip into one:
Ziperu::File.add_recursive("site.zip", "public", threads: 8) # what is under public/,
# compressed on 8 threads
Ziperu::File.open("site.zip") do |zf|
zf.extract_all("restored/", threads: 8) # never writes outside restored/
zf.extract_all("restored/", on_exists: :overwrite, exclude: ["*.log"])
endBuild an archive in memory and hand it out, write one straight to an IO, or take one in:
bytes = Ziperu::OutputStream.write_buffer do |zos|
zos.put_next_entry("report.csv")
zos.write(csv)
end.string
Ziperu::OutputStream.write_buffer(socket) do |zos| # a pipe or socket is streamed,
zos.put_next_entry("report.csv") # nothing buffered to the end
zos.write(csv)
end
Ziperu::File.open_buffer(params[:upload].read) do |zf|
zf.each { |e| puts "#{e.name}: #{e.size} bytes" }
endStream a zip download without a temp file. OutputStream.body returns a
Rack body: an Enumerator of the archive's bytes, produced as the server
consumes them.
require "ziperu/rails_streaming"
body = Ziperu::OutputStream.body do |zos|
attachments.each do |att|
zos.put_next_entry(att.filename)
att.download { |chunk| zos.write(chunk) }
end
end
[200, Ziperu::RailsStreaming.headers("attachments.zip"), body]In a Rails controller, zip_stream sets the headers and the body, with
no need for ActionController::Live:
class ExportsController < ApplicationController
include Ziperu::RailsStreaming
def show
zip_stream("export.zip") do |zos|
zos.put_next_entry("a.csv")
zos.write(csv)
end
end
endAdd files to an archive you already have (appended in place, the rest is not rewritten), or replace one; or keep the original and write the changed archive elsewhere:
Ziperu::File.open("backup.zip") do |zf|
zf.add("logs/today.log", "/var/log/app/today.log")
zf.add("upload.bin", StringIO.new(bytes)) # any IO, streamed on commit
zf.get_output_stream("manifest.json") { |io| io.write(manifest.to_json) }
end
Ziperu::File.open("backup.zip", write: "backup-2.zip") { |zf| zf.remove("old.log") }
Ziperu::File.open("backup.zip", write: false) { |zf| zf.read("manifest.json") } # read-onlyPick one entry out of a large archive, or read it all as a stream.
foreach yields one entry at a time in constant memory, however many
there are:
entry = Ziperu::File.foreach("huge.zip").find { |e| e.name.end_with?(".sig") }
Ziperu::InputStream.open(socket) do |zis| # any IO, no seeking needed
while (entry = zis.get_next_entry)
process(entry.name, zis.read)
end
end
# A pipe or an upload read in one pass, an entry's worth of memory at a
# time, rather than taken in whole to reach the central directory:
Ziperu::InputStream.open(s3_object.body, streaming: true) do |zis|
while (entry = zis.get_next_entry)
zis.each_line { |line| ... }
end
endRead an archive in place on a server, without downloading it: only the central directory and the entries read are fetched, with HTTP Range requests (S3, GCS, a CDN; or a block that returns byte ranges):
io = Ziperu::RemoteIO.new(url) # "https://example.com/dataset.zip"
Ziperu::File.open_buffer(io, write: false) do |zf|
zf.extract("docs/guide.txt", "guide.txt") # a few requests, not 5 GB
endLeave out an entry whose data could not be had, and go on with the rest (a download that failed half-way through a streamed zip, say):
body = Ziperu::OutputStream.body do |zos|
files.each do |name, url|
zos.put_next_entry(name)
begin
fetch(url) { |chunk| zos << chunk }
rescue Net::HTTPError
zos.rollback_entry # before its first byte on a stream; any time on a file
end
end
end
[200, { "content-type" => "application/zip" }, body]Seek about in a Stored entry, for readers that want random access (a PDF stored in an archive):
Ziperu::File.open("scans.zip") do |zf|
zf.get_input_stream("scan.pdf") { |io| io.seek(-1024, IO::SEEK_END); io.read(1024) }
endPasswords, both ways:
Ziperu::File.open("secret.zip", password: "s3cret") { |zf| zf.extract_all("out/") }
Ziperu::OutputStream.open("secret.zip", encrypter: Ziperu::AESEncrypter.new("s3cret")) do |zos|
zos.put_next_entry("plan.txt")
zos.write("...")
endKeep hostile archives in check before reading a byte of them:
Ziperu.max_entries = 10_000
Ziperu.max_total_size = 2 << 30 # 2 GiB uncompressed
Ziperu.max_compression_ratio = 1_000 # a zip bomb runs to a millionOr for one archive only, leaving the globals alone; every Ziperu.*
setting is a keyword of the same name on File, InputStream and
OutputStream:
Ziperu::File.open(upload, max_entries: 1_000, max_total_size: 1 << 30) { |zip| ... }
Ziperu::OutputStream.open("out.zip", write_extended_timestamps: true) { |zos| ... }Ziperu::Limits has ready-made sets of these: UPLOAD for archives
users upload, STRICT for small documents, NONE to clear them.
Ziperu::File.open(upload, **Ziperu::Limits::UPLOAD) { |zip| ... }
Ziperu::Limits.apply(Ziperu::Limits::STRICT) # the globalsLook before you extract. extraction_plan says what extract_all would
do with each entry, without writing anything. verify(report: true) says
which entries were checked, which failed and which were skipped:
Ziperu::File.open(upload) do |zip|
plan = zip.extraction_plan("out", sanitize: :windows)
plan.reject(&:extract?).each { |item| warn "#{item.entry.name}: #{item.status}" }
plan.select(&:collides_with) # entries that land on the same path
plan.sum(&:declared_size) # declared bytes to be written
report = zip.verify(report: true)
report.ok? # false if anything failed or was skipped
report.skipped # { entry => :encrypted }, say
endUnpack whatever was uploaded, a zip or a tar archive, compressed or not.
Ziperu.extract tells which from the first bytes. A tar archive is read
front to back, so it can come from a pipe or a response body:
Ziperu.extract(upload, "out", **Ziperu::Limits::UPLOAD)
Ziperu::Tar.extract_all("release.tar.gz", "src", strip_components: 1)
Ziperu::Tar.foreach("logs.tar.zst") do |entry| # one entry at a time
process(entry.name, entry.read) if entry.file?
endTar extraction follows the rules zip extraction does, and adds its own for hard links and devices; docs/tar.md has them, and what is read.
Write a tar archive, to a file or to anything with write. The
compression follows the file's name, or compression::
Ziperu::Tar.add_recursive("site.tar.gz", "public")
Ziperu::Tar.create("backup.tar.zst", level: 10) do |tar|
tar.add("report.pdf", "tmp/report.pdf") # a file from disk
tar.add("upload.bin", StringIO.new(bytes)) # any IO
tar.add_data("manifest.json", manifest.to_json)
tar.add_recursive("var/log/app", prefix: "logs/")
end
[200, { "content-type" => "application/gzip" },
Ziperu::Tar.body(compression: :gzip) { |tar| tar.add_data("report.csv", csv) }]Change the Gemfile line and keep require "zip": the Zip constant and
its classes (Zip::File, Zip::Entry, Zip::Error, ...) point at the
Ziperu ones. Class names read Ziperu::... in inspect output and
exception messages, which only matters to code comparing against the
string "Zip::Entry".
Gems that depend on rubyzip (roo, caxlsx, rubyXL and the like) still
pull it in, but under Bundler ziperu's zip.rb comes first on the load
path, so require "zip" loads ziperu and those gems run on it; rubyzip
stays installed and unused. Checked with Bundler 2.3, 2.5 and 4.0, in
either Gemfile order.
Without Bundler, RubyGems loads whichever gem asks for zip first. To
have ziperu answer for rubyzip there too, require this before anything
else loads it (the top of a script, or config/boot.rb):
require "ziperu/replace_rubyzip" # every require "zip" / "zip/..." loads ziperuIt raises if rubyzip is already loaded, rather than mix the two. Short of
that, use require "ziperu" and Ziperu:: for your own code and leave
Zip:: to rubyzip.
ziperu tracks the rubyzip 3.x API (Ziperu::RUBYZIP_COMPAT_VERSION), and
diverges on purpose where rubyzip is lax: InputStream reads through the
central directory so streamed archives work; every read stops at the
declared size (Ziperu::EntrySizeError); a CRC mismatch raises; names
flagged UTF-8 come back as UTF-8 strings; duplicate names in one
OutputStream raise. The full list, and what ziperu adds (archive limits,
File#verify, symlink entries, progress callbacks, more compression
methods), is in docs/migrating.md. What rubyzip's own
test suite makes of ziperu is in COMPAT.md.
- Ruby 3.3 to 4.0 are supported and tested on Linux, macOS and Windows. 3.1 and 3.2 still get binaries, best effort.
- Precompiled for x86_64 and aarch64 Linux (glibc and musl; musl needs
libgcc), Intel and Apple Silicon macOS, and x64 and arm64 Windows. Elsewhere the source gem builds with Rust 1.88+. - CRuby only: on JRuby or TruffleRuby, use rubyzip.
bundle install
bundle exec rake compile test # build the extension, run the suite
bundle exec rake compat # rubyzip's own test suite against ziperu
bundle exec rake fuzz # differential fuzzing (TIME=180 for three minutes)
bundle exec rake fuzz:tar # the same for tar, against Python's tarfile
bundle exec rake bench # the table aboveNeeds Ruby 3.1+ and Rust 1.88+. Windows setup, the fuzzer, the compat run, the release pipeline and the code layout are described in docs/development.md.
- RubyGems
- Changelog
- Migrating from rubyzip: every deliberate difference, and what ziperu adds
- rubyzip compatibility report
- Tar archives: what is read and written, how extraction behaves, the limits
- Benchmarks: all three platforms, and which calls release the GVL
- Security: what extraction and reading guard against
- Development: building, the fuzzer, the release pipeline
Bug reports and pull requests are welcome on
GitHub. Run
bundle exec rake compile test before opening one; CI also runs clippy,
rubyzip's suite, the fuzzer and the interoperability check.
The gem is available as open source under the terms of the
MIT License. The Ruby layer ports a good part of rubyzip
(the extra-field, filesystem, DOS time, entry-set and split code, and the
test fixtures under test/data/rubyzip/), which is BSD-2-Clause; its
notice is in LICENSE-rubyzip.txt and the ported
files say so at the top.