crossbind
GitHub
← 所有库

zlib

DEFLATE 压缩。

安装

在浏览器中运行;Node.js 和边缘运行环境也使用同一个包。构建目标:wasm32,单线程和多线程。

shell
npm install @crossbind/port-zlib-wasm@beta
crossbind.config.js
import zlibWasm from '@crossbind/port-zlib-wasm/crossbind.config.js';
 
export default {
dependencies: [zlibWasm],
paths: { config: import.meta.url },
};
main.js
import { initNative, zlibVersion } from '@crossbind/port-zlib/zlib.h';
 
await initNative();

crossbind 本身随你的打包工具插件一起提供;打包工具插件介绍了 Vite、Webpack、Rspack、Rsbuild、Rollup、esbuild、Bun 和 Next.js 的用法。

在浏览器中运行 zlib,提供 CompressionStream 所缺少的控制选项

浏览器用 CompressionStream 进行 gzip 压缩和解压,但它不接受压缩级别、字典和头字段,而且只能从第一个字节开始。这些应用运行由 crossbind 编译的上游 zlib 1.4:它们能直接跳到大型 .gz 文件的中间,在不改动任何像素的情况下缩小 PNG,并逐个条目地读取基于 ZIP 的文件。 首次运行时会下载一次 0.5 MB 的 WebAssembly;本页的所有应用都共用它,而且不会上传任何内容。

应用 01

无需解压,直接跳到大型 .gz 文件的中间

gzip 没有索引,所以每个读取器(包括浏览器的 DecompressionStream)都必须从第一个字节开始解压,才能读到中间部分。只要知道某个 deflate 块精确到位的位置,以及它之前的 32 KB 文本,zlib 就能从这个块开始解压。只需扫描一遍,大约每隔 1 MB 记录一次这些信息,之后读取任意一行都只需几毫秒。这正是 zlib 附带的示例 zran.c 所用的技术;而 zlib 的 JavaScript 移植版 pako 省略了这项技术所依赖的 inflatePrime 调用。

日志在模块中生成,每行 64 字节,并以级别 6 进行 gzip 压缩。你自己的文件只保留在这个标签页中:它会被复制到模块的内存中,绝不会上传。

生成一份日志,或者为你自己的 .gz 建立索引,然后读取其中的任意行或偏移量。
查看代码
src/support/gzip_index.h
// src/support/gzip_index.h (excerpt): start inflating at an access point
if (fseeko(in, point.in - (point.bits ? 1 : 0), SEEK_SET) == -1) throw std::runtime_error("cannot seek in the file");
int ch = 0;
if (point.bits && (ch = std::getc(in)) == EOF) throw std::runtime_error("the file is shorter than its index");
z_stream strm{};
if (inflateInit2(&strm, RAW) != Z_OK) throw std::runtime_error("inflateInit2 failed");
Stream end(&strm, inflateEnd);
if (point.bits) inflatePrime(&strm, point.bits, ch >> (8 - point.bits));
if (!point.window.empty()) inflateSetDictionary(&strm, point.window.data(), static_cast<uInt>(point.window.size()));
main.js
const m = await initNative();
const path = '/memfs/zlibapps/access.log.gz';
await m.SeekableGzip.writeLog(path, 250000, 6); // 16,000,000 B of log, 3,001,352 B of gzip
const gz = await new m.SeekableGzip(path, 1024); // one pass: 14 access points
 
const line = await gz.read((123456 - 1) * 64, 63);
// '0123456 2026-01-01T08:34:23Z GET /api/items/49264 200 0628ms'
await gz.lastDecoded(); // 864,773 B decompressed to get it
await gz.readFromStart((123456 - 1) * 64, 63);
await gz.lastDecoded(); // 7,901,183 B without the index
应用 02

不改动一个像素,让 PNG 变小

PNG 的像素就是 zlib 数据:每一行都先经过过滤,也就是根据周围的行进行预测,然后所有行再经过 deflate 压缩。这个应用会以 zlib 的最高级别尝试文件自身的过滤器和另外五种过滤器,保留最小的结果,并原样复制其他所有数据块。浏览器不会给你这样的控制:canvas.toBlob 只对 JPEG 这类质量可变的格式接受质量参数,所以 PNG 怎么输出完全取决于它的编码器。结果会被再次解码并进行比较:在 C++ 中逐行比较,在这个浏览器中逐像素比较。

