gzdeflate / gzinflate
gzdeflate(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_RAW): string|false · gzinflate(string $data, int $max_length = 0): string|false
Compresses/decompresses raw deflate data (RFC 1951) — the leanest of the three zlib formats (raw deflate / zlib / gzip), forming a family with gzcompress (zlib format) and gzencode (gzip format); the wbits window parameter is the core switch across languages.
C C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>
/* The C standard library has no compression (the real three formats come from zlib's
deflateInit2, where windowBits selects the format: -15 = raw deflate, 15 = zlib, 31 = gzip;
link with -lz). Hand-write a stored-mode (BTYPE=00) payload shared by all three wrappers
to show the real header-overhead ladder:
raw has no header/trailer < zlib adds 2+4 bytes < gzip adds 10+8 bytes. */
static uint32_t adler32_of(const uint8_t *p, size_t n) { /* zlib trailer checksum */
uint32_t a = 1, b = 0;
const uint32_t MOD = 65521;
for (size_t i = 0; i < n; i++) {
a = (a + p[i]) % MOD;
b = (b + a) % MOD;
}
return (b << 16) | a;
}
static uint32_t crc32_of(const uint8_t *p, size_t n) { /* gzip trailer checksum */
uint32_t c = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
c ^= p[i];
for (int k = 0; k < 8; k++) {
c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
}
}
return c ^ 0xFFFFFFFFu;
}
/* RFC 1951 stored-block payload: BFINAL=1, BTYPE=00 + LEN/NLEN + raw data */
static size_t stored_payload(const uint8_t *in, size_t n, uint8_t *out) {
size_t o = 0;
out[o++] = 0x01;
out[o++] = (uint8_t)(n & 0xff); out[o++] = (uint8_t)(n >> 8);
out[o++] = (uint8_t)(~n & 0xff); out[o++] = (uint8_t)((~n >> 8) & 0xff);
memcpy(out + o, in, n); o += n;
return o;
}
int main(void) {
const char *s = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
size_t sn = strlen(s);
uint8_t payload[128], raw[128], zlb[128], gzp[128];
size_t pn = stored_payload((const uint8_t *)s, sn, payload);
/* raw deflate: payload only */
memcpy(raw, payload, pn);
/* zlib: 0x78 0x9c header + payload + big-endian adler32 trailer */
size_t zn = 0;
zlb[zn++] = 0x78; zlb[zn++] = 0x9c;
memcpy(zlb + zn, payload, pn); zn += pn;
uint32_t ad = adler32_of((const uint8_t *)s, sn);
zlb[zn++] = (uint8_t)(ad >> 24); zlb[zn++] = (uint8_t)(ad >> 16);
zlb[zn++] = (uint8_t)(ad >> 8); zlb[zn++] = (uint8_t)ad;
/* gzip: 10-byte header + payload + little-endian crc32/isize trailer */
size_t gn = 0;
gzp[gn++] = 0x1f; gzp[gn++] = 0x8b; gzp[gn++] = 8; gzp[gn++] = 0;
memset(gzp + gn, 0, 4); gn += 4;
gzp[gn++] = 0; gzp[gn++] = 3;
memcpy(gzp + gn, payload, pn); gn += pn;
uint32_t c = crc32_of((const uint8_t *)s, sn);
memcpy(gzp + gn, &c, 4); gn += 4;
uint32_t is = (uint32_t)sn;
memcpy(gzp + gn, &is, 4); gn += 4;
printf("input: %zu\n", sn);
printf("raw deflate: %zu\n", pn);
printf("zlib format: %zu\n", zn);
printf("gzip format: %zu\n", gn);
printf("overhead order: %s\n", pn < zn && zn < gn ? "ok" : "bad");
/* validate each wrapper's header/trailer fields (the stored payload IS the original data) */
size_t len = (size_t)raw[1] | ((size_t)raw[2] << 8);
int ok = len == sn
&& zlb[0] == 0x78
&& crc32_of(gzp + 15, len) == crc32_of((const uint8_t *)s, sn); /* 15 = 10-byte header + 5-byte stored-block header */
printf("roundtrips: %s\n", ok ? "ok" : "bad");
return 0;
}
input: 89 raw deflate: 94 zlib format: 100 gzip format: 112 overhead order: ok roundtrips: ok
C++ C++26
#include <cstdint>
#include <cstring>
#include <iostream>
#include <string>
/* The C++ standard library has no compression (real work: zlib's deflateInit2 switches the
three formats via windowBits -15/15/31, link -lz; or boost::iostreams). Hand-write a
stored-mode payload shared by all three wrappers to show the real header-overhead ladder:
raw has no header/trailer < zlib adds 2+4 bytes < gzip adds 10+8 bytes. */
static uint32_t adler32_of(const std::string &s) { // zlib trailer checksum
uint32_t a = 1, b = 0;
const uint32_t MOD = 65521;
for (unsigned char x : s) {
a = (a + x) % MOD;
b = (b + a) % MOD;
}
return (b << 16) | a;
}
static uint32_t crc32_of(const uint8_t *p, size_t n) { // gzip trailer checksum
uint32_t c = 0xFFFFFFFFu;
for (size_t i = 0; i < n; i++) {
c ^= p[i];
for (int k = 0; k < 8; k++) {
c = (c >> 1) ^ (0xEDB88320u & (uint32_t)-(int32_t)(c & 1));
}
}
return c ^ 0xFFFFFFFFu;
}
// RFC 1951 stored-block payload: BFINAL=1, BTYPE=00 + LEN/NLEN + raw data
static std::string stored_payload(const std::string &in) {
std::string out;
unsigned short n = (unsigned short)in.size();
out += (char)0x01;
out += (char)(n & 0xff); out += (char)(n >> 8);
out += (char)(~n & 0xff); out += (char)((~n >> 8) & 0xff);
out += in;
return out;
}
int main() {
std::string s = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
std::string payload = stored_payload(s);
// raw deflate: payload only; zlib: 0x78 0x9c header + adler32 big-endian trailer;
// gzip: 10-byte header + crc32/isize little-endian trailer
std::string raw = payload;
std::string zlb = "\x78\x9c" + payload;
uint32_t ad = adler32_of(s);
for (int i = 3; i >= 0; i--) zlb += (char)((ad >> (8 * i)) & 0xff);
std::string gzp("\x1f\x8b\x08\0\0\0\0\0\0\x03", 10);
gzp += payload;
uint32_t c = crc32_of(reinterpret_cast<const uint8_t *>(s.data()), s.size());
for (int i = 0; i < 4; i++) gzp += (char)((c >> (8 * i)) & 0xff);
uint32_t is = (uint32_t)s.size();
for (int i = 0; i < 4; i++) gzp += (char)((is >> (8 * i)) & 0xff);
std::cout << "input: " << s.size() << "\n";
std::cout << "raw deflate: " << raw.size() << "\n";
std::cout << "zlib format: " << zlb.size() << "\n";
std::cout << "gzip format: " << gzp.size() << "\n";
bool order = raw.size() < zlb.size() && zlb.size() < gzp.size();
std::cout << "overhead order: " << (order ? "ok" : "bad") << "\n";
// validate each wrapper's header/trailer fields (the stored payload IS the original data)
size_t len = (unsigned char)raw[1] | ((size_t)(unsigned char)raw[2] << 8);
bool ok = len == s.size() && (unsigned char)zlb[0] == 0x78
&& crc32_of(reinterpret_cast<const uint8_t *>(gzp.data()) + 15, len) == crc32_of(reinterpret_cast<const uint8_t *>(s.data()), s.size());
std::cout << "roundtrips: " << (ok ? "ok" : "bad") << "\n";
return 0;
}
input: 89 raw deflate: 94 zlib format: 100 gzip format: 112 overhead order: ok roundtrips: ok
C# v11.0.100
using System.IO.Compression;
// three .NET types for the three container formats:
// DeflateStream = raw deflate (RFC 1951), ZLibStream = zlib (RFC 1950, .NET 6+), GZipStream = gzip (RFC 1952)
byte[] s = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."u8.ToArray();
static byte[] CompressWith(StreamFactory factory, byte[] data)
{
using var ms = new MemoryStream();
using (var w = factory(ms, CompressionMode.Compress)) w.Write(data);
return ms.ToArray();
}
byte[] raw = CompressWith((st, m) => new DeflateStream(st, CompressionLevel.Optimal, leaveOpen: true), s);
byte[] zlb = CompressWith((st, m) => new ZLibStream(st, CompressionLevel.Optimal, leaveOpen: true), s);
byte[] gzp = CompressWith((st, m) => new GZipStream(st, CompressionLevel.Optimal, leaveOpen: true), s);
Console.WriteLine($"input: {s.Length}");
Console.WriteLine($"raw deflate: {raw.Length}");
Console.WriteLine($"zlib format: {zlb.Length}");
Console.WriteLine($"gzip format: {gzp.Length}");
Console.WriteLine($"overhead order: {(raw.Length < zlb.Length && zlb.Length < gzp.Length ? "ok" : "bad")}");
static byte[] DecompressWith(StreamFactory factory, byte[] data)
{
using var r = factory(new MemoryStream(data), CompressionMode.Decompress);
using var ms = new MemoryStream();
r.CopyTo(ms);
return ms.ToArray();
}
bool ok = DecompressWith((st, m) => new DeflateStream(st, m), raw).SequenceEqual(s)
&& DecompressWith((st, m) => new ZLibStream(st, m), zlb).SequenceEqual(s)
&& DecompressWith((st, m) => new GZipStream(st, m), gzp).SequenceEqual(s);
Console.WriteLine($"roundtrips: {(ok ? "ok" : "bad")}");
delegate Stream StreamFactory(Stream inner, CompressionMode mode);
input: 89 raw deflate: 50 zlib format: 56 gzip format: 68 overhead order: ok roundtrips: ok
Go v1.27.4
package main
import (
"bytes"
"compress/flate"
"compress/gzip"
"compress/zlib"
"fmt"
"io"
)
func main() {
s := []byte("The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.")
// three standard-library packages for the three container formats:
var br, bz, bg bytes.Buffer
wr, _ := flate.NewWriter(&br, flate.BestCompression) // RFC 1951 raw deflate
wr.Write(s)
wr.Close()
wz, _ := zlib.NewWriterLevel(&bz, zlib.BestCompression) // RFC 1950 zlib
wz.Write(s)
wz.Close()
wg, _ := gzip.NewWriterLevel(&bg, gzip.BestCompression) // RFC 1952 gzip
wg.Write(s)
wg.Close()
fmt.Println("input:", len(s))
fmt.Println("raw deflate:", br.Len())
fmt.Println("zlib format:", bz.Len())
fmt.Println("gzip format:", bg.Len())
if br.Len() < bz.Len() && bz.Len() < bg.Len() {
fmt.Println("overhead order: ok")
} else {
fmt.Println("overhead order: bad")
}
// decode with the matching package: flate.Reader / zlib.Reader / gzip.Reader
fr := flate.NewReader(bytes.NewReader(br.Bytes()))
backR, _ := io.ReadAll(fr)
zr, _ := zlib.NewReader(bytes.NewReader(bz.Bytes()))
backZ, _ := io.ReadAll(zr)
gr, _ := gzip.NewReader(bytes.NewReader(bg.Bytes()))
backG, _ := io.ReadAll(gr)
ok := string(backR) == string(s) && string(backZ) == string(s) && string(backG) == string(s)
if ok {
fmt.Println("roundtrips: ok")
} else {
fmt.Println("roundtrips: bad")
}
}
input: 89 raw deflate: 50 zlib format: 56 gzip format: 68 overhead order: ok roundtrips: ok
Java v27.0.1
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
public class Main {
// the nowrap flag of Deflater/Inflater is the format switch:
// true = raw deflate (RFC 1951), false = zlib (RFC 1950); gzip (RFC 1952) uses GZIPOutputStream
static byte[] deflateWrap(byte[] data, int level, boolean nowrap) throws Exception {
Deflater def = new Deflater(level, nowrap);
def.setInput(data);
def.finish();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
while (!def.finished()) out.write(buf, 0, def.deflate(buf));
def.end();
return out.toByteArray();
}
static byte[] inflateWrap(byte[] data, boolean nowrap) throws Exception {
Inflater inf = new Inflater(nowrap);
inf.setInput(data);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
while (!inf.finished()) out.write(buf, 0, inf.inflate(buf));
inf.end();
return out.toByteArray();
}
public static void main(String[] args) throws Exception {
byte[] s = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.".getBytes(StandardCharsets.UTF_8);
byte[] raw = deflateWrap(s, Deflater.BEST_COMPRESSION, true);
byte[] zlb = deflateWrap(s, Deflater.BEST_COMPRESSION, false);
ByteArrayOutputStream gz = new ByteArrayOutputStream();
GZIPOutputStream go = new GZIPOutputStream(gz);
go.write(s);
go.close();
byte[] gzp = gz.toByteArray();
System.out.println("input: " + s.length);
System.out.println("raw deflate: " + raw.length);
System.out.println("zlib format: " + zlb.length);
System.out.println("gzip format: " + gzp.length);
System.out.println("overhead order: " + (raw.length < zlb.length && zlb.length < gzp.length ? "ok" : "bad"));
boolean ok = Arrays.equals(inflateWrap(raw, true), s)
&& Arrays.equals(inflateWrap(zlb, false), s)
&& Arrays.equals(new GZIPInputStream(new ByteArrayInputStream(gzp)).readAllBytes(), s);
System.out.println("roundtrips: " + (ok ? "ok" : "bad"));
}
}
input: 89 raw deflate: 49 zlib format: 55 gzip format: 67 overhead order: ok roundtrips: ok
JavaScript v26.13.1
// Node zlib maps one function per format: deflateRaw = raw deflate (RFC 1951),
// deflate = zlib (RFC 1950), gzip = gzip (RFC 1952)
const zlib = require("node:zlib");
const s = Buffer.from("The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.");
const raw = zlib.deflateRawSync(s, { level: 9 });
const zlb = zlib.deflateSync(s, { level: 9 });
const gzp = zlib.gzipSync(s, { level: 9 });
console.log(`input: ${s.length}`);
console.log(`zlib adds +${zlb.length - raw.length} over raw (2-byte header + 4-byte adler32)`);
console.log(`gzip adds +${gzp.length - zlb.length} over zlib (10-byte header + 8-byte trailer)`);
console.log(`overhead order: ${raw.length < zlb.length && zlb.length < gzp.length ? "ok" : "bad"}`);
// decoding must use the same family: inflateRawSync / inflateSync / gunzipSync
const ok = zlib.inflateRawSync(raw).equals(s) && zlib.inflateSync(zlb).equals(s) && zlib.gunzipSync(gzp).equals(s);
console.log(`roundtrips: ${ok ? "ok" : "bad"}`);
input: 89 zlib adds +6 over raw (2-byte header + 4-byte adler32) gzip adds +12 over zlib (10-byte header + 8-byte trailer) overhead order: ok roundtrips: ok
PHP v8.6.0
$s = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
// One deflate algorithm, three container formats:
$raw = gzdeflate($s); // RFC 1951 raw deflate: no header/trailer, smallest
$zlib = gzcompress($s); // RFC 1950 zlib: 2-byte header (78 9c) + 4-byte adler32
$gzip = gzencode($s); // RFC 1952 gzip: 10-byte header (magic 1f 8b) + 8-byte crc32/isize
echo "input: ", strlen($s), "\n";
echo "zlib adds +", strlen($zlib) - strlen($raw), " over raw (2-byte header + 4-byte adler32)\n";
echo "gzip adds +", strlen($gzip) - strlen($zlib), " over zlib (10-byte header + 8-byte trailer)\n";
echo "overhead order: ", strlen($raw) < strlen($zlib) && strlen($zlib) < strlen($gzip) ? "ok" : "bad", "\n";
// each format decodes only with its own counterpart function
echo "roundtrips: ", gzinflate($raw) === $s && gzuncompress($zlib) === $s && gzdecode($gzip) === $s ? "ok" : "bad";
input: 89 zlib adds +6 over raw (2-byte header + 4-byte adler32) gzip adds +12 over zlib (10-byte header + 8-byte trailer) overhead order: ok roundtrips: ok
Python v3.15.2
import zlib
s = b"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog."
# The wbits window parameter is the format switch: -15 = raw deflate (RFC 1951),
# 15 = zlib (RFC 1950), 31 = gzip (RFC 1952)
def wrap(data: bytes, wbits: int) -> bytes:
c = zlib.compressobj(9, zlib.DEFLATED, wbits)
return c.compress(data) + c.flush()
raw = wrap(s, -15)
zlb = wrap(s, 15)
gzp = wrap(s, 31)
print(f"input: {len(s)}")
print(f"zlib adds +{len(zlb) - len(raw)} over raw (2-byte header + 4-byte adler32)")
print(f"gzip adds +{len(gzp) - len(zlb)} over zlib (10-byte header + 8-byte trailer)")
print(f"overhead order: {'ok' if len(raw) < len(zlb) < len(gzp) else 'bad'}")
# decoding takes the same wbits value
ok = (zlib.decompress(raw, -15) == s
and zlib.decompress(zlb, 15) == s
and zlib.decompress(gzp, 31) == s)
print(f"roundtrips: {'ok' if ok else 'bad'}")
input: 89 zlib adds +6 over raw (2-byte header + 4-byte adler32) gzip adds +12 over zlib (10-byte header + 8-byte trailer) overhead order: ok roundtrips: ok
Rust v1.99.1
// Rust's standard library has no compression (flate2 in real projects: DeflateEncoder /
// ZlibEncoder / GzEncoder cover all three formats). Hand-write a stored-mode (BTYPE=00) payload
// shared by all three wrappers to show the real header-overhead ladder:
// raw has no header/trailer < zlib adds 2+4 bytes < gzip adds 10+8 bytes.
fn adler32_of(data: &[u8]) -> u32 {
const MOD: u32 = 65521;
let mut a: u32 = 1;
let mut b: u32 = 0;
for &x in data {
a = (a + x as u32) % MOD;
b = (b + a) % MOD;
}
(b << 16) | a
}
fn crc32_of(data: &[u8]) -> u32 {
let mut c: u32 = 0xFFFF_FFFF;
for &b in data {
c ^= b as u32;
for _ in 0..8 {
c = if c & 1 == 1 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 };
}
}
!c
}
// RFC 1951 stored-block payload (BFINAL=1, BTYPE=00 + LEN/NLEN + raw data)
fn stored_payload(data: &[u8]) -> Vec<u8> {
let n = data.len();
let mut out = vec![0x01u8];
out.extend_from_slice(&(n as u16).to_le_bytes());
out.extend_from_slice(&(!(n as u16)).to_le_bytes());
out.extend_from_slice(data);
out
}
fn main() {
let s: &[u8] = b"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
let payload = stored_payload(s);
// raw deflate: payload only; zlib: 0x78 0x9c header + adler32 trailer; gzip: 10-byte header + crc32/isize trailer
let raw = payload.clone();
let mut zlb = vec![0x78, 0x9c];
zlb.extend_from_slice(&payload);
zlb.extend_from_slice(&adler32_of(s).to_be_bytes());
let mut gzp = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3];
gzp.extend_from_slice(&payload);
gzp.extend_from_slice(&crc32_of(s).to_le_bytes());
gzp.extend_from_slice(&(s.len() as u32).to_le_bytes());
println!("input: {}", s.len());
println!("raw deflate: {}", raw.len());
println!("zlib format: {}", zlb.len());
println!("gzip format: {}", gzp.len());
println!("overhead order: {}", if raw.len() < zlb.len() && zlb.len() < gzp.len() { "ok" } else { "bad" });
// validate each wrapper's header/trailer fields (the stored payload IS the original data)
let len = u16::from_le_bytes([raw[1], raw[2]]) as usize;
let ok = len == s.len()
&& zlb[0] == 0x78 && u32::from_be_bytes([zlb[zlb.len() - 4], zlb[zlb.len() - 3], zlb[zlb.len() - 2], zlb[zlb.len() - 1]]) == adler32_of(s)
&& gzp[0] == 0x1f && gzp[1] == 0x8b && crc32_of(&gzp[15..15 + len]) == crc32_of(s); // 15 = 10-byte header + 5-byte stored-block header
println!("roundtrips: {}", if ok { "ok" } else { "bad" });
}
input: 89 raw deflate: 94 zlib format: 100 gzip format: 112 overhead order: ok roundtrips: ok
TypeScript v26.13.1
// Node zlib maps one function per format: deflateRaw = raw deflate (RFC 1951),
// deflate = zlib (RFC 1950), gzip = gzip (RFC 1952)
import { deflateRawSync, deflateSync, gzipSync, gunzipSync, inflateRawSync, inflateSync } from "node:zlib";
const s: Buffer = Buffer.from("The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.");
const raw: Buffer = deflateRawSync(s, { level: 9 });
const zlb: Buffer = deflateSync(s, { level: 9 });
const gzp: Buffer = gzipSync(s, { level: 9 });
console.log(`input: ${s.length}`);
console.log(`zlib adds +${zlb.length - raw.length} over raw (2-byte header + 4-byte adler32)`);
console.log(`gzip adds +${gzp.length - zlb.length} over zlib (10-byte header + 8-byte trailer)`);
console.log(`overhead order: ${raw.length < zlb.length && zlb.length < gzp.length ? "ok" : "bad"}`);
// decoding must use the same family: inflateRawSync / inflateSync / gunzipSync
const ok: boolean = inflateRawSync(raw).equals(s) && inflateSync(zlb).equals(s) && gunzipSync(gzp).equals(s);
console.log(`roundtrips: ${ok ? "ok" : "bad"}`);
input: 89 zlib adds +6 over raw (2-byte header + 4-byte adler32) gzip adds +12 over zlib (10-byte header + 8-byte trailer) overhead order: ok roundtrips: ok
Language differences
The full family map: gzdeflate/gzinflate (RFC 1951 raw deflate, no header/trailer), gzcompress/gzuncompress (RFC 1950 zlib, 2-byte header 78 9c + 4-byte adler32), gzencode/gzdecode (RFC 1952 gzip, 10-byte header 1f 8b + 8-byte crc32/isize) — one deflate algorithm in three containers; decode with the matching counterpart or you get "unknown compression method".
Measured header overhead (89-byte sample, local PHP/Python/JS/Java): raw=49 < zlib=55 < gzip=67; Go/C# ship their own deflate and run slightly larger (50/56/68) but the ordering holds.
The wbits window parameter is the format switch: Python compressobj(wbits=-15/15/31), C zlib deflateInit2(windowBits=-15/15/31), Java Deflater/Inflater(nowrap), JS deflateRaw/deflate/gzip trio, .NET DeflateStream/ZLibStream/GZipStream, Go compress/flate+zlib+gzip packages, Rust flate2's three encoders.
C/C++/Rust have no compression in their standard libraries: the example hand-writes one stored-mode payload and only adds the three wrappers' headers/trailers, reproducing the overhead ladder for real (94/100/112) and validating every header field.
On the PHP side, the streaming incremental API deflate_init(ZLIB_ENCODING_RAW/DEFLATE/GZIP) + deflate_add follows the same wbits-switch idea.