\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#234: Add Support For Zlib Compression}
\date{December 08, 2004}
\author{Pascal Scheffers}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#234}&\textbf{Add Support For Zlib Compression}\\\hline
Author&

Pascal Scheffers \tipmail{pascal}{scheffers.net}
\\
Created&Wednesday, \(\text{8}^{\text{th}}\) December 2004\\
Type&Project\\
Tcl Version&\(8.6\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.21 $\\
Keywords&Tcl, zip, gzip, deflate\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes a new core package with commands to handle compression and decompression using the Zlib compression library.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

The Zlib compression algorithm is a widely used method for compression of files and streams. It is the algorithm used for .gz and (most) .zip files, as well as one of the standard compression algorithms in the HTTP protocol specifications.

Including support for Zlib compression in the core would enable the use of compressed VFS files, fast pure Tcl implementations of gzip and zip utilities and the use of compression in various network protocols.

A compressed VFS would be of great benefit to the new \textbf{clock} implementation \cite{tip173}, which brings a long a large number of small files which contain the timezone data. Although this would also require support for a VFS file format in the core. One possible candidate would be the Tcl Read Only fs (trofs), or perhaps a zip file VFS (only a tclvfs zip handler exists at the time of writing). Such a compressed VFS is outside the scope of this TIP, but would be much easier in the future based on top of it.

\subsection{History and Implementation Notes}

The specification and implementation for the package and command originally came from tclkit. This was wrapped in a TEA compliant package as a stand alone package. The reference implementation is a full rewrite, retaining the public API of the tclkit \textit{zlib} command.

The gzip support and C Language API are not part of the original \textit{zlib} extension. The streaming decompression is functionaly equivalent to tclkit \textbf{zlib sinflate}, but uses a different command names. Streaming compression is new.

The package version for this release is 2.0 because the private API from the original command has been removed. Alternatively, the package version can be 1.2 indicating new features were added and no existing public APIs were changed.

\section{Dependency Issues}

The package utilizes zlib/libz from the gzip project [\url{http://www.gzip.org/zlib/}]. The license of this project/library is compatible with the Tcl license, and it also compiles on most, if not all, platforms where Tcl compiles.

For ease of use, the core distribution shall include a copy of libz under \textit{tcl/contrib}. This copy will be built and used automatically when autoconf cannot find zlib.h during the configure stage.

\section{Streaming}

For large files (where large is a relative value, of course), streaming compression and decompression is required. This is implemented by using temporary commands, which can be fed small amounts of data, yielding small chunks of (de)compressed data.

\section{Tcl API}

\subsection{Block Compression and Decompression}

There are three compressed formats supported by this command:
\begin{itemize}
\item{}
\textit{compress} --- the output contains raw deflate data, with no zlib/gzip headers or trailers and no checksum value.
\item{}
\textit{deflate} --- the output contains data in zlib format, with zlib header and trailer using an Adler-32 checksum
\item{}
\textit{gzip} --- the output contains data in gzip format, with empty gzip filename, no extra data, no comment, no modification time (set to zero), no header crc and the operating system will be set to 255 (unknown).
\end{itemize}

Data is treated as binary, meaning that all input and output is going to be converted and treated as byte arrays in Tcl.

\begin{quote}
\textbf{zlib compress} \textit{data} ?\textbf{-level} \textit{level}?
\end{quote}

Returns raw deflated byte-array version of binary data \textit{data}, at an optional compression \textit{level}. The compression level must be between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time).

\begin{quote}
\textbf{zlib decompress} \textit{compressedData} 
\end{quote}

Decompresses a raw deflated byte array as obtained from \textbf{zlib compress}.

\begin{quote}
\textbf{zlib deflate} \textit{data} ?\textbf{-level} \textit{level}?
\end{quote}

Returns zlib-compressed version of \textit{data}, at an optional compression \textbf{level}. The compression level must be between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time).

\begin{quote}
\textbf{zlib inflate} \textit{deflatedData} 
\end{quote}

Decompresses the zlib-compressed data as obtained from \textbf{zlib deflate}.

\begin{quote}
\textbf{zlib gzip} \textit{data} ?\textbf{-level} \textit{level}? ?\textbf{-header} \textit{gzipHeaderDict}?
\end{quote}

Returns gzip-compressed \textit{data}, at an optional compression \textit{level}. The compression level must be between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time).

