What this is about
A compressed file stores the same information in fewer bytes. You use it every day: a .gz or .zip file, a web page that arrives smaller than it looks, a log archive. The program that makes the file small is the compressor. The program that gets the original back is the decompressor.
This article explains the main trick behind gzip in plain words, shows a real before and after from Mojo, and tells how to use it from a script.
Why it matters
Smaller files save disk space and download time. Web servers compress pages so they travel faster. Backups of text logs often shrink to a small fraction of their size.
It helps to know the limits too. Compression is not magic. Data that already looks random cannot shrink, and some files, such as already compressed pictures, barely change. A little understanding tells you when to bother.
How it works
Take this line of text:
the cat sat on the mat. the cat sat on the mat. the cat sat on the mat.
A person would say "that sentence, three times". A compressor does the same. The first time it sees a piece of text, it writes the text. Later, when it sees the same piece again, it writes a short note: "go back 24 characters and copy 24 characters". A note is shorter than the text it replaces.
That idea has a name, but you do not need it to use the tool. In the gzip format there are two steps.
- Find repeats. Look for pieces of text that appeared earlier, and replace each with a pointer back to it.
- Write common symbols short. After step one, some symbols turn up often. Give those short codes, and give rare symbols longer codes.
The format that does both steps is called deflate. The wrapper around it adds a header and a check number to catch damage. gzip puts one wrapper on it, and zlib puts a different, lighter one. Raw deflate has no wrapper at all.
The more repeats in your data, the smaller the result. Text, logs, JSON and source code have many. Data with no pattern has none, so there is nothing to point back to.
Let's try it in Mojo
Our mojo-gzip library calls the system's own compression library, libz. Here is a program with two experiments. We ran it on Mojo 1.2.0.
from gzip import compress, decompress
def main() raises:
var data = List[UInt8](length=1 << 20, fill=65)
var z = compress(data, 6, "gzip")
print("before", len(data), "after", len(z))
var back = decompress(z)
print("round trip ok", len(back) == len(data))
It printed:
before 1048576 after 1052
round trip ok True
One MiB of the letter A, which is the most repetitive input you can make, shrank to 1,052 bytes. The same job through Python's gzip.compress at level 6 also gave 1,052 bytes. The round trip got every byte back.
A second experiment used the cat sentence above, repeated 50 times. That is 3,600 bytes of text. Compressed at level 6, it was 69 bytes, and Python gave 69 as well. Those figures come from our own runs on one machine.
The 6 is the level, from 1 to 9. A higher level tries harder to find repeats and takes longer. The "gzip" says which wrapper to use. Other choices are "zlib" and "raw".
Working with big files
compress and decompress work on bytes held in memory. For a large .gz file, use GzFile, which streams. You read a chunk into a buffer you own, process it, and read the next. The README measured streaming 50 MB of output and a peak of 12 MB of memory, with a gate below 30 MB.
When you close a GzFile after reading, it raises an error if the file was cut short. That is useful. A half-downloaded .gz file does not quietly look complete.
The library also offers crc32 and adler32, the check numbers that gzip and zlib use. Both give the same answers as Python's zlib.crc32 and zlib.adler32, and you can chain them over many chunks.
How it was checked, and what to expect
The README checks 43 read, decompress and checksum results against Python. It also checks that 60 files written by the library, across five inputs, three levels and three formats, inflate to the source under Python. Cut-short, bit-flipped and multi-member files are among the fixtures. Four of four planted bugs were caught.
On speed, the README reports 21.8 MB inflated in 15 to 17 ms against 19 to 20 ms for Python, and 3 ms for deflate on both. The speed is the same as Python's because both call the same libz. Mojo adds convenience and a checked API, not a faster algorithm here.
The library needs libz.so.1 at run time. Every common Linux system has it.
For other formats we have mojo-zstd, which does zstd and lz4 in pure Mojo, and mojo-zip for zip files. See the table in mojo-libs.
The library now lives in mojo-libs under libs/gzip. The older repository is read-only.
Words you may not know
- Compress: make data take fewer bytes.
- Round trip: compress and then decompress, and check you get the original.
- Level: a number from 1 to 9 for how hard the compressor tries.
- Checksum: a small number computed from data, used to spot damage.
- Stream: read or write in chunks, so the whole file need not fit in memory.
Try it
- Run the program above and change the
fill=65line to see how repeats affect the size. - Compress a text file with the
gzipcommand and compare the sizes. - Read the mojo-gzip repository README and try
GzFileon a log of your own.
Read next
- Memory-mapped files, explained is another way to work with a big file without loading it all at once.

Commentaires
Pas encore de commentaires.
Se connecter pour commenter.