示例是模块绘制的一张图表,并像快速编码器那样保存:不进行过滤,使用 zlib 级别 1。绘制的 PNG 来自这个浏览器的 canvas 编码器,所以它的数字取决于浏览器。大图像需要几秒钟:每次尝试都要对整张图像进行 deflate 压缩。

压缩示例、这个浏览器绘制的 PNG 或你自己的 PNG,并比较尝试过的每种过滤器和策略。
查看代码
src/native/png_squeezer.h
// src/native/png_squeezer.h (excerpt): the file's own rows, five filter choices, then the winner with Z_FILTERED
attempt(6, found, Z_DEFAULT_STRATEGY);
const size_t foundSize = best.size();
for (int method : {0, 1, 2, 4, 5}) {
const std::string rows = pngfile::filter(image, raw, method);
if (rows == found) record(method, Z_DEFAULT_STRATEGY, foundSize, 0, true);
else attempt(method, rows, Z_DEFAULT_STRATEGY);
}
attempt(bestFilter, std::string(bestRows), Z_FILTERED);
main.js
const m = await initNative();
const [path] = await m.autoMountFiles([file], await m.getRandomPath('/memfs')); // a PNG from <input type="file">
const report = JSON.parse(await m.PngSqueezer.optimize(path, path + '.min.png'));
// the sample chart: report.original 17191, report.bytes 4989 (up filter, level 9)
await m.PngSqueezer.samePixels(path, path + '.min.png'); // true
const smaller = await m.getFileBytes(path + '.min.png');
应用 03

无需解包,查看 .zip、.docx 或 .xlsx 的内部

ZIP 就是一串 deflate 流,末尾再加上一个目录;Word、Excel、EPUB 和 Java 文件也都是 ZIP。zlib 没有 ZIP API,这个构建也没有包含它的 contrib/minizip,但它具备两个关键部分:原始 inflate 和 CRC-32。在此之上的几百行 C++ 代码会读取目录,按需 inflate 单个条目,并像 unzip -t 那样检查每个校验和。

示例是模块自己写出的一个包含四个条目的归档。你自己的文件只保留在这个标签页中:它会被复制到模块的内存中,绝不会上传。经过加密或者用 deflate 以外的方法压缩的条目,只会列出,不会打开。

打开示例,或者你自己的 .zip、.docx、.xlsx 或 .epub 文件,列出其中的条目并读取任意一个。
查看代码
src/support/zip_format.h
// src/support/zip_format.h (excerpt): one entry, inflated as raw deflate
z_stream strm{};
if (inflateInit2(&strm, -15) != Z_OK) throw std::runtime_error("inflateInit2 failed"); // raw deflate: no zlib header
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&strm, inflateEnd);
int ret = Z_OK;
do {
if (strm.avail_in == 0) {
const size_t count = std::fread(input.data(), 1, static_cast<size_t>(std::min<uint64_t>(CHUNK, left)), file);
if (count == 0) throw std::runtime_error("its deflate data ends early");
left -= count;
strm.next_in = input.data();
strm.avail_in = static_cast<uInt>(count);
}
strm.next_out = output.data();
strm.avail_out = static_cast<uInt>(CHUNK);
ret = inflate(&strm, Z_NO_FLUSH);
if (ret != Z_OK && ret != Z_STREAM_END) throw std::runtime_error(strm.msg ? strm.msg : "its deflate data is corrupt");
if (!deliver(output.data(), CHUNK - strm.avail_out)) return result;
} while (ret != Z_STREAM_END);
main.js
const m = await initNative();
const [path] = await m.autoMountFiles([file], await m.getRandomPath('/memfs')); // a .zip, .docx, .xlsx, .epub, .jar...
const { entries } = JSON.parse(await m.ZipReader.list(path));
const entry = JSON.parse(await m.ZipReader.read(path, entries[0].name, 4096));
entry.crcOk; // true: inflated and checked
const report = JSON.parse(await m.ZipReader.test(path)); // every CRC-32, as unzip -t does

示例

