RingDotNetfor Ring

Streams and compression

A stream is a flow of bytes that can come from memory, a file or the network. This lesson writes and reads a MemoryStream, compresses text with GZip, and shows why one pattern works for everything.

What you will learn#

Streams in one minute#

A stream is like a pipe: bytes go in at one end and come out at the other. The same few classes work with every kind of pipe:

ClassSource or target
MemoryStreammemory
FileStreama file (File.Create, File.OpenRead)
NetworkStreama socket (the tutorial Sockets)
GZipStreamwraps another stream and compresses or decompresses what passes
StreamWriter / StreamReaderturn text into bytes and back

Because they wrap each other you can stack them: text → StreamWriter → GZipStream → FileStream → disk.

The program#

samples/UsingDotNet/tutorials/ch05_streams.ring
# streams and compression - the same data in memory, in a file, and squeezed with GZip
load "dotnet.ring"

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

func main

	oUtf8 = new Encoding().UTF8

	# 1. A stream is a flow of bytes. A MemoryStream keeps them in memory: no file is needed to learn the pattern.
	oMemory = new MemoryStream()
	oWriter = new StreamWriter(oMemory)
	oWriter.WriteLine("first line")
	oWriter.WriteLine("second line")
	oWriter.Flush()                                   # the writer keeps a buffer: Flush sends it to the stream
	? "1. bytes in the memory stream: " + oMemory.Length

	# 2. Go back to the start and read what was written
	oMemory.Position = 0
	oReader = new StreamReader(oMemory)
	? "2. read back: " + oReader.ReadLine() + " / " + oReader.ReadLine()

	# 3. Compression: repeated text becomes much smaller. GZipStream wraps another stream: what you write is compressed on the way.
	cText = ""
	for nI = 1 to 200
		cText += "The quick brown fox jumps over the lazy dog. "
	next
	aBytes = oUtf8.GetBytes(cText)
	oPacked = new MemoryStream()
	oGzipWriter = new StreamWriter((new GZipStream).@New([ :stream = oPacked, :mode = "Compress", :leaveOpen = True ]))
	oGzipWriter.Write(cText)
	oGzipWriter.Dispose()                             # Dispose finishes the compressed data: without it the result is incomplete
	? nl + "3. " + len(aBytes) + " bytes became " + oPacked.Length + " bytes (" + floor(oPacked.Length * 100 / len(aBytes)) + " %)"

	# 4. And back again: reading through a GZipStream decompresses
	oPacked.Position = 0
	oUnzip = new GZipStream(oPacked,"Decompress")
	oBack = new StreamReader(oUnzip)
	cBack = oBack.ReadToEnd()
	? "4. the text is the same after the round trip: " + yesNo(cBack = cText)

	# 5. Files are streams too: File.Create gives a FileStream, with the same Read/Write methods
	cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_streams.gz"])
	oFileStream = new File().Create(cFile)
	oFileGzip = new GZipStream(oFileStream,"Compress")
	oFileWriter = new StreamWriter(oFileGzip)
	oFileWriter.Write(cText)
	oFileWriter.Dispose()                             # closes the writer, the GZipStream and the file
	? nl + "5. the .gz file has " + new FileInfo(cFile).Length + " bytes"
	new File().Delete(cFile)

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. bytes in the memory stream: 25
2. read back: first line / second line

3. 9000 bytes became 120 bytes (1 %)
4. the text is the same after the round trip: yes

5. the .gz file has 120 bytes
Note

This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Write, rewind, read#

Step 1 writes two lines into a MemoryStream. A StreamWriter keeps a buffer, so Flush() sends it to the stream before you look at Length. Step 2 sets Position = 0 to go back to the start (after writing, the position is at the end) and reads the lines with a StreamReader.

Compression#

The text of step 3 repeats the same sentence 200 times: 9,000 bytes become 120. Compression removes repetition, so text compresses very well and already compressed data (a zip, a JPEG) does not. A GZipStream created with "Compress" compresses what you write into it; with "Decompress" it decompresses what you read from it. Enum values are written as text ("Compress").

Warning

A compressing stream finishes its data only when it is disposed. Without Dispose() the end of the data is missing and the result cannot be read back. StreamWriter.Dispose() closes the stream under it too; the constructor option leaveOpen = True keeps the inner MemoryStream open so you can read it afterwards.

Files are streams too#

Step 5 stacks a StreamWriter on a GZipStream on a file created with File.Create. Disposing the writer closes everything below it. The pattern is the same as in memory.

What you learned#

Exercises#

  1. Compress a text file to .gz and decompress it to a new file, then compare the two with a hash (the tutorial Hashing and encryption).
  2. Try ZipArchive to put several files in one zip.
  3. Compress a text of 200 different lines and compare the size with the repeated text.

Next#

Binary files

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