RingDotNetfor Ring

Compression

Compression makes data smaller by finding repetition. This lesson uses the GZip, Deflate and Brotli streams to compress and decompress bytes in memory and to write and read a compressed file.

What you will learn#

The tutorial Files and folders made a ZIP archive of files. This lesson compresses data (one stream of bytes). GZip is the format of .gz files and of Content-Encoding: gzip on the web.

The program#

samples/UsingDotNet/tutorials/ch05_compression.ring
# compression - GZip, Deflate and Brotli on streams, sizes, a round trip and a compressed file
load "dotnet.ring"

using {
	"System"
	"System.IO"
	"System.IO.Compression"
	"System.Text"
}

func main

	# Compression looks for repetition. A text with many repeated parts becomes small; random data does not.
	cText = ""
	for i = 1 to 200
		cText += "The quick brown fox jumps over the lazy dog. "
	next
	oUtf8 = new UTF8Encoding()
	aBytes = oUtf8.GetBytes(cText)             # a byte[] is a Ring text of bytes in this package
	? "1. original text: " + len(aBytes) + " bytes"

	# 2. The three formats. Each one is a stream that WRAPS another stream: we write into the compressor, and the compressed
	#    bytes land in the memory stream below it. CompressionLevel.Optimal gives the smallest result.
	? nl + "2. compressed sizes:"
	for cFormat in ["GZip","Deflate","Brotli"]
		cPacked = compress(cFormat,aBytes)
		? "   " + padRight(cFormat,8) + len(cPacked) + " bytes   (" + floor(len(aBytes) / len(cPacked)) + " times smaller)"
	next

	# 3. The round trip: decompress and compare
	cPacked = compress("GZip",aBytes)
	cBack = decompress("GZip",cPacked)
	? nl + "3. after GZip and back: " + len(cBack) + " bytes, same as the original: " + (cBack = aBytes)

	# 4. GZip data starts with two fixed bytes (31 and 139): that is how a program recognizes a .gz file
	? nl + "4. first bytes of a GZip result: " + ascii(cPacked[1]) + " " + ascii(cPacked[2])

	# 5. Data that does not repeat does not shrink (it grows a little because of the header)
	cNoise = ""
	for i = 1 to 2000
		cNoise += char(random(255))
	next
	cNoisePacked = compress("GZip",cNoise)
	? nl + "5. 2000 random bytes: the GZip result is larger than the original: " + (len(cNoisePacked) > 2000)

	# 6. A compressed file: write a .gz file, read it back line by line with a StreamReader on top of the decompressor
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_compression.txt.gz"])
	oFile = new FileStream(cFile,"Create")
	oGzip = new GZipStream(oFile,"Compress")
	oWriter = new StreamWriter(oGzip)
	for i = 1 to 3
		oWriter.WriteLine("line " + i + " of the compressed file")
	next
	oWriter.Dispose()                          # closing the writer also closes the compressor and the file
	? nl + "6. file size on disk: " + new FileInfo(cFile).Length + " bytes"
	oFile = new FileStream(cFile,"Open")
	oGzip = new GZipStream(oFile,"Decompress")
	oReader = new StreamReader(oGzip)
	while not oReader.EndOfStream
		? "   read: " + oReader.ReadLine()
	end
	oReader.Dispose()
	new File().Delete(cFile)

func compress cFormat,cData

	oMemory = new MemoryStream()
	oPacker = packer(cFormat,oMemory,"Compress")
	oPacker.Write(cData,0,len(cData))
	oPacker.Dispose()                          # Dispose finishes the compressed data: without it the end is missing
	return oMemory.ToArray()

func decompress cFormat,cData

	oSource = new MemoryStream().@New([ :buffer = cData ])
	oUnpacker = packer(cFormat,oSource,"Decompress")
	oOut = new MemoryStream()
	oUnpacker.CopyTo(oOut)
	return oOut.ToArray()

func packer cFormat,oStream,oMode

	switch cFormat
	on "GZip"    return new GZipStream(oStream,oMode)
	on "Deflate" return new DeflateStream(oStream,oMode)
	on "Brotli"  return new BrotliStream(oStream,oMode)
	off

func padRight cText,nWidth

	return cText + copy(" ",nWidth - len(cText))
Output
1. original text: 9000 bytes

2. compressed sizes:
   GZip    108 bytes   (83 times smaller)
   Deflate 90 bytes   (100 times smaller)
   Brotli  54 bytes   (166 times smaller)

3. after GZip and back: 9000 bytes, same as the original: 1

4. first bytes of a GZip result: 31 139

5. 2000 random bytes: the GZip result is larger than the original: 1

6. file size on disk: 66 bytes
   read: line 1 of the compressed file
   read: line 2 of the compressed file
   read: line 3 of the compressed file

How it works#

Streams that wrap streams#

A compression stream does not hold data itself: it is built on top of another stream and a mode (Compress or Decompress). Bytes written to a compressor are packed and written to the stream below it; bytes read from a decompressor come from the stream below it, unpacked. The stream below can be a MemoryStream (bytes in memory) or a FileStream (a file). The three classes have the same members, so the function packer is the only place that knows the format. It is made with new GZipStream(oStream, "Compress"). The mode is an enum, so it is a text.

Compress and decompress#

compress writes the bytes into the compressor (Write(bytes, 0, count)) and calls Dispose(). Dispose matters: it writes the end of the compressed data. If you only read the memory stream without it, the result is cut and cannot be decompressed. decompress opens a MemoryStream on the packed bytes ([ :buffer = ... ]), wraps it in a decompressor and copies everything to another stream with CopyTo. A byte[] is a Ring text of bytes in this package, so len() is the number of bytes and cBack = aBytes compares them.

Sizes#

The text repeats one sentence 200 times, so every format makes it tiny; Brotli is the smallest and GZip the largest here, which is common for text (Brotli is slower to compress). With normal text expect 2 to 4 times smaller, not 100. A GZip result starts with the bytes 31 139 (1F 8B), which is how programs recognize a .gz file.

Random data#

Compression needs repetition. Random bytes have none, so the result is slightly larger than the original (the header and the bookkeeping cost a few bytes). Data that is already compressed (JPEG, PNG, ZIP, MP4) behaves the same: compressing it twice does not help.

A compressed file#

Step 6 puts a GZipStream on a FileStream and a StreamWriter on the compressor. Everything written with WriteLine is compressed on its way to the disk. Disposing the writer closes the whole chain. Reading is the same chain in the other direction: StreamReader on GZipStream on FileStream, and EndOfStream tells when the lines are finished. (The tutorial Streams and compression explains streams.)

Note

BrotliStream lives in another assembly (System.IO.Compression.Brotli); RingDotNet finds it for you. CompressionLevel ("Optimal", "Fastest", "SmallestSize") is an optional second value of the constructor when the mode is Compress.

What you learned#

Exercises#

  1. Compress the text of a real file (a log from the tutorial A project: analyze a log file) and print the ratio for each format.
  2. Add CompressionLevel and compare "Fastest" with "SmallestSize" with a Stopwatch.
  3. Write a function gzipFile(source, target) that uses CopyTo between two file streams.
  4. Compress the same bytes twice and look at the size of the second result.

Next#

ZIP archives in memory

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.