Java Inflater 的字典请求:压缩字节已经喂完,为什么仍要另外提供一份字典

10-06 5阅读

解压器已经收到完整压缩数据,第一次inflate却输出零字节。继续补输入也没有必要,因为needsInput为false;它真正报告的是needsDictionary。压缩端使用了预置字典,接收端必须通过另外的约定取得同一份字典字节。

下面在内存中完成压缩与解压,默认使用带zlib包装的格式。字典、输入和压缩结果全部由本次程序创建,不读取外部文件。实验关注字典握手,不比较压缩率,也不把模型插图当成协议字段的精确布局。

完整复现与实际输出

保存整段脚本为demo.sh,执行bash demo.sh。本次实跑环境为Linux、GNU Bash 5.2.37与OpenJDK 21.0.12.1;使用java的单文件源码入口,-ea启用断言,不需要单独调用javac。脚本只在临时目录生成实验文件,退出时自动清理。

Java Inflater 的字典请求:压缩字节已经喂完,为什么仍要另外提供一份字典

AI生成概念插图:压缩胶囊在解码门前等待,一块约定好的字典纹理补齐后才能展开。不是协议抓包或压缩率图表。

#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cat > "$tmp/Demo.java" <<'JAVA'
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.*;
class Demo {
  public static void main(String[] args) throws Exception {
    byte[] dictionary = "status=ready; user=sample; mode=test;".getBytes(StandardCharsets.UTF_8);
    byte[] input = "status=ready; user=sample; mode=test; status=ready;".getBytes(StandardCharsets.UTF_8);
    var compressed = new ByteArrayOutputStream();
    var deflater = new Deflater();
    try {
      deflater.setDictionary(dictionary);
      deflater.setInput(input); deflater.finish();
      byte[] buffer = new byte[32];
      while (!deflater.finished()) {
        int n = deflater.deflate(buffer);
        if (n == 0) throw new AssertionError("deflater made no progress");
        compressed.write(buffer, 0, n);
      }
    } finally { deflater.end(); }
    var inflater = new Inflater();
    try {
      inflater.setInput(compressed.toByteArray());
      byte[] first = new byte[32];
      int n = inflater.inflate(first);
      assert n == 0 && inflater.needsDictionary() && !inflater.needsInput();
      var checksum = new Adler32(); checksum.update(dictionary);
      long required = Integer.toUnsignedLong(inflater.getAdler());
      assert required == checksum.getValue();
      System.out.println("first output bytes=" + n + "; needs dictionary=" + inflater.needsDictionary());
      System.out.println("dictionary identifier matches=" + (required == checksum.getValue()));
      try {
        inflater.setDictionary(new byte[]{1, 2, 3});
        throw new AssertionError("wrong dictionary accepted");
      } catch (IllegalArgumentException expected) {
        System.out.println("wrong dictionary=IllegalArgumentException");
      }
      inflater.setDictionary(dictionary);
      var restored = new ByteArrayOutputStream();
      while (!inflater.finished()) {
        n = inflater.inflate(first);
        if (n > 0) restored.write(first, 0, n);
        else if (!inflater.finished()) throw new AssertionError("unexpected decompressor stall");
      }
      assert Arrays.equals(restored.toByteArray(), input);
      System.out.println("restored=" + restored.toString(StandardCharsets.UTF_8));
      System.out.println("remaining input=" + inflater.getRemaining());
    } finally { inflater.end(); }
  }
}
JAVA
java -ea "$tmp/Demo.java"

以下为完整脚本的实际标准输出;本次运行退出码为零,标准错误为空。

first output bytes=0; needs dictionary=true
dictionary identifier matches=true
wrong dictionary=IllegalArgumentException
restored=status=ready; user=sample; mode=test; status=ready;
remaining input=0

先提供字典,再开始压缩内容

Deflater在接收正文前调用setDictionary,随后setInput并finish。循环收集每次deflate返回的有效字节,直到finished为true;最后在finally里end释放本地压缩器资源。不能只调用一次deflate就假定所有数据已经交付。

预置字典给压缩器一段双方事先知道的历史内容。压缩流可以利用这些模式,却不会把完整字典自动作为正文再传一次。因此,接收方即使保存了整个压缩结果,仍可能缺少解码所需的外部字节。

零输出之后,要检查具体状态

把完整压缩结果交给Inflater后,第一次inflate输出零字节,needsDictionary为true而needsInput为false。这一组合区分了“等更多压缩输入”和“需要字典”。若只在零输出时盲目重复inflate,程序可能一直没有进展。

本例的状态是受控已知的,因此直接断言。处理任意流时,还要分别处理finished、输入不足、格式错误和输出预算耗尽,不能把所有零输出都解释成同一种情况。状态机应保证每轮要么取得进展,要么清楚地等待某种外部条件。

Adler标识帮助选字典,但不是字典本身

在需要字典的状态下,getAdler给出所需字典的Adler-32值。Java返回int,代码用Integer.toUnsignedLong把它当无符号三十二位值比较,再与本地字典独立计算的校验值核对。

这份标识有助于从已约定的字典集合中选候选,不会反推出完整字典,也不是抗碰撞的身份认证。实际协议应使用可靠的字典版本与分发安排;不能只因为Adler值相同就接受来自不可信来源的任意数据。

错误字典拒绝后,仍用正确内容完成恢复

程序先故意传入三个无关字节,得到IllegalArgumentException,再传入正确字典。之后继续inflate,累计所有有效输出,最后与原始输入逐字节比较。这个反例证明成功需要相符的字典,不是随便调用一次setDictionary就能解除状态。

本次环境在错误字典被拒之后可继续提供正确字典,程序明确实测了这一流程。生产系统仍应限制候选尝试,不要靠遍历大量未知内容碰运气。字典缺失应该成为可定位的协议错误,包含安全的版本标识,而非无限重试。

包装格式、资源和输入边界都要约定

这里使用Deflater与Inflater的默认zlib包装,没有启用nowrap。原始DEFLATE与其他包装的字典发现方式不能直接照搬这个needsDictionary/getAdler流程。通信双方必须先统一格式,再讨论如何提供和标记字典。

最终remaining input为零,且恢复内容完全相同,说明本样本没有额外未消费尾部。对不可信压缩数据还需要限制压缩大小、展开字节数和处理时间,避免资源耗尽;本文只处理自己生成的短输入。字典校验、完整输出比对和finally中的end分别覆盖协议、内容与资源责任,缺一项都不能算完整验收。

参考资料

资料核验与本地实跑日期:2026年10月6日。结果对应上述环境,移植时请保留反例和断言一起复验。

Java SE 21:Deflater.setDictionary与压缩结束

Java SE 21:Inflater.needsDictionary、getAdler与setDictionary

Java SE 21:Adler32校验值

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。