每个示例都由一个小小的 C++ 头文件和调用它的 JavaScript 组成,并附有构建本站时它输出的内容。仅 JavaScript 标签页直接使用 zlib 自己的头文件完成同样的事,不需要 C++ 文件。最后一个是为 WASI 构建的完整 C++ 程序。

压缩和解压缓冲区

大多数 zlib 代码都会用到的两个调用:以指定级别调用 compress2,以及用调用方保存的原始大小调用 uncompress。

src/native/zlib_codec.h
#pragma once
 
#include <zlib.h>
 
#include <stdexcept>
#include <string>
 
// One-shot zlib: compress2 and uncompress, in the zlib format (RFC 1950). Bytes cross the binding as
// a byte string: one UTF-16 code unit (0-255) per byte.
class Zlib {
public:
static std::string version() { return zlibVersion(); }
 
static std::u16string compress(const std::string& text, int level) {
uLongf size = compressBound(static_cast<uLong>(text.size()));
std::string out(size, '\0');
const int status = compress2(reinterpret_cast<Bytef*>(&out[0]), &size, reinterpret_cast<const Bytef*>(text.data()), static_cast<uLong>(text.size()), level);
if (status != Z_OK) throw std::runtime_error(status == Z_STREAM_ERROR ? "level must be between -1 and 9" : zError(status));
std::u16string bytes(size, u'\0');
for (uLongf i = 0; i < size; ++i) bytes[i] = static_cast<unsigned char>(out[i]);
return bytes;
}
 
// The zlib format does not record the original size, so the caller keeps it next to the data.
static std::string decompress(const std::u16string& bytes, int originalSize) {
if (originalSize < 0 || originalSize > (256 << 20)) throw std::invalid_argument("originalSize must be between 0 and 256 MiB");
std::string in(bytes.size(), '\0');
for (size_t i = 0; i < bytes.size(); ++i) {
if (bytes[i] > 0xFF) throw std::invalid_argument("not a byte string");
in[i] = static_cast<char>(bytes[i]);
}
std::string out(static_cast<size_t>(originalSize), '\0');
uLongf size = static_cast<uLongf>(out.size());
const int status = uncompress(reinterpret_cast<Bytef*>(&out[0]), &size, reinterpret_cast<const Bytef*>(in.data()), static_cast<uLong>(in.size()));
if (status == Z_BUF_ERROR) throw std::runtime_error("the data is larger than originalSize");
if (status != Z_OK) throw std::runtime_error(status == Z_DATA_ERROR ? "corrupt or incomplete zlib data" : zError(status));
out.resize(size);
return out;
}
};
main.js
import { initNative, Zlib } from './native/zlib_codec.h';
 
await initNative();
const text = 'crossbind '.repeat(100);
const packed = await Zlib.compress(text, 9);
const bytes = Uint8Array.from(packed, (c) => c.charCodeAt(0));
console.log(await Zlib.version(), bytes.length, [...bytes.slice(0, 2)].map((b) => b.toString(16)).join(' '));
console.log((await Zlib.decompress(packed, text.length)) === text);
输出首次运行需下载 0.5 MB
1.4 27 78 da
true

写入一个记住自身文件名的 .gz

windowBits 为 15 + 16 的 deflateInit2 会写出 gzip 而不是 zlib 格式,deflateSetHeader 会填写 gunzip -N 恢复的头字段。inflateGetHeader 会把它们读回来。

src/native/gzip_header.h
#pragma once
 
#include <zlib.h>
 
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
 
