C/C + + Programming: zlib manual translation

edition

#define ZLIB_VERSION "1.2.11"
#define ZLIB_VERNUM 0x12b0

test

#include <stdio.h>
#include <zlib.h>


int main(void)
{
    printf("ZLIB_VERSION = %s\n", ZLIB_VERSION);
    printf("ZLIB_VERNUM = %d", ZLIB_VERNUM);
    return 0;
}

introduce

zlib compression library provides compression and decompression algorithms in memory, including integrity check of uncompressed data. This version of the library only supports one compression method, but other methods will be added later with the same stream interface.

If the buffer is large enough (for example, if the input file is mmap), compression can be done in a single step or by calling the compression function repeatedly. In the latter case, the application must provide more input / output space before each call.

The default compressed data format used by the memory function is zlib format, which is a zlib wrapper recorded in RFC 1950 around a deflate stream. The deflate stream itself is also recorded in RFC 1951.

The library also supports reading and writing files in gzip (.gz) format, and its interface is similar to stdio using functions starting with "gz". Gzip format is different from zlib format. Gzip is a gzip wrapper, recorded in RFC 1952, around a deflate stream.

The library can also read and write gzip and raw deflate streams in memory.

The zlib format is designed to be compact and fast for use on memory and communication channels. gzip format is designed for single file compression on the file system. It has a larger header file than zlib to maintain directory information, and uses a different and slower inspection method than zlib.

The library does not install any signal handlers. The decoder checks the consistency of the compressed data, so the library will not crash even if the input is damaged.

Stream data structure

typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
typedef void   (*free_func)  OF((voidpf opaque, voidpf address));

struct internal_state;

typedef struct z_stream_s {
    z_const Bytef *next_in;     /* Next input byte */
    uInt     avail_in;  /* Number of bytes available */
    uLong    total_in;  /* Total number of input bytes read so far */

    Bytef    *next_out; /* The next output byte will be placed here */
    uInt     avail_out; /* next_out Free space remaining */
    uLong    total_out; /*  Total bytes output so far */

    z_const char *msg;  /*  The last error message is NULL if there is no error */
    struct internal_state FAR *state; /* Application not visible */

    alloc_func zalloc;  /* Used to assign internal status */
    free_func  zfree;   /* Used to release the internal state */
    voidpf     opaque;  /* Private data objects passed to zalloc and zfree */

    int     data_type;  /* best guess about the data type: binary or text
                           for deflate, or the decoding state for inflate */
    uLong   adler;      /* Adler-32 or CRC-32 value for uncompressed data */
    uLong   reserved;   /* Reserved for future use */
} z_stream;

typedef z_stream FAR *z_streamp;

gzip header information for incoming and outgoing zlib routines. For more details on the meaning of these fields, see RFC 1952.

typedef struct gz_header_s {
    int     text;       /* True if compressed data is considered text */
    uLong   time;       /* Modification time */
    int     xflags;     /* Additional flags (not used when writing gzip files) */
    int     os;         /* operating system */
    Bytef   *extra;     /* Pointer to the extra field or, if not, to Z_NULL */
    uInt    extra_len;  /* Extra field length (valid if extra! = z_null) */
    uInt    extra_max;  /* Extra space (only when reading header) */
    Bytef   *name;      /* Point to a zero terminated file name or Z_NULL pointer */
    uInt    name_max;   /* Space at name (only when reading header) */
    Bytef   *comment;   /* Point to a zero terminated comment or Z_NULL pointer */
    uInt    comm_max;   /* Space at comment (only when reading header) */
    int     hcrc;       /* true if header crc exists or will exist */
    int     done;       /* true when reading gzip header is complete (not used when writing gzip file) */
} gz_header;

typedef gz_header FAR *gz_headerp;

Use of structure

  • When available_ When in drops to zero, the application must update next_ in and available_ in.
  • When available_ When out drops to 0, the application must update next_ out and available_ out.
  • The application must initialize zalloc, zfree, and opaque before calling the init function.

The opaque value provided by the application will be passed as the first parameter to call zalloc and zfree. This is useful for custom memory management. The compressed library has no additional meaning for the opaque value.

  • All other fields are set by the compression library and must not be updated by the application.
  • If there is not enough memory for the object, zalloc must return Z_ NULL.
  • If zlib is used in a multithreaded application, then zalloc and zfree must be thread safe. In this case, zlib is thread safe.
  • When zalloc and zfree enter the initialization function, they are Z_ When null, they are set to use the internal routines of the standard library functions malloc() and free().
  • On a 16 bit system, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but if the symbol maxseg is defined_ 64K (see zconf.h), no more bytes need to be allocated.

Warning:

  • On MSDOS, the object returned by zalloc has exactly 65536 bytes of pointer, and the offset must be set to zero.
  • The default allocation function provided by this library ensures this (see zutil.c).
  • To reduce memory requirements and avoid any allocation of 64K objects, use - Dmax at the expense of compression ratio_ WBITS = 14 (see zconf.h).
  • Field total_ in and total_ out can be used for statistics or progress reports.
  • After compression, total_ in saves the total size of uncompressed data and can be saved for use by the decompressor (especially when the decompressor wants to decompress all data in one step).

constant

The flush value is allowed. See deflate() and inflate() below for details:

#define Z_NO_FLUSH      0
#define Z_PARTIAL_FLUSH 1
#define Z_SYNC_FLUSH    2
#define Z_FULL_FLUSH    3
#define Z_FINISH        4
#define Z_BLOCK         5
#define Z_TREES         6

The return code of the compression / decompression function. Negative values are errors and positive values are used for special but normal events:

