[mibz2 · Research blog](<https://lmmx.github.io/mibz2/blog/index.md>)

# Stop zeroing the buffer: direct decoding across Rust and Python

Removing hidden zero-fills and wrapper copies lets mibz2 decode straight into Rust buffers and Python text without unsafe code.

28 November 2026 · 7 min read · [Research result](<#5-respecting-the-block-boundary-across-languages>)

A fast decompression core can still lose half its speed at the outer API boundary. Standard library wrappers often spend more time preparing memory than the decoder spends decompressing bytes. That hidden tax shows up when callers ask for a whole buffer, a UTF-8 text stream, or incremental push chunks.

Two new safe-Rust changes now ship on the main branch of mibz2. They remove the same wasted memory passes on both sides of the language boundary. In Rust, overriding whole-stream byte and string reads eliminates hidden buffer zeroing and intermediate block copies. In Python, a direct UTF-8 text reader and a reusable incremental decompressor replace CPython's triple-copy text wrapper. Both Python features stay strictly inside the Python 3.10 Stable ABI.

Neither change adds a single line of unsafe code. Every benchmark below was verified byte for byte in alternating fresh subprocesses on a Linux virtual machine.

**Takeaways**

- **Rust whole-stream reads cut up to 61% off CPU time and 60% off peak memory.** Decoding directly into the caller's vector removes spare-capacity zero-fills and staging copies. Wikidata and ordinary text run 4% to 6.6% faster with zero regressions across 58 cells.
- **Overriding byte reads alone missed Rust string reads.** In Rust 1.99.1, the default string reader calls an internal helper instead of delegating to a custom byte override. Overriding both methods brought the same direct path to UTF-8 strings with exact error rollback.
- **Direct Python UTF-8 text mode saves 186 MiB of peak memory on Wikidata.** Decoding straight from lent Rust block slices drops whole-file peak memory by 30%. That brings text reads within 0.8 MiB and 1.5% CPU of raw binary reads.
- **Text line lists run up to 17% faster in Python.** Reading all lines from a 28.7 MB text file drops 17.1% in CPU time on one thread. Four-thread runs drop 15.1%, while keeping one universal Stable ABI wheel.
- **Incremental push decompression runs up to 13.1 times faster than Python's standard library.** Reusing block scratch and decoding complete blocks off the Global Interpreter Lock speeds up text by 6.6 to 7.0 times. Twelve-stream Wikidata runs 13.1 times faster.

## 1\. Why Rust's default whole-stream read touches memory three times

Most Rust libraries implement only the core byte-slice read method on a streaming reader. They inherit the trait's default whole-stream helpers. That convenience works well for small reads, yet it imposes three silent costs on a block decoder.

First, Rust's safe default loop cannot hand uninitialized memory to a reader. Each time the caller's output vector grows, the standard library zero-fills the new spare capacity before asking the reader to overwrite it. On a 40 MB run-heavy stream, the processor faults and writes 40 MB of zeros before decoding a single byte.

Second, our sequential reader already decoded each bzip2 block into an internal staging vector before copying slices out. With the zero-fill pass included, every decoded byte crossed memory three times. It was written once as zeros, once into the staging block, and once into the caller's vector.

Third, a subtle standard-library detail caught us during testing. In Rust 1.99.1, the default string-reading method does not call a custom byte-read override. Instead, it calls the standard library's internal default byte loop directly. Overriding byte reads alone left string callers paying the full zero-fill and copy penalty.

We also found an eager page-fault tax on the input side. Our sequential reader grew its initial 4 MiB input buffer by resizing an empty vector with zeros. That loop touched all 1,024 memory pages up front, even for a 51-byte file. Switching to allocator-zeroed allocation leaves untouched pages unmapped until input actually fills them.

## 2\. Direct safe decoding into caller buffers in Rust

Fixing all four paths took zero unsafe code and kept every error-handling contract intact.

On the sequential path, the reader first drains any unread bytes left from earlier partial reads. It then decodes each remaining bzip2 block straight into the caller's vector. If a corrupt block fails halfway through, the reader truncates the vector back to that block's start. All earlier valid bytes stay intact, and the error latches cleanly.

On the parallel path, workers already produce whole decoded block vectors up to 900 KiB. When the caller passes an empty vector with zero capacity, the reader moves the first decoded block straight into it. That transfer uses zero copying and zero second allocation. Every later block appends directly and returns its empty buffer to the worker pool for reuse.

String reads reuse the same direct byte path without touching unsafe code. The reader moves the string's backing bytes into direct byte decoding, then validates UTF-8 in one pass. On any I/O failure, bad checksum, or invalid UTF-8 byte, it truncates back to the original length. The caller's string is restored completely intact.

Direct safe decoding in Rust: dataflow change and paired CPU and peak-memory cuts

Left: removing spare-capacity zero-fills and intermediate block copies drops Rust whole-stream reads from three memory passes to one. Right: expansive run-heavy streams drop 60% in both CPU time and peak memory, while Wikidata, text, and random all improve with zero regressions.

We tested these changes over nine alternating fresh-subprocess rounds on a four-vCPU Linux virtual machine. All 58 cells improved or stayed flat with zero regressions:

- **Expansive run-heavy streams:** single-byte runs dropped **61.0% in CPU** and **60.0% in peak memory**. Peak resident memory fell from 113.5 MiB down to 45.4 MiB. Mixed runs dropped **59.9% in CPU** and **59.2% in peak memory**, falling from 61.1 MiB to 24.9 MiB. Parallel runs across one to eight threads saw matching 50% to 59% cuts.
- **Wikidata JSON:** sequential byte reads dropped **6.3% to 6.6% in CPU time** on 209.7 MB. Four-thread string reads cut **4.0% CPU** and **4.1% peak memory**, dropping from 298.1 MiB to 285.8 MiB.
- **Ordinary text and random data:** four-thread text byte reads dropped **5.1% in CPU** and **5.7% in peak memory**. Four-thread random reads cut **11.6% off peak memory** by avoiding duplicated growth buffers, falling from 74.4 MiB to 65.8 MiB.

## 3\. Cutting 186 MiB off Python UTF-8 text mode

Our [earlier Python line-delivery post](<https://lmmx.github.io/mibz2/blog/2026-11-28-python-line-delivery-stable-abi/index.md>) removed CPython's redundant binary buffer. That work accelerated raw binary line iteration up to 26 times inside one universal Stable ABI wheel. Two major Python surfaces still remained: UTF-8 text mode and incremental push decompression.

Until now, mibz2's file opener supported binary mode only. Anyone reading compressed logs or JSON dumps as strings had to wrap mibz2 in CPython's standard text wrapper.

That wrapper repeats the exact staging mistake we just fixed in Rust. It pulls 8 KiB chunks into temporary bytes objects, then decodes them into an internal character buffer. Finally, it slices or joins lines to hand back to the caller. That pipeline adds three copies per byte on top of parallel decoding.

Raising CPython's internal text chunk size from 8 KiB to 256 KiB actually hurt. On 28.7 MB of text, CPU time regressed from 754.8 ms to 793.1 ms. Peak memory also rose by 7.4 MiB because the oversized character buffer evicted L1 and L2 caches. On 210 MB of Wikidata JSON, reading the whole file through the standard wrapper spiked peak memory to **621.4 MiB**. That is nearly three times the decoded output and 187 MiB above binary reads.

mibz2 now supports native text mode directly in its opener while keeping full standard-library compatibility:

- **Direct UTF-8 decoding from lent block slices.** For strict UTF-8 streams with standard newlines, Rust decodes straight from the lent block slice into Python strings via the Stable ABI. Temporary bytes chunks and the extra character buffer vanish completely.
- **Safe eight-byte newline scanning across block boundaries.** Pure integer operations scan eight bytes at a time for line feeds and carriage returns. Multi-byte UTF-8 characters and carriage-return pairs stay intact whenever they cross a bzip2 block boundary.
- **Shared lock handle with zero per-line borrow churn.** Extracting a shared reader handle removed PyO3's per-line borrow overhead during iteration. Single-thread text iteration speedup more than doubled, jumping from 3.7% to 8.7%.
- **Exact error parity and clean fallback.** When invalid UTF-8 bytes appear, Rust delegates that slice to CPython's own strict decoder. Exception offsets and messages therefore match character for character. Non-UTF-8 encodings and custom error handlers fall back cleanly to the standard wrapper.

On 210 MB of Wikidata JSON, single-thread whole-file text reads dropped **11.9% in CPU time**, falling from 1,870.6 ms to 1,647.4 ms. Peak memory fell **186.4 MiB**, dropping **30.0%** from 621.4 MiB down to 435.0 MiB. Native UTF-8 text reads now sit within 1.5% CPU and 0.8 MiB memory of raw binary reads. On 28.7 MB of text with 793,778 lines, reading all lines dropped **17.1% in CPU** on one thread and **15.1%** on four threads.

## 4\. Incremental push decompression in Python

Not every Python pipeline pulls bytes from a seekable file. HTTP clients, asynchronous downloaders, cloud object streams, and archive extractors push arbitrary compressed chunks into a stateful decompressor.

Python's standard library provides an incremental bzip2 decompressor for those callers. It runs single-threaded C libbzip2 at roughly 13 MB/s on Wikidata.

mibz2 now ships a drop-in incremental decompressor matching the full standard interface. It supports bounded output limits, end-of-stream flags, unused trailing bytes for multi-stream handoff, and standard end-of-file errors. Internally, it reuses its BWT scratch, symbol scratch, and output buffers across incoming chunks. It compacts its input buffer in amortized constant time and decodes complete blocks off the Global Interpreter Lock.

Direct Python UTF-8 text mode savings (left) and incremental decompressor speedup vs standard library (right)

Left: direct Rust UTF-8 text mode removes CPython's triple-copy TextIOWrapper, saving 186 MiB of peak memory on Wikidata and up to 17.1% CPU on text line lists. Right: mibz2's reusable incremental decompressor runs 6.6× to 13.1× faster than Python's standard library while holding peak memory between 28 and 50 MiB.

Across all five push-decompression workloads, mibz2 beat Python's standard library by a wide margin. On text, CPU time fell from roughly 2.1 seconds down to 0.32 seconds, a **6.6× to 7.0× speedup**. On twelve-stream Wikidata, CPU time dropped from 16.5 seconds to 1.26 seconds, a **13.1× speedup**. Peak resident memory stayed modest throughout, sitting between 27.8 and 49.5 MiB.

## 5\. Respecting the block boundary across languages

Looking at both changes side by side reveals one clear design rule. Both Rust's generic byte-reading trait and Python's layered I/O stack were designed around small, unbuffered kernel reads. When a block-parallel bzip2 decoder sits underneath them, generic defaults force extra memory passes. Rust zero-fills spare vector capacity before overwriting it, while Python bounces 8 KiB chunks into an oversized character buffer.

Respecting the natural 900 KiB bzip2 block boundary removes that waste in both languages without trading away safety. Rust moves whole decoded blocks straight into the caller's vector or string. Python lends the same block slice directly into UTF-8 string creation and reuses block scratch across push chunks. All of it stays in safe Rust inside one universal Python 3.10 Stable ABI wheel.

All timings above come from paired container benchmarks confirming API-layer CPU and memory savings. Physical workstation release verification stays separate through our automated hardware preflight gate. Both advances are merged on the main branch today and queued for the next mibz2 release.

---

**Sources:**

- Rust direct whole-stream byte and string decoding: [\#1398](<https://github.com/lmmx/mibz2/pull/1398>) (`b4135e21`), [lab notebook](<https://github.com/lmmx/mibz2/blob/1c83b8aa/docs/notebook/2026-11-28-bzreader-read-to-end.md>).
- Python direct UTF-8 text mode and incremental push decompressor: [\#1397](<https://github.com/lmmx/mibz2/pull/1397>) (`318c870b`), [lab notebook](<https://github.com/lmmx/mibz2/blob/1c83b8aa/docs/notebook/2026-11-28-python-rt-and-decompressor.md>).
- Earlier binary Python line-delivery post: [Twenty-six times faster line iteration in Python without leaving the Stable ABI](<https://lmmx.github.io/mibz2/blog/2026-11-28-python-line-delivery-stable-abi/index.md>).