// gzip (RFC 1952) with the header fields gunzip -N restores: the original file name and the
// modification time. Bytes cross the binding as a byte string: one UTF-16 code unit (0-255) per byte.
class Gzip {
public:
static std::u16string compress(const std::string& data, const std::string& name, double mtime, int level) {
z_stream stream{};
// windowBits 15 + 16: a 32 KiB window, and the gzip wrapper instead of the zlib one.
if (deflateInit2(&stream, level, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw std::invalid_argument("level must be between -1 and 9");
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, deflateEnd);
gz_header header{};
header.name = reinterpret_cast<Bytef*>(const_cast<char*>(name.c_str()));
header.time = static_cast<uLong>(mtime);
header.os = 3; // Unix
deflateSetHeader(&stream, &header);
std::string out(deflateBound(&stream, static_cast<uLong>(data.size())), '\0');
stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(data.data()));
stream.avail_in = static_cast<uInt>(data.size());
stream.next_out = reinterpret_cast<Bytef*>(&out[0]);
stream.avail_out = static_cast<uInt>(out.size());
if (deflate(&stream, Z_FINISH) != Z_STREAM_END) throw std::runtime_error("deflate did not finish");
std::u16string bytes(stream.total_out, u'\0');
for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = static_cast<unsigned char>(out[i]);
return bytes;
}
 
static std::string fileName(const std::u16string& gz) {
std::string name;
uLong mtime = 0;
readHeader(gz, name, mtime);
return name;
}
 
// Seconds since 1970-01-01T00:00:00Z.
static double modified(const std::u16string& gz) {
std::string name;
uLong mtime = 0;
readHeader(gz, name, mtime);
return static_cast<double>(mtime);
}
 
static std::string decompress(const std::u16string& gz) {
std::string in = fromUnits(gz);
z_stream stream{};
if (inflateInit2(&stream, 15 + 32) != Z_OK) throw std::runtime_error("inflateInit2 failed"); // + 32: gzip or zlib, from the header
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, inflateEnd);
stream.next_in = reinterpret_cast<Bytef*>(&in[0]);
stream.avail_in = static_cast<uInt>(in.size());
std::string out;
std::vector<char> chunk(64 << 10);
int status = Z_OK;
while (status != Z_STREAM_END) {
stream.next_out = reinterpret_cast<Bytef*>(chunk.data());
stream.avail_out = static_cast<uInt>(chunk.size());
status = inflate(&stream, Z_NO_FLUSH);
if (status != Z_OK && status != Z_STREAM_END) throw std::runtime_error(stream.msg ? stream.msg : "truncated or corrupt input");
out.append(chunk.data(), chunk.size() - stream.avail_out);
if (out.size() > (256u << 20)) throw std::runtime_error("refusing to decompress more than 256 MiB");
}
return out;
}
 
private:
static std::string fromUnits(const std::u16string& units) {
std::string bytes(units.size(), '\0');
for (size_t i = 0; i < units.size(); ++i) {
if (units[i] > 0xFF) throw std::invalid_argument("not a byte string");
bytes[i] = static_cast<char>(units[i]);
}
return bytes;
}
 
// inflateGetHeader fills the fields while inflate reads the header; Z_BLOCK stops right after it.
static void readHeader(const std::u16string& gz, std::string& name, uLong& mtime) {
std::string in = fromUnits(gz);
z_stream stream{};
if (inflateInit2(&stream, 15 + 16) != Z_OK) throw std::runtime_error("inflateInit2 failed"); // + 16: gzip only
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, inflateEnd);
std::vector<Bytef> nameBuffer(1024, 0);
gz_header header{};
header.name = nameBuffer.data();
header.name_max = static_cast<uInt>(nameBuffer.size() - 1);
inflateGetHeader(&stream, &header);
Bytef output = 0;
stream.next_in = reinterpret_cast<Bytef*>(&in[0]);
stream.avail_in = static_cast<uInt>(in.size());
stream.next_out = &output;
stream.avail_out = 1;
const int status = inflate(&stream, Z_BLOCK);
if ((status != Z_OK && status != Z_STREAM_END) || header.done != 1) throw std::runtime_error(stream.msg ? stream.msg : "not a complete gzip header");
name = reinterpret_cast<const char*>(nameBuffer.data());
mtime = header.time;
}
};
main.js
import { initNative, Gzip } from './native/gzip_header.h';
 
await initNative();
const rows = Array.from({ length: 200 }, (_, i) => `${i + 1},sensor-${i % 4},${18 + ((i * 7) % 9)}`);
const csv = ['reading,sensor,celsius', ...rows].join('\n') + '\n';
const gz = await Gzip.compress(csv, 'readings.csv', Date.UTC(2026, 0, 1) / 1000, 9);
const bytes = Uint8Array.from(gz, (c) => c.charCodeAt(0));
console.log(`${csv.length} B -> ${bytes.length} B, starts ${bytes[0].toString(16)} ${bytes[1].toString(16)}`);
console.log(await Gzip.fileName(gz), new Date((await Gzip.modified(gz)) * 1000).toISOString());
console.log((await Gzip.decompress(gz)) === csv);
输出首次运行需下载 0.5 MB
3115 B -> 747 B, starts 1f 8b
readings.csv 2026-01-01T00:00:00.000Z
true

