Skip to main content

7  DEFLATE: gzip and zlib

7.1 Introduction

If you have ever downloaded a file, you have used DEFLATE. Phil Katz designed it for his PKZIP archiver; it first appeared in a test release in 1991 and became the standard method of the zip format when PKZIP 2.04 shipped at the start of 1993. Jean-loup Gailly and Mark Adler built the free gzip program on it, first released on 31 October 1992, and then the zlib library, released in 1995, which put DEFLATE inside other programs. In 1996 Peter Deutsch wrote down all three formats, byte by byte, in three RFCs, the documents in which the Internet’s formats are specified: DEFLATE itself (Deutsch 1996a), the gzip file format (Deutsch 1996b) and the zlib stream format (Deutsch and Gailly 1996).

Then nothing changed, and that is the point. A gzip file written in 1993 decompresses today with any gzip tool on any computer, and one written today will decompress in fifty years, because the format is simple, free, documented to the last bit and implemented thousands of times over. DEFLATE is inside zip archives, PNG images, PDF files, compressed web pages, R’s package tarballs and R’s own .rds files (Chapter 12). Physics formats use it too: ROOT, the particle physicist’s data framework, offers zlib alongside LZMA, LZ4 and Zstandard, HDF5 has a deflate filter, and the FITS standard allows gzip compression of image tiles (IAU FITS Working Group 2018). If you need a compressor whose output will certainly be readable by someone else, in any language, in any decade, this is it.

Prerequisites

library(tidyverse)

7.2 How DEFLATE works

DEFLATE is the two previous chapters put together. First, an LZ77 search (Chapter 6) turns the input into a stream of literal bytes and back-references. The window reaches 32 kilobytes back, and a match can be 3 to 258 bytes long (Deutsch 1996a). Then Huffman coding (Chapter 5) compresses that stream, using two codes: one for literal bytes and match lengths together, and one for match distances.

The stream is cut into blocks, and each block can be stored in one of three ways: uncompressed, which avoids expanding data that will not compress; with a fixed Huffman code written into the standard, which saves sending a table for short blocks; or with a dynamic Huffman code built for that block, whose table is sent first in compact form as a list of code lengths. The compressor chooses for each block. The decompressor just follows instructions.

That split, a decompressor that is fully specified and a compressor that is free to search as cleverly as it likes, is why DEFLATE has lasted. Compressors have improved for thirty years while every decompressor ever written still reads their output. The level setting, from 1 to 9, controls how hard the compressor searches for matches; it never affects whether the output can be read.

7.3 A gzip file, byte by byte

A gzip file wraps a DEFLATE stream in a ten-byte header and an eight-byte trailer, all laid out in RFC 1952. Because the format is documented to the byte, base R’s readBin(), which reads raw bytes from a file, is all you need to inspect one. Here are the first ten bytes of the dimuon file:

header <- readBin("data/dimuon.csv.gz", what = "raw", n = 10)
header
#>  [1] 1f 8b 08 00 00 00 00 00 00 06
Bytes Value (hex) Meaning
1-2 1f 8b Magic number: this is a gzip file
3 08 Compression method 8: DEFLATE
4 00 Flags: optional fields present (0 means none)
5-8 00 00 00 00 Modification time, seconds since 1970 (0 means not recorded)
9 00 Extra flags: hints about the compression level
10 06 Operating system that wrote the file

The magic number 1f 8b is how every gzip tool recognizes a gzip file, and it is how readr knew to decompress this one. Byte 3 says the data are DEFLATE, the only method gzip has ever used.

The trailer holds a CRC-32 checksum of the original data, which lets a decompressor detect corruption, and the original length, modulo 232, as a four-byte little-endian integer. Read the length and compare it with the size of the decompressed data:

gz_bytes <- readBin("data/dimuon.csv.gz", what = "raw", n = file.size("data/dimuon.csv.gz"))

trailer <- tail(gz_bytes, 8)
readBin(trailer[5:8], what = "integer", size = 4, endian = "little")
#> [1] 6869021

csv_bytes <- memDecompress(gz_bytes, type = "gzip")
length(csv_bytes)
#> [1] 6869021

They agree. Nothing about this file depends on R, on readr or on any particular gzip program. The specification is the contract.

7.4 Compression levels

The dimuon CSV holds 6,869,021 bytes of text. To see what the compression levels trade, write it at each level through a gzfile() connection, whose compression argument sets the level, and record the size and the time:

csv_lines <- readLines("data/dimuon.csv.gz")    # readLines() decompresses too

write_gzip <- function(level) {
  path <- tempfile(fileext = ".csv.gz")
  seconds <- system.time({
    con <- gzfile(path, open = "w", compression = level)
    writeLines(csv_lines, con)
    close(con)
  })[["elapsed"]]
  tibble(level = level, megabytes = file.size(path) / 1e6, seconds = seconds)
}