When header dict is not given with the \textbf{-header} option, the gzip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and the operating system will be set to 255 (unknown).

The header dict may contain:
\begin{itemize}
\item{}
\textbf{crc} --- integer: CRC-32 of the uncompressed data.
\item{}
\textbf{filename} --- string: original file name.
\item{}
\textbf{os} --- integer: Operating system/file system used (see RFC 1952 [\url{http://www.ietf.org/rfc/rfc1952.txt}] for list of codes).
\item{}
\textbf{size} --- integer: uncompressed size modulo 2**32.
\item{}
\textbf{time} --- integer: unix mtime in seconds since 1970-1-1, suitable for use with \textbf{clock format}.
\item{}
\textbf{type} --- flag: \textbf{binary} for binary data, \textbf{text} for ``probably text''.
\end{itemize}

Other fields may be added in the future.

\begin{quote}
\textbf{zlib gunzip} \textit{gzipData} ?\textbf{-headerVar} \textit{headerDictVarName}?
\end{quote}

Decompresses the gzip data as obtained from \textbf{zlib gzip} or any gzip file.

The command returns the uncompressed data. The optional \textbf{-headerVar} variable name will be filled with the available header fields. If a field does not exist in the gzip header, it will not be present in the dict. For example, the original filename, comment and crc are optional header fields and will be not set in the dict if they do not exist.

Note that \textbf{compress}/\textbf{decompress}, \textbf{deflate}/\textbf{inflate} and \textbf{gzip}/\textbf{gunzip} must be used in pairs.

\subsection{Streaming Compression and Decompression}

Streaming is handled in one of two ways. Either by \textbf{push}ing a transformation onto a channel's transformation stack, or by a worker command which is created by calling the \textbf{zlib} command's \textbf{stream} subcommand.

\subsection{Channel Transformations}

\begin{quote}
\textbf{zlib push} \textbf{deflate}\tipbar{}\textbf{inflate}\tipbar{}\textbf{compress}\tipbar{}\textbf{decompress}\tipbar{}\textbf{gzip}\tipbar{}\textbf{gunzip} \textit{channel} ?\textit{-level level}? ?\textit{-limit count}? ?\textit{-header gzipHeaderDict}? ?\textit{-headerVar headerDictVarName}?
\end{quote}

Pushes the requested transformation onto the channel stack. The compression level must be between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). The \textbf{-limit} option specifies the maximum number of bytes to read from the channel. This is mainly intended to specify how much compressed should be read from a non-seekable channel.

The \textbf{-header} and \textbf{-headerVar} are only used for \textbf{gzip} and \textbf{gunzip} modes respectively. See the previous section for their definition.

Additional \textbf{chan} commands are enabled after pushing a zlib transformation:

\begin{quote}
\textbf{chan adler32} \textit{channelId}
\end{quote}

Returns the Adler32 checksum for the data. Continuously updated during compression, available only at the of decompression.

\begin{quote}
\textbf{chan fullflush} \textit{channelId}
\end{quote}

Performs a fullflush on the compression output.

At the end of the data during compression, simply \textbf{chan pop} to finalize compression and flush any remaining compressed data.

At the end of compressed data, the channel will return EOF until the transformation is popped from the channel. If no \textbf{-limit} was specified, the current access position of the channel is undefined.

When the base channel or transform returns EOF, compression will automatically finalize. When EOF occurs during decompression but the compressed stream is not yet at EOF, an error will be raised. 

\subsection{The zlib stream command}

\begin{quote}
\textbf{zlib stream} \textbf{deflate}\tipbar{}\textbf{inflate}\tipbar{}\textbf{compress}\tipbar{}\textbf{decompress}\tipbar{}\textbf{gzip}\tipbar{}\textbf{gunzip} ?\textit{-level level}? ?\textit{-header gzipHeaderDict}? ?\textit{-headerVar headerDictVarName}?
\end{quote}

Returns a command name which will perform the requested operation in a streaming fashion. The compression level value, \textit{level}, is only used when compressing data.

The \textbf{-header} and \textbf{-headerVar} are only used for \textbf{gzip} and \textbf{gunzip} modes respectively. See earlier in this TIP for their definition.

\subsubsection{Stream Worker Command}

The stream worker command is used to actually compress and decompress in smaller chunks than the input and/or output.

\begin{quote}
\textit{stream} \textbf{put} ?\textit{-flush\tipbar{}-fullflush\tipbar{}-finalize}? \textit{data}
\end{quote}

Adds data to be (de)compression. The flags \textbf{-flush}, \textbf{-fullflush} and \textbf{-finalize} are mutually exclusive and indicate the desired flushing of the stream. \textbf{-finalize} is used to indicate the last block of data while compressing. After \textbf{-finalize}, no more data can be added to be compressed. For decompression, after \textbf{-finalize} you can still add more data for decompression.

\begin{quote}
\textit{stream} \textbf{flush}
\end{quote}

The next invoke of the stream's \textbf{get} subcommand will try to get the most data from the stream. While compressing, calling [\textit{stream} \textbf{flush}] often will degrade the compression ratio as it forces all remaining input to be output immediately.

\begin{quote}
\textit{stream} \textbf{fullflush}
\end{quote}

Like the \textbf{flush} subcommand, the next \textbf{get} subcommand invoked on the stream will try to get the most data from the stream. Additionally, the compressor will output extra data to enable recovery from this point in the datastream.

\begin{quote}
\textit{stream} \textbf{finalize}
\end{quote}

For compression, this signals the end of the input data; no more data can be added to the stream after the \textbf{finalize} subcommand is called. For decompression, this functions the same as the \textbf{flush} subcommand.

\begin{quote}
\textit{stream} \textbf{get} ?\textbf{-count} \textit{count}?
\end{quote}

Gets (de)compressed data from the stream. The optional \textit{count} parameter specifies the maximum number of bytes to read from the stream. Especially for decompression, it is strongly recommended to specify a \textit{count}.

\begin{quote}
\textit{stream} \textbf{eof}
\end{quote}

Returns 0 while the end of the compressed stream has not been reached. Returns 1 when the end of compressed stream was reached or the last data has been put to the stream and \textbf{-finalize} was specified, or [\textit{stream} \textbf{finalize}] has been called while compressing data.

When [\textit{stream} \textbf{eof}] is returning true, and [\textit{stream} \textbf{get} ?\textit{count}?] returns an empty string, you will have obtained all data from the stream.

\begin{quote}
\textit{stream} \textbf{checksum}
\end{quote}

Returns the Adler-32 or CRC-32 checksum of the uncompressed data. For compressing streams, this value is updated on each \textbf{\$stream put}. For decompressing streams, the value will only match the adler32 of the decompressed string after the last [\textit{stream} \textbf{get}] returned an empty string. Which type of checksum is computed (Adler-32 or CRC-32) depends on the compression format of the stream.

\begin{quote}
\textit{stream} \textbf{close}
\end{quote}

Deletes the \textit{stream} worker command and all storage associated with it. Discards any remaining input and output. After this command, the \textit{stream} command cannot be used anymore.

\subsection{Checksums}

\begin{quote}
\textbf{zlib crc32} \textit{data} ?\textbf{-startValue} \textit{startValue}?
\end{quote}

Calculates a standard \textit{CRC-32} checksum, with an optional start value for incremental calculations.

\begin{quote}
\textbf{zlib adler32} \textit{data} ?\textbf{-startValue} \textit{startValue}?
\end{quote}

Calculates a quick \textit{Adler-32} checksum, with an optional start value for incremental calculations.

\section{C API}

\subsection{Synopsys}

Tcl\_Obj * \textbf{Tcl\_ZlibDeflate}(\textit{interp, format, data, level, dictObj})

Tcl\_Obj * \textbf{Tcl\_ZlibInflate}(\textit{interp, format, data, dictObj})

unsigned int \textbf{Tcl\_ZlibCRC32}(\textit{initValue, bytes, length})

unsigned int \textbf{Tcl\_ZlibAdler32}(\textit{initValue, bytes, length})

int \textbf{Tcl\_ZlibStreamInit}(\textit{interp, mode, format, level, dictObj, zshandlePtr})

Tcl\_Obj * \textbf{Tcl\_ZlibStreamGetCommandName}(\textit{zshandle})

int \textbf{Tcl\_ZlibStreamEof}(\textit{zshandle})

int \textbf{Tcl\_ZlibStreamClose}(\textit{zshandle})

int \textbf{Tcl\_ZlibStreamAdler32}(\textit{zshandle})

int \textbf{Tcl\_ZlibStreamPut}(\textit{zshandle, dataObj, flush})

int \textbf{Tcl\_ZlibStreamGet}(\textit{zshandle, dataObj, count})

\subsection{Arguments}
\begin{description}
\item[Tcl\_Interp *interp (in)]
Optional interpreter to use for error reporting.
\item[int format (in)]
Compressed data format. For compression and decompression either \textbf{TCL\_ZLIB\_FORMAT\_RAW}, \textbf{TCL\_ZLIB\_FORMAT\_ZLIB} or \textbf{TCL\_ZLIB\_FORMAT\_GZIP}. A fourth value, \textbf{TCL\_ZLIB\_FORMAT\_AUTO} is available for decompression, which can be used when decompressing either GZIP or ZLIB formatted data. Decompression of RAW data requires specifying the format as RAW.
\item[int mode (in)]
Compress or decompress mode. Either \textbf{TCL\_ZLIB\_INFLATE} or \textbf{TCL\_ZLIB\_DEFLATE}.
\item[Tcl\_Obj *data (in)]
The input data for compression or decompression. Will be interpreted as a bytearray object.
\item[int level (in)]
The compression level. Must either be between 0 and 9 (1 gives best speed, 9 gives best compression, 0 gives no compression at all with the input data is simply copied a block at a time) or -1 to get a default level that balances speed and compressed size. This parameter is ignored by decompressing streams.
\item[const char *bytes (in/out)]
On input, an array of bytes for calculation of checksums or compression/decompression. On output, an array of bytes to copy compressed or decompressed data into.
\item[int length (in)]
number of bytes to calculate the checksum on, or the size of \textit{bytes} buffer to read from or write to.
\item[unsigned int initValue (in)]
start value value for the crc-32 or adler-32 calculation.
\item[Tcl\_Obj *dictPtr (in)]
A reference to a dict containing any additional options for the stream handler. This is used to pass options such as \textbf{-limit}, \textbf{-header}, etc. See the Tcl command documentation for a list of options supported for a particular format and mode. If NULL, will be treated as if it is an empty dict.
\item[Tcl\_ZlibStream **zshandlePtr (out)]
Pointer to an integer to receive the handle to the stream. All subsequent \textit{Tcl\_ZlibStream*}() calls require this handle.
\item[Tcl\_ZlibStream *zshandle (in)]
Handle for the stream.
\item[Tcl\_Obj *dataObj (in/out)]
A bytearray object to read the streamed data from (\textbf{Tcl\_ZlibStreamPut}) or write the streamed data to (\textbf{Tcl\_ZlibStreamGet}).
\item[int flush (in)]
Flush parameter. \textbf{TCL\_ZLIB\_NO\_FLUSH}, \textbf{TCL\_ZLIB\_FLUSH}, \textbf{TCL\_ZLIB\_FULLFLUSH} or \textbf{TCL\_ZLIB\_FINALIZE}.
\item[int count (in)]
Maximum number of bytes to be written to the \textit{dataObj} Tcl\_Obj. The special flag value -1 means get all bytes.
\end{description}

\subsection{Functions}

\begin{quote}
\textbf{Tcl\_ZlibDeflate()}
\end{quote}

Depending on the \textit{type} flag, this function returns a \textit{Tcl\_Obj *} with a zero reference count containing the compressed data in either raw deflate format, zlib format or gzip format. If an error happens during compression, this function will return NULL and store a message in the Tcl interpreter.

\begin{quote}
\textbf{Tcl\_ZlibInflate()}
\end{quote}

This function returns a \textit{Tcl\_Obj *} with a zero reference count containing the decompressed data. The \textit{buffersize} argument may be used as a hint if the decompressed size is know before decompression. If an error happens during decompression, this function will return NULL and store a message in the Tcl interpreter.

\begin{quote}
\textbf{Tcl\_ZlibCRC32()}
\end{quote}

This function returns the standard CRC-32 calculation. The \textit{startvalue} should contain the previously returned value for streaming calculations, or zero for the first block.

\begin{quote}
\textbf{Tcl\_ZlibAdler32()}
\end{quote}

This function returns a quick Adler-32 calculation. The \textit{startvalue} should contain the previously returned value for streaming calculations, or zero for the first block.

\begin{quote}
\textbf{Tcl\_ZlibStreamInit()}
\end{quote}

This function initializes the internal state for compression or decompression and creates the Tcl worker command for use at the script level. Returns TCL\_OK when initialization was succesful.

\begin{quote}
\textbf{Tcl\_ZlibStreamGetCommandName()}
\end{quote}

This function returns a \textit{Tcl\_Obj *} which contains the fully qualified stream worker command name associated with this stream.

\begin{quote}
\textbf{Tcl\_ZlibStreamEof()}
\end{quote}

This function returns 0 or 1 depending on the state of the (de)compressor. For decompression, eof is reached when the entire compressed stream has been decompressed. For compression, eof is reached when the stream has been flushed with \textbf{TCL\_ZLIB\_FINALIZE}.

\begin{quote}
\textbf{Tcl\_ZlibStreamClose()}
\end{quote}

This function frees up all memory associated with this stream, deletes the Tcl worker command and discards all remaining input and output data.

\begin{quote}
\textbf{Tcl\_ZlibStreamAdler32()}
\end{quote}

This function returns the Adler-32 checksum of the uncompressed data up to this point. For decompressing streams, the checksum will only match the checksum of uncompressed data when \textit{Tcl\_ZlibStreamGet} returns an empty string.

\begin{quote}
\textbf{Tcl\_ZlibStreamPut()}
\end{quote}

This function is used to copy data to the stream from the given buffer. For compression, the final block of data, which may be an empty string, must be indicated with \textbf{TCL\_ZLIB\_FINALIZE} as the flush parameter. The number of bytes read from the supplied buffer is returned (or -1 on error).

\begin{quote}
\textbf{Tcl\_ZlibStreamGet()}
\end{quote}

This function is used to copy the data from the stream to the given buffer. The number of bytes written to the supplied buffer is returned (or -1 on error).

\section{Usage}

Zlib support is to form part of Tcl's standard API: no special measures will be needed for Tcl code or C-implemented extensions to make use of it.

\section{Safe Interpreters}

These commands only work on data already available to a safe interpreter and are therefore safe make available in the safe interpreter.

\section{Reference Implementation}

An old version the reference implementation is available at the subversion repository [\url{http://svn.scheffers.net/zlib}]. Alternatively, a recent snapshot is available [\url{http://svn.scheffers.net/zlib.tar.gz}]. This reference implementation includes a copy of zlib-1.2.1 [\url{http://www.gzip.org}].

The reference implementation currently implements a version 1.8 of this TIP.

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#173]{tip173}
Kevin Kenny,
\emph{Internationalisation and Refactoring of the 'clock' Command},
on-line at \url{http://purl.org/tcl/tip/173.html}
\end{thebibliography}
\end{document}