以流的方式用 gzip 处理文件

适用于不应一次性放进一个缓冲区的数据:zlib 自带示例 zpipe.c 中的 deflate() 和 inflate() 循环,以 64 KB 为一步,从文件到文件进行处理。

src/native/gzip_stream.h
#pragma once
 
#include <zlib.h>
 
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
 
// Streaming gzip, file to file, in 64 KiB steps: the deflate() and inflate() loops of zlib's own
// examples/zpipe.c, with windowBits 15 + 16 for gzip. Memory stays at two buffers whatever the size.
class GzipStream {
public:
// Returns the compressed size.
static double compressFile(const std::string& input, const std::string& output, int level) {
File in = open(input, "rb");
File out = open(output, "wb");
z_stream stream{};
if (deflateInit2(&stream, level, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw std::invalid_argument("level must be between -1 and 9");
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, deflateEnd);
std::vector<unsigned char> source(CHUNK);
std::vector<unsigned char> target(CHUNK);
double written = 0;
int flush = Z_NO_FLUSH;
do {
stream.avail_in = static_cast<uInt>(std::fread(source.data(), 1, CHUNK, in.get()));
if (std::ferror(in.get())) throw std::runtime_error("cannot read " + input);
flush = std::feof(in.get()) ? Z_FINISH : Z_NO_FLUSH;
stream.next_in = source.data();
do {
stream.avail_out = CHUNK;
stream.next_out = target.data();
deflate(&stream, flush);
written += write(out.get(), target.data(), CHUNK - stream.avail_out);
} while (stream.avail_out == 0);
} while (flush != Z_FINISH);
return written;
}
 
// Returns the decompressed size. Reads every member of a concatenated .gz, as gunzip does.
static double decompressFile(const std::string& input, const std::string& output) {
File in = open(input, "rb");
File out = open(output, "wb");
z_stream stream{};
if (inflateInit2(&stream, 15 + 32) != Z_OK) throw std::runtime_error("inflateInit2 failed"); // + 32: gzip or zlib
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, inflateEnd);
std::vector<unsigned char> source(CHUNK);
std::vector<unsigned char> target(CHUNK);
double written = 0;
int status = Z_OK;
for (;;) {
stream.avail_in = static_cast<uInt>(std::fread(source.data(), 1, CHUNK, in.get()));
if (std::ferror(in.get())) throw std::runtime_error("cannot read " + input);
if (stream.avail_in == 0) break;
stream.next_in = source.data();
do {
if (status == Z_STREAM_END) {
if (stream.avail_in == 0) break;
inflateReset(&stream); // another member follows
}
stream.avail_out = CHUNK;
stream.next_out = target.data();
status = inflate(&stream, Z_NO_FLUSH);
if (status == Z_NEED_DICT || status == Z_DATA_ERROR || status == Z_MEM_ERROR) throw std::runtime_error(stream.msg ? stream.msg : "corrupt input");
written += write(out.get(), target.data(), CHUNK - stream.avail_out);
} while (stream.avail_out == 0 || (status == Z_STREAM_END && stream.avail_in > 0));
}
if (status != Z_STREAM_END) throw std::runtime_error("the input ends in the middle of a gzip member");
return written;
}
 
private:
static constexpr size_t CHUNK = 64 << 10;
using File = std::unique_ptr<FILE, int (*)(FILE*)>;
 
static File open(const std::string& path, const char* mode) {
File file(std::fopen(path.c_str(), mode), std::fclose);
if (!file) throw std::runtime_error("cannot open " + path);
return file;
}
 
static double write(FILE* file, const unsigned char* data, size_t size) {
if (size && std::fwrite(data, 1, size, file) != size) throw std::runtime_error("write failed");
return static_cast<double>(size);
}
};
main.js
import { initNative } from './native/gzip_stream.h';
 