gzip_levels <- map(1:9, write_gzip) |>
  list_rbind() |>
  mutate(ratio = length(csv_bytes) / 1e6 / megabytes)

gzip_levels
#> # A tibble: 9 × 4
#>   level megabytes seconds ratio
#>   <int>     <dbl>   <dbl> <dbl>
#> 1     1      2.98  0.0900  2.31
#> 2     2      2.89  0.110   2.38
#> 3     3      2.77  0.140   2.48
#> 4     4      2.72  0.150   2.53
#> 5     5      2.60  0.25    2.65
#> 6     6      2.53  0.47    2.71
#> 7     7      2.52  0.64    2.73
#> 8     8      2.51  1.01    2.74
#> 9     9      2.51  1.01    2.74
ggplot(gzip_levels, aes(x = seconds, y = megabytes, label = level)) +
  geom_line(colour = "grey70") +
  geom_point(size = 2) +
  geom_text(nudge_y = 0.02, size = 3.5) +
  labs(x = "Time to compress (s)", y = "Compressed size (MB)")
A scatter plot of compressed size against compression time for gzip levels 1 to 9, each point labelled with its level. Size falls steadily from level 1 to level 6, then flattens while the time keeps growing.
Figure 7.1: gzip’s levels trade time for size. Beyond the default, level 6, the extra time buys very little.

Your timings will differ, but the shape will not. The levels up to the default, 6, each buy a little more compression for a little more time; the levels after it cost far more time for a sliver of size. That is why the default sits at the bend. Decompression speed hardly depends on the level at all, because decompressing a DEFLATE stream is the same work however hard the compressor searched.

7.5 gzip in everyday R

You rarely need to think about any of this, because gzip is built into R at every level.

  • readr reads and writes it by file extension. read_csv("x.csv.gz") decompresses as it reads, and write_csv(df, "x.csv.gz") compresses as it writes. The same goes for read_tsv(), read_lines() and their relatives.
  • Base R’s connections handle it. file(), which readLines() and read.csv() use underneath, recognizes a gzip file from its magic number and decompresses it; gzfile() writes one, with a choice of level.
  • memCompress(x, "gzip") and memDecompress() work on raw vectors in memory. memCompress() writes the zlib format of RFC 1950 rather than the gzip file format; the two wrap the same DEFLATE stream in different headers. The first two bytes of zlib’s header, typically 78 9c at the default level, are as recognizable as gzip’s 1f 8b:
memCompress(charToRaw("muon muon muon muon"), type = "gzip")[1:2]
#> [1] 78 9c
  • saveRDS() compresses R objects with gzip unless you ask for something else (Chapter 12), and Parquet files can use it for each column (Chapter 13).

7.6 When to choose gzip

gzip is the conservative choice, in the best sense: whatever else changes, someone will be able to read it. Choose it for files you share, files you archive and files that must open in tools you do not control. It is not the best at anything else. LZ4 and Zstandard compress and decompress several times faster (Chapter 10), and bzip2, xz and Zstandard at high levels make smaller files (Chapter 8, Chapter 9). Its 32-kilobyte window also means it cannot see repetition on longer scales: a detector configuration that recurs every megabyte looks new to it every time. When you need speed or size, use a newer codec; when you need certainty, use gzip.

7.7 Summary

DEFLATE is LZ77 with a 32-kilobyte window followed by Huffman coding, wrapped as gzip files or zlib streams, and it has not changed since it was written down in 1996. You read a gzip header and trailer with nothing but readBin(), recovered the original file size from the trailer, and measured how the compression levels trade time for size. In R, gzip is everywhere: readr and base connections read and write it by extension, memCompress() uses it in memory, and saveRDS() and Parquet can use it on disk.

7.8 Exercises

  1. Write a small data frame with write_csv() to a .csv.gz file and decode its header as above. What does the operating-system byte say? Look up its meaning in RFC 1952.
  2. Repeat the compression-level comparison for the magnetometer CSV. Is the default level a good choice for it too?
  3. Write the dimuon data both uncompressed and gzipped, and time read_csv() on each with system.time(). Which is faster to read on your computer? Why might the compressed file be the faster one on a slow disk or a network drive?
  4. Compress a raw vector of a million identical bytes, as.raw(rep(0, 1e6)), with memCompress(). What compression ratio do you get? DEFLATE cannot do much better than about 1000:1 on any input; use the 258-byte maximum match length to explain why.
  5. The gzip trailer stores the original length modulo 232. What would it hold for a 5-gigabyte file, and why does that make it unreliable for measuring the size of big files?