#define Z_OK 0
#define Z_STREAM_END 1
#define Z_NEED_DICT 2
#define Z_ERRNO (-1)
#define Z_STREAM_ERROR (-2)
#define Z_DATA_ERROR (-3)
#define Z_MEM_ERROR (-4)
#define Z_BUF_ERROR (-5)
#define Z_VERSION_ERROR (-6)

Compression level:

#define Z_NO_COMPRESSION 0
#define Z_BEST_SPEED 1
#define Z_BEST_COMPRESSION 9
#define Z_DEFAULT_COMPRESSION (-1)

Compression strategy - see deflateInit2() below for details:

#define Z_FILTERED 1
#define Z_HUFFMAN_ONLY 2
#define Z_RLE 3
#define Z_FIXED 4
#define Z_DEFAULT_STRATEGY 0

deflate() data_ Possible values for the type field:

#define Z_BINARY 0
#define Z_TEXT 1
#define Z_ASCII Z_TEXT / * and 1.2 2 and earlier*/
#define Z_UNKNOWN 2

deflate's compression method (the only one supported in this release):

#define Z_DEFLATED 8

Used to initialize zalloc, zfree, opaque:

#define Z_NULL 0

And version < 1.0 2 compatibility:

#define zlib_version zlibVersion()

basic function

ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  • The application can compare zlibVersion with zlib_ Consistency of version.
  • If the first character is different, the library code actually used is the same as zlib H header file is incompatible.
  • This check is performed automatically by deflateInit and inflateInit.
ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  • Initializes the internal stream state for compression.

    • The fields zalloc, zfree, and opaque must be initialized before calling deflateInit.
    • If zalloc and zfree are set to Z_NULL, deflateInit updates them to use the default allocation function.
  • Compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:

    • 1 indicates the best speed, 9 indicates the best compression, and 0 indicates no compression at all (only one block of input data is copied at a time)
    • Z_DEFAULT_COMPRESSION is the default compromise between request speed and compression (currently equivalent to level 6).
  • If successful, deflateInit returns Z_OK;

    • If there is not enough memory, Z is returned_ MEM_ ERROR;
    • Returns Z if the level is not a valid compression level_ STREAM_ ERROR;
    • If the zlib library version (zlib_Uversion) is incompatible with the version assumed by the caller (zlib_Uversion), z_version_error is returned.
    • msg is set to null if there are no error messages.
  • deflateInit does not perform any compression: this will be done by deflate().

ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  • deflate compresses as much data as possible and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output delays (read input without producing any output), except when forced refresh.
  • The detailed semantics are as follows. deflate does one or both of the following:
    • From next_ In starts compressing more input and updates next accordingly_ In and available_ in . If all inputs cannot be processed (because there is not enough space in the output buffer), next_in and available_in are updated and processing continues for the next call to deflate()
    • From next_out starts generating more output and updates next accordingly_ Out and available_ out . This operation is enforced if the parameter flush is not zero. Forced refresh often reduces the compression rate, so set this parameter only if necessary. Even if flush is zero, some output may be provided
  • Before calling deflate(), the application should update available accordingly by providing more input and / or consuming more output_ In or available_ Out to ensure that at least one operation is possible;
  • Before calling, available_ Out should not be zero.
  • Applications can use compressed output when needed, such as when the output buffer is full (available_out = = 0), or after each call to deflate().
  • If deflate returns Z_OK and available_ If out is zero, it must be called again after the buffer has made room, because more output may hang. See deflatePending(), which you can use if necessary to determine if there is more output in this case.
  • Normally, the flush parameter is set to Z_NO_FLUSH, which allows deflate to decide how much data to accumulate before generating output to maximize compression.

Advanced features

The following functions are only required in some special applications.

ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
                                     int  level,
                                     int  method,
                                     int  windowBits,
                                     int  memLevel,
                                     int  strategy));
  • This is another version of deflateInit with more compression options. The caller must first initialize next_ in, zalloc, zfree, and opaque fields.

  • The method parameter is the compression method. In this version of the library, it must be Z_ DEFLATED.

  • The windowBits parameter is the base two logarithm of the window size (history buffer size).

    • For this version of the library, it should be between 8 and 15.
    • The higher the value of this parameter, the better the compression effect, but at the expense of memory utilization.
    • If you use deflateInit instead, the default value is 15.
  • The memLevel parameter specifies how much memory should be allocated for the internal compression state.

    • memLevel=1 uses the minimum memory, but the speed is slow and the compression ratio is reduced;
    • memLevel=9 use maximum memory for optimal speed.
    • The default value is 8.
    • For the total memory usage of windowBits and memLevel, see zconf h.
  • The strategy parameter is used to optimize the compression algorithm

    • Use value Z_ DEFAULT_ Structure is used for general data
    • Use value Z_ FILTERED is used for data generated by a filter (or predictor)
    • Use value Z_ HUFFMAN_ ONLY forced Huffman encoding (no string matching)
    • Z_ RLE limits the matching distance to one (stroke length coding)
  • If successful, deflateInit2 returns Z_OK;

    • If there is not enough memory, Z is returned_ MEM_ ERROR;
    • If the parameter is invalid (for example, invalid method), Z_STREAM_ERROR is returned;
    • Z_VERSION_ERROR is returned if the zlib library version (zlib_version) is incompatible with the version assumed by the caller (zlib_version).
    • msg is set to null if there are no error messages.
    • deflateInit2 does not perform any compression: this will be done by deflate().

Keywords: C++

Added by benjrox on Tue, 21 Dec 2021 02:55:09 +0200