const m = await initNative();
const { GzipStream } = m;
let seed = 42;
const random = (n) => (seed = (seed * 48271) % 2147483647) % n;
const lines = Array.from({ length: 50000 }, (_, i) => `2026-09-24T12:00:${String(i % 60).padStart(2, '0')}Z GET /api/items/${random(9000)} ${random(10) ? 200 : 404} ${random(900)}ms`);
// m.FS.writeFile adds to a file that already exists, so every run gets a fresh directory.
const dir = await m.getRandomPath('/memfs');
await m.FS.writeFile(`${dir}/access.log`, lines.join('\n'));
 
const packed = await GzipStream.compressFile(`${dir}/access.log`, `${dir}/access.log.gz`, 6);
const unpacked = await GzipStream.decompressFile(`${dir}/access.log.gz`, `${dir}/access.copy.log`);
const original = await m.getFileBytes(`${dir}/access.log`);
const copy = await m.getFileBytes(`${dir}/access.copy.log`);
console.log(`${original.length} B -> ${packed} B -> ${unpacked} B`);
console.log(copy.length === original.length && copy.every((byte, i) => byte === original[i]));
输出首次运行需下载 0.5 MB
2537578 B -> 363636 B -> 2537578 B
true

用预设字典压缩短消息

短消息中可供回溯引用的内容很少。用 deflateSetDictionary 和 inflateSetDictionary 载入之前的消息,每条新消息都会参照它们进行压缩。

src/native/zlib_dictionary.h
#pragma once
 
#include <zlib.h>
 
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
 
// Raw deflate (RFC 1951, no header or checksum) with a preset dictionary: both sides load the same
// bytes first, so a short message can point back at strings it never contained. An empty dictionary
// gives plain raw deflate.
class ZlibDictionary {
public:
ZlibDictionary(const std::string& dictionary, int level) : dictionary(dictionary), level(level) {}
 
std::u16string compress(const std::string& message) const {
z_stream stream{};
// windowBits -15: raw deflate with a 32 KiB window.
if (deflateInit2(&stream, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) throw std::invalid_argument("level must be between -1 and 9");
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, deflateEnd);
if (!dictionary.empty()) deflateSetDictionary(&stream, reinterpret_cast<const Bytef*>(dictionary.data()), static_cast<uInt>(dictionary.size()));
std::string out(deflateBound(&stream, static_cast<uLong>(message.size())), '\0');
stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(message.data()));
stream.avail_in = static_cast<uInt>(message.size());
stream.next_out = reinterpret_cast<Bytef*>(&out[0]);
stream.avail_out = static_cast<uInt>(out.size());
if (deflate(&stream, Z_FINISH) != Z_STREAM_END) throw std::runtime_error("deflate did not finish");
std::u16string bytes(stream.total_out, u'\0');
for (size_t i = 0; i < bytes.size(); ++i) bytes[i] = static_cast<unsigned char>(out[i]);
return bytes;
}
 
std::string decompress(const std::u16string& bytes) const {
std::string in(bytes.size(), '\0');
for (size_t i = 0; i < bytes.size(); ++i) {
if (bytes[i] > 0xFF) throw std::invalid_argument("not a byte string");
in[i] = static_cast<char>(bytes[i]);
}
z_stream stream{};
if (inflateInit2(&stream, -15) != Z_OK) throw std::runtime_error("inflateInit2 failed");
std::unique_ptr<z_stream, int (*)(z_stream*)> end(&stream, inflateEnd);
// Raw deflate carries no dictionary ID, so the dictionary goes in before the first inflate().
if (!dictionary.empty()) inflateSetDictionary(&stream, reinterpret_cast<const Bytef*>(dictionary.data()), static_cast<uInt>(dictionary.size()));
stream.next_in = reinterpret_cast<Bytef*>(&in[0]);
stream.avail_in = static_cast<uInt>(in.size());
std::string out;
std::vector<char> chunk(16 << 10);
int status = Z_OK;
while (status != Z_STREAM_END) {
stream.next_out = reinterpret_cast<Bytef*>(chunk.data());
stream.avail_out = static_cast<uInt>(chunk.size());
status = inflate(&stream, Z_NO_FLUSH);
if (status != Z_OK && status != Z_STREAM_END) throw std::runtime_error(stream.msg ? stream.msg : "truncated or corrupt input");
out.append(chunk.data(), chunk.size() - stream.avail_out);
if (out.size() > (1u << 20)) throw std::runtime_error("a message above 1 MiB is not a small message");
}
return out;
}
 
