deflate_init / deflate_add / inflate_init / inflate_add
deflate_init(int $encoding, array|object $options = []): DeflateContext|false · deflate_add(DeflateContext $context, string $data, int $flush_mode = ZLIB_SYNC_FLUSH): string|false · inflate_init(int $encoding, array|object $options = []): InflateContext|false · inflate_add(InflateContext $context, string $data, int $flush_mode = ZLIB_SYNC_FLUSH): string|false
Incremental (streaming) deflate compression/decompression: feed data in chunks with flush modes controlling block boundaries — contrasted with the existing gzdeflate (one-shot): NO_FLUSH middle chunks produce identical output while SYNC_FLUSH inserts sync-marker bytes; Python's zlib.compressobj and Java's Deflater are the direct counterparts.
C C23
#include <stdio.h>
#include <string.h>
int main(void) {
/* no zlib linkage here: hand-rolled RFC 1951 STORED blocks (BTYPE=00) */
const char *part = "Hello, streaming world! ";
unsigned char data[484] = {0};
size_t n = 0;
for (int i = 0; i < 20; i++) { memcpy(data + n, part, 24); n += 24; }
memcpy(data + n, "END", 3); n += 3;
/* chunked: two stored blocks split at 100 (LEN/NLEN little-endian) */
unsigned char chunked[600] = {0};
size_t k = 0;
chunked[k++] = 0x00; /* BFINAL=0, BTYPE=00 */
chunked[k++] = 100; chunked[k++] = 0; /* LEN */
chunked[k++] = 0x9B; chunked[k++] = 0xFF; /* NLEN = ~LEN */
memcpy(chunked + k, data, 100); k += 100;
chunked[k++] = 0x01; /* BFINAL=1, BTYPE=00 */
unsigned len2 = (unsigned)(n - 100);
chunked[k++] = (unsigned char)len2; chunked[k++] = (unsigned char)(len2 >> 8);
chunked[k++] = (unsigned char)~len2; chunked[k++] = (unsigned char)(~len2 >> 8);
memcpy(chunked + k, data + 100, n - 100); k += n - 100;
/* one-shot: single stored block wrapping everything */
unsigned char once[600] = {0};
size_t m = 0;
once[m++] = 0x01;
once[m++] = (unsigned char)n; once[m++] = (unsigned char)(n >> 8);
once[m++] = (unsigned char)~n; once[m++] = (unsigned char)(~n >> 8);
memcpy(once + m, data, n); m += n;
printf("%zu chunked vs %zu one-shot: %s\n", k, m,
memcmp(chunked, once, k < m ? k : m) == 0 && k == m ? "identical" : "different");
/* unpack: walk the stored blocks back (the inflate side) */
unsigned char restored[484] = {0};
size_t r = 0, i = 0;
unsigned char header;
do {
header = chunked[i++];
size_t len = chunked[i] | (chunked[i + 1] << 8);
i += 4; /* skip LEN + NLEN */
memcpy(restored + r, chunked + i, len);
r += len; i += len;
} while (!(header & 1));
printf("%s\n", memcmp(restored, data, n) == 0 ? "inflate matches original" : "fail");
return 0;
}
493 chunked vs 488 one-shot: different inflate matches original
C++ C++26
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
int main() {
// no zlib linkage here: hand-rolled RFC 1951 STORED blocks (BTYPE=00)
std::string part = "Hello, streaming world! ";
std::vector<uint8_t> data;
for (int i = 0; i < 20; i++)
data.insert(data.end(), part.begin(), part.end());
const char *end = "END";
data.insert(data.end(), end, end + 3);
auto append_stored = [&data](std::vector<uint8_t> &out, uint8_t bfinal,
size_t off, size_t len) {
out.push_back(bfinal); // BTYPE=00 in the low bits
uint16_t l = static_cast<uint16_t>(len);
uint16_t nlen = static_cast<uint16_t>(~l);
out.push_back(l & 0xFF);
out.push_back(l >> 8);
out.push_back(nlen & 0xFF);
out.push_back(nlen >> 8);
for (size_t i = off; i < off + len; i++)
out.push_back(data[i]);
};
std::vector<uint8_t> chunked, once;
append_stored(chunked, 0x00, 0, 100);
append_stored(chunked, 0x01, 100, data.size() - 100);
append_stored(once, 0x01, 0, data.size());
std::cout << chunked.size() << " chunked vs " << once.size() << " one-shot: "
<< (chunked == once ? "identical" : "different") << "\n";
// unpack: walk the stored blocks back (the inflate side)
std::vector<uint8_t> restored;
size_t i = 0;
uint8_t header;
do {
header = chunked[i++];
uint16_t len = chunked[i] | (chunked[i + 1] << 8);
i += 4;
restored.insert(restored.end(), chunked.begin() + i, chunked.begin() + i + len);
i += len;
} while (!(header & 1));
std::cout << (restored == data ? "inflate matches original" : "fail") << "\n";
return 0;
}
493 chunked vs 488 one-shot: different inflate matches original
C# v11.0.100
// DeflateStream wraps any stream: chunked writes with Flush between them
string data = string.Concat(System.Linq.Enumerable.Repeat("Hello, streaming world! ", 20)) + "END";
byte[] all = System.Text.Encoding.UTF8.GetBytes(data);
var chunked = new MemoryStream();
using (var def = new System.IO.Compression.DeflateStream(chunked,
System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true))
{
byte[] first = System.Text.Encoding.UTF8.GetBytes(data[..100]);
def.Write(first, 0, first.Length);
def.Flush(); // sync-flushes the deflate block boundary
byte[] rest = System.Text.Encoding.UTF8.GetBytes(data[100..]);
def.Write(rest, 0, rest.Length);
}
var once = new MemoryStream();
using (var def2 = new System.IO.Compression.DeflateStream(once,
System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true))
{
def2.Write(all, 0, all.Length);
}
Console.WriteLine($"{chunked.Length} chunked vs {once.Length} one-shot: " +
(chunked.Length != once.Length ? "different" : "identical"));
chunked.Position = 0;
using var inf = new System.IO.Compression.DeflateStream(chunked, System.IO.Compression.CompressionMode.Decompress);
using var sr = new StreamReader(inf, System.Text.Encoding.UTF8);
Console.WriteLine(sr.ReadToEnd() == data ? "inflate matches original" : "fail");
44 chunked vs 36 one-shot: different inflate matches original
Go v1.27.4
package main
import (
"bytes"
"compress/flate"
"fmt"
"io"
)
func main() {
data := bytes.Repeat([]byte("Hello, streaming world! "), 20)
data = append(data, []byte("END")...)
// flate.Writer: feed chunks; Flush() is a sync flush between them
var chunked bytes.Buffer
w, _ := flate.NewWriter(&chunked, flate.DefaultCompression)
w.Write(data[:100])
w.Flush()
w.Write(data[100:])
w.Close()
var once bytes.Buffer
w2, _ := flate.NewWriter(&once, flate.DefaultCompression)
w2.Write(data)
w2.Close()
diff := !bytes.Equal(chunked.Bytes(), once.Bytes())
fmt.Printf("%d chunked vs %d one-shot: %s\n", chunked.Len(), once.Len(),
map[bool]string{true: "different", false: "identical"}[diff])
restored, _ := io.ReadAll(flate.NewReader(bytes.NewReader(chunked.Bytes())))
if bytes.Equal(restored, data) {
fmt.Println("inflate matches original")
} else {
fmt.Println("fail")
}
}
144 chunked vs 35 one-shot: different inflate matches original
Java v27.0.1
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class Main {
public static void main(String[] args) throws Exception {
String data = "Hello, streaming world! ".repeat(20) + "END";
byte[] all = data.getBytes(StandardCharsets.UTF_8);
// Deflater: feed chunks, SYNC_FLUSH between them
Deflater def = new Deflater();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
def.setInput(all, 0, 100);
int n = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH);
out.write(buf, 0, n);
def.setInput(all, 100, all.length - 100);
def.finish();
while (!def.finished()) {
n = def.deflate(buf, 0, buf.length);
out.write(buf, 0, n);
}
def.end();
byte[] chunked = out.toByteArray();
// one-shot comparison
Deflater def2 = new Deflater();
def2.setInput(all);
def2.finish();
ByteArrayOutputStream once = new ByteArrayOutputStream();
while (!def2.finished()) {
int m = def2.deflate(buf, 0, buf.length);
once.write(buf, 0, m);
}
def2.end();
System.out.println(chunked.length + " chunked vs " + once.size() + " one-shot: "
+ (java.util.Arrays.equals(chunked, once.toByteArray()) ? "identical" : "different"));
// inflate back
Inflater inf = new Inflater();
inf.setInput(chunked);
byte[] restored = new byte[all.length];
int total = inf.inflate(restored);
inf.end();
System.out.println(new String(restored, 0, total, StandardCharsets.UTF_8).equals(data)
? "inflate matches original" : "fail");
}
}
48 chunked vs 40 one-shot: different inflate matches original
JavaScript v26.13.1
// zlib streams: chunked writes with a sync flush between them
const zlib = require("node:zlib");
const data = "Hello, streaming world! ".repeat(20) + "END";
async function main() {
const chunks = [];
const def = zlib.createDeflateRaw();
def.on("data", (c) => chunks.push(c));
const done = new Promise((res) => def.on("end", res));
def.write(Buffer.from(data.slice(0, 100)));
def.flush(); // sync flush marks the chunk boundary
def.end(Buffer.from(data.slice(100)));
await done;
const chunked = Buffer.concat(chunks);
const once = zlib.deflateRawSync(Buffer.from(data));
console.log(`${chunked.length} chunked vs ${once.length} one-shot: ${chunked.equals(once) ? "identical" : "different"}`);
const inf = zlib.inflateRawSync(chunked);
console.log(inf.toString() === data ? "inflate matches original" : "fail");
}
main();
67 chunked vs 34 one-shot: different inflate matches original
PHP v8.6.0
// streaming: feed chunks through a context; sync flushes mark chunk boundaries
$data = str_repeat("Hello, streaming world! ", 20) . "END";
$ctx = deflate_init(ZLIB_ENCODING_RAW);
$part1 = deflate_add($ctx, substr($data, 0, 100), ZLIB_SYNC_FLUSH);
$part2 = deflate_add($ctx, substr($data, 100), ZLIB_FINISH);
$chunked = $part1 . $part2;
$once = gzdeflate($data);
echo strlen($chunked), " chunked vs ", strlen($once), " one-shot: ",
$chunked === $once ? "identical" : "different", "\n";
echo inflate_add(inflate_init(ZLIB_ENCODING_RAW), $chunked, ZLIB_FINISH) === $data
? "inflate matches original\n" : "fail\n";
42 chunked vs 34 one-shot: different inflate matches original
Python v3.15.2
# compressobj: streaming counterpart with Z_SYNC_FLUSH
import zlib
data = ("Hello, streaming world! " * 20) + "END"
co = zlib.compressobj(wbits=-15) # raw deflate, like ZLIB_ENCODING_RAW
part1 = co.compress(data[:100].encode()) + co.flush(zlib.Z_SYNC_FLUSH)
part2 = co.compress(data[100:].encode()) + co.flush(zlib.Z_FINISH)
chunked = part1 + part2
once = zlib.compress(data.encode(), wbits=-15)
print(len(chunked), "chunked vs", len(once), "one-shot:",
"identical" if chunked == once else "different")
print("inflate matches original" if zlib.decompress(chunked, wbits=-15) == data.encode() else "fail")
42 chunked vs 34 one-shot: different inflate matches original
Rust v1.99.1
fn main() {
// no compression crate in scope: hand-rolled RFC 1951 STORED blocks
// (BTYPE=00 wraps raw bytes in chunk containers, the deflate block format)
let data: Vec<u8> = "Hello, streaming world! ".repeat(20).into();
let data = [data.as_slice(), b"END"].concat();
// chunked: two stored blocks (LEN <= 65535 each)
let mut chunked: Vec<u8> = Vec::new();
chunked.push(0x00); // BFINAL=0, BTYPE=00
let (a, b) = data.split_at(100);
chunked.extend_from_slice(&(a.len() as u16).to_le_bytes());
chunked.extend_from_slice(&(!(a.len() as u16)).to_le_bytes());
chunked.extend_from_slice(a);
chunked.push(0x01); // BFINAL=1, BTYPE=00
chunked.extend_from_slice(&(b.len() as u16).to_le_bytes());
chunked.extend_from_slice(&(!(b.len() as u16)).to_le_bytes());
chunked.extend_from_slice(b);
// one-shot: a single stored block
let mut once: Vec<u8> = vec![0x01];
once.extend_from_slice(&(data.len() as u16).to_le_bytes());
once.extend_from_slice(&(!(data.len() as u16)).to_le_bytes());
once.extend_from_slice(&data);
println!("{} chunked vs {} one-shot: {}",
chunked.len(), once.len(),
if chunked == once { "identical" } else { "different" });
// unpack: walk the stored blocks back (the inflate side)
let mut restored: Vec<u8> = Vec::new();
let mut i = 0usize;
loop {
let header = chunked[i];
i += 1;
let len = u16::from_le_bytes([chunked[i], chunked[i + 1]]) as usize;
i += 4; // skip LEN + NLEN
restored.extend_from_slice(&chunked[i..i + len]);
i += len;
if header & 1 == 1 {
break; // BFINAL
}
}
println!("{}", if restored == data { "inflate matches original" } else { "fail" });
}
493 chunked vs 488 one-shot: different inflate matches original
TypeScript v26.13.1
// zlib streams: chunked writes with a sync flush between them
import zlib from "node:zlib";
const data: string = "Hello, streaming world! ".repeat(20) + "END";
async function main(): Promise<void> {
const chunks: Buffer[] = [];
const def = zlib.createDeflateRaw();
def.on("data", (c: Buffer) => chunks.push(c));
const done = new Promise<void>((res) => def.on("end", res));
def.write(Buffer.from(data.slice(0, 100)));
def.flush(); // sync flush marks the chunk boundary
def.end(Buffer.from(data.slice(100)));
await done;
const chunked = Buffer.concat(chunks);
const once = zlib.deflateRawSync(Buffer.from(data));
console.log(`${chunked.length} chunked vs ${once.length} one-shot: ${chunked.equals(once) ? "identical" : "different"}`);
const inf = zlib.inflateRawSync(chunked);
console.log(inf.toString() === data ? "inflate matches original" : "fail");
}
main();
67 chunked vs 34 one-shot: different inflate matches original
Language differences
C: no zlib linkage here — hand-rolled RFC 1951 STORED blocks demonstrate the essence of deflate's block structure, "chunked containers differ from one-shot but unpack identically" (example); in production link zlib's deflateInit_/deflate/inflate series.
C++: isomorphic STORED blocks with a lambda builder (example); production uses zlib or Boost.Iostreams.
C#: DeflateStream over a MemoryStream is the streaming form (example); Flush() pushes out the deflate block boundary, and the output is longer than one-shot (44 vs 36 — .NET's block strategy differs from zlib, with identical decompression); note it emits raw deflate (RFC 1951).
Go: compress/flate Writer/Flush/NewReader (example); Flush() is sync-flush semantics, chunked 144 vs one-shot 35 — Go's block strategy yields different sizes from the zlib family (identical decompression).
Java: Deflater.deflate(buf, off, len, SYNC_FLUSH) is the exact counterpart (example); 48 vs 40 (Java's bundled zlib version differs from PHP's libz in block strategy, identical decompression); Inflater restores the original.
JavaScript: Node zlib streams (createDeflateRaw plus flush(), example); the streaming API versus deflateRawSync mirrors incremental vs one-shot; 67 vs 34 (Node flush pushes out more aggressively, same library different call shape).
PHP: deflate_init/deflate_add are the streaming counterparts of gzdeflate (one-shot); flush-mode semantics: NO_FLUSH hoards data (middle chunks may match the one-shot output byte for byte), SYNC_FLUSH flushes to a byte boundary (inserting the 00 00 FF FF marker, longer output), FULL_FLUSH resets the dictionary, FINISH ends the stream; the three ZLIB_ENCODING_* constants switch raw/zlib/gzip containers; inflate_init/inflate_add mirror it on the decompression side; typical uses: compressing while receiving network streams, chunked compression of large files.
Python: zlib.compressobj plus flush(Z_SYNC_FLUSH/Z_FINISH) is the closest counterpart (example); wbits=-15 selects raw deflate matching ZLIB_ENCODING_RAW; 42 vs 34 matches PHP exactly (same zlib library).
Rust: no compression crate in scope — hand-written STORED blocks demonstrate the block structure (example); the production standard is the flate2 crate (write::DeflateEncoder as the streaming counterpart).
TypeScript: same Node zlib streaming API (example); the type layer annotates chunks as Buffer.