private:
std::string dictionary;
int level;
};
main.js
import { initNative, ZlibDictionary } from './native/zlib_dictionary.h';
 
await initNative();
const event = (i) => `{"event":"click","user":${1000 + ((i * 37) % 900)},"page":"/products/${i % 12}","ms":${(i * 7919) % 400}}`;
const dictionary = Array.from({ length: 20 }, (_, i) => event(i)).join('\n');
const plain = await new ZlibDictionary('', 9);
const primed = await new ZlibDictionary(dictionary, 9);
 
const message = event(4321);
const alone = await plain.compress(message);
const packed = await primed.compress(message);
console.log(`dictionary: ${dictionary.length} B`);
console.log(`${message.length} B message: ${alone.length} B alone, ${packed.length} B with the dictionary`);
console.log((await primed.decompress(packed)) === message);
输出首次运行需下载 0.5 MB
dictionary: 1195 B
59 B message: 59 B alone, 11 B with the dictionary
true

分段计算数据的校验和

crc32 和 adler32 可以在多个分段之间延续累计值,crc32_combine 和 adler32_combine 则可以合并分别计算出的各段校验和。

src/native/zlib_checksum.h
#pragma once
 
#include <zlib.h>
 
#include <string>
 
// CRC-32 (what gzip, ZIP and PNG store) and Adler-32 (what the zlib format stores). A running value
// continues across pieces, and two values combine into the checksum of the joined data, so pieces can
// be checksummed separately, in any order.
class Checksum {
public:
static unsigned int crc32(const std::string& data) { return crc32Update(0, data); }
static unsigned int adler32(const std::string& data) { return adler32Update(1, data); }
 
static unsigned int crc32Update(unsigned int crc, const std::string& data) {
return static_cast<unsigned int>(::crc32(crc, reinterpret_cast<const Bytef*>(data.data()), static_cast<uInt>(data.size())));
}
 
static unsigned int adler32Update(unsigned int adler, const std::string& data) {
return static_cast<unsigned int>(::adler32(adler, reinterpret_cast<const Bytef*>(data.data()), static_cast<uInt>(data.size())));
}
 
// The checksum of first + second, from the two checksums and the length of second in bytes.
static unsigned int crc32Combine(unsigned int first, unsigned int second, double secondLength) {
return static_cast<unsigned int>(::crc32_combine(first, second, static_cast<z_off_t>(secondLength)));
}
 
static unsigned int adler32Combine(unsigned int first, unsigned int second, double secondLength) {
return static_cast<unsigned int>(::adler32_combine(first, second, static_cast<z_off_t>(secondLength)));
}
};
main.js
import { initNative, Checksum } from './native/zlib_checksum.h';
 
await initNative();
const hex = (value) => value.toString(16).padStart(8, '0');
const text = 'The quick brown fox jumps over the lazy dog';
console.log(`crc32 ${hex(await Checksum.crc32(text))}, adler32 ${hex(await Checksum.adler32(text))}`);
 
const [head, tail] = ['The quick brown fox ', 'jumps over the lazy dog'];
const running = await Checksum.crc32Update(await Checksum.crc32(head), tail);
const combined = await Checksum.crc32Combine(await Checksum.crc32(head), await Checksum.crc32(tail), tail.length);
const adler = await Checksum.adler32Combine(await Checksum.adler32(head), await Checksum.adler32(tail), tail.length);
console.log(`running crc32 ${hex(running)}, combined crc32 ${hex(combined)}, combined adler32 ${hex(adler)}`);
输出首次运行需下载 0.5 MB
crc32 414fa339, adler32 5bdc0fda
running crc32 414fa339, combined crc32 414fa339, combined adler32 5bdc0fda

gzip 命令行工具

WASI 没有 JavaScript 绑定:程序就是一个链接了该库的 main(),构建成一个 .wasm,再用 wasmtime 运行。这个程序使用 zlib 自带的 .gz 文件函数 gzopen、gzwrite 和 gzread,以 64 KB 为一步进行流式处理。

crossbind.config.js
import zlibWasi from '@crossbind/port-zlib-wasi/crossbind.config.js';
 
export default {
general: { name: 'zlib-tool' },
dependencies: [zlibWasi],
paths: { config: import.meta.url },
};
src/native/main.cpp
// A command-line gzip for WASI, on zlib's own .gz file functions:
// zlib-tool gzip <input> <output.gz> [level]
// zlib-tool gunzip <input.gz> <output>
#include <zlib.h>
 
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <string>
#include <vector>
 
namespace {
 
using File = std::unique_ptr<FILE, int (*)(FILE*)>;
 
File open(const char* path, const char* mode) {
File file(std::fopen(path, mode), std::fclose);
if (!file) std::fprintf(stderr, "cannot open %s\n", path);
return file;
}
 
long long fileSize(const char* path) {
File file = open(path, "rb");
if (!file || std::fseek(file.get(), 0, SEEK_END) != 0) return -1;
return std::ftell(file.get());
}
 
// gzwrite deflates the bytes as they arrive; gzclose finishes the stream and writes the trailer.
long long compress(const char* input, const char* output, int level) {
File in = open(input, "rb");
if (!in) return -1;
gzFile out = gzopen(output, ("wb" + std::to_string(level)).c_str());
if (!out) {
std::fprintf(stderr, "cannot create %s\n", output);
return -1;
}
std::vector<char> buffer(64 << 10);
size_t read = 0;
while ((read = std::fread(buffer.data(), 1, buffer.size(), in.get())) > 0) {
if (gzwrite(out, buffer.data(), static_cast<unsigned>(read)) != static_cast<int>(read)) {
int code = 0;
std::fprintf(stderr, "gzwrite: %s\n", gzerror(out, &code));
gzclose(out);
return -1;
}
}
if (gzclose(out) != Z_OK) {
std::fprintf(stderr, "cannot finish %s\n", output);
return -1;
}
return fileSize(output);
}
 
// gzread inflates every member of the file in turn, as gunzip does.
long long decompress(const char* input, const char* output) {
gzFile in = gzopen(input, "rb");
if (!in) {
std::fprintf(stderr, "cannot open %s\n", input);
return -1;
}
if (gzdirect(in)) { // gzread would copy a file that is not gzip; refuse it instead
std::fprintf(stderr, "%s is not a gzip file\n", input);
gzclose(in);
return -1;
}
File out = open(output, "wb");
if (!out) {
gzclose(in);
return -1;
}
std::vector<char> buffer(64 << 10);
long long written = 0;
int got = 0;
while ((got = gzread(in, buffer.data(), static_cast<unsigned>(buffer.size()))) > 0) {
if (std::fwrite(buffer.data(), 1, static_cast<size_t>(got), out.get()) != static_cast<size_t>(got)) {
std::fprintf(stderr, "cannot write %s\n", output);
gzclose(in);
return -1;
}
written += got;
}
if (got < 0) {
int code = 0;
std::fprintf(stderr, "gzread: %s\n", gzerror(in, &code));
gzclose(in);
return -1;
}
gzclose(in);
return written;
}
 
} // namespace
 
int main(int argc, char** argv) {
const bool packing = argc >= 4 && std::strcmp(argv[1], "gzip") == 0;
const bool unpacking = argc >= 4 && std::strcmp(argv[1], "gunzip") == 0;
if (!packing && !unpacking) {
std::fprintf(stderr, "usage: zlib-tool gzip <input> <output.gz> [level]\n zlib-tool gunzip <input.gz> <output>\n");
return 2;
}
const long long written = packing ? compress(argv[2], argv[3], argc >= 5 ? std::atoi(argv[4]) : 6) : decompress(argv[2], argv[3]);
if (written < 0) return 1;
std::printf("zlib %s %s: %s -> %s, %lld B written\n", zlibVersion(), argv[1], argv[2], argv[3], written);
return 0;
}
shell
npx crossbind build -p wasi -e wasi -b release
wasmtime run --dir=. .crossbind/build/zlib-tool-wasi-wasm32-st-release.wasm gzip access.log access.log.gz 6
wasmtime run --dir=. .crossbind/build/zlib-tool-wasi-wasm32-st-release.wasm gunzip access.log.gz access.copy.log
output
zlib 1.4 gzip: access.log -> access.log.gz, 363636 B written
zlib 1.4 gunzip: access.log.gz -> access.copy.log, 2537578 B written
输入关键词,搜索指南的所有页面和章节。
↑↓ 选择↵ 打开esc 关闭