woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

开源zlib压缩库

介绍

zlib

这个版本只有一种压缩方式,但是以后其他的算法也会被加入进来,并且接口是一样的。

 

如果缓存区足够大,压缩被一次完成,否则就重复调用压缩。在后一种情况,程序必须在每次调用时提供更多的输入或更多输出空间。

 

本压缩库也支持gzip.gz)格式的读写操作。接口也和stdio相似。

 

本压缩库不安装任何信号处理,解码器检查压缩数据的一致性,所以,本压缩库决不会使输入崩溃。

 

 

--------------------------------------------------------------------------------

 

实用函数

以下实用函数的实现建立在basic stream-oriented 函数上。

为了了简化接口,设置了一些默认选项(压缩级别,内存使用,标准内存分配器功能)这些实用函数的源代码很容易被修改,如果你要实现有些特殊选项。

函数列表:

intcompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

intcompress2 (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen,int level);

intuncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLongsourceLen);

 

typedefvoidp gzFile;

 

gzFilegzopen (const char *path, const char *mode);

gzFilegzdopen (int fd, const char *mode);

 

intgzsetparams (gzFile file, int level, int strategy);

 

intgzread (gzFile file, voidp buf, unsigned len);

intgzwrite (gzFile file, const voidp buf, unsigned len);

 

intVA gzprintf (gzFile file, const char *format, ...);

intgzputs (gzFile file, const char *s);

char* gzgets (gzFile file, char *buf, int len);

intgzputc (gzFile file, int c);

intgzgetc (gzFile file);

intgzflush (gzFile file, int flush);

z_off_tgzseek (gzFile file, z_off_t offset, int whence);

z_off_tgztell (gzFile file);

intgzrewind (gzFile file);

intgzeof (gzFile file);

intgzclose (gzFile file);

constchar * gzerror (gzFile file, int *errnum);

 

函数说明:

intcompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen);

 

压缩source bufferdestination buffer

sourceLen

destLen

如果输入文件是mmap'ed,这个函数可以用于压缩整个文件。

如果压缩成功返回Z_OK, 如果没有足够的内存返回Z_MEM_ERROR,如果没有足够的空间输出文件返回Z_BUF_ERROR.

 

intcompress2 (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen,int level);

 

压缩source bufferdestination buffer

参数级leveldefalteInit一样。

destLen

如果压缩成功返回Z_OK, 如果没有足够的内存返回Z_MEM_ERROR,如果没有足够的空间输出文件返回Z_BUF_ERROR.

如果level是无效的,返回Z_STREAM_ERROR.

 

intuncompress (Bytef *dest, uLongf *destLen, const Bytef *source, uLongsourceLen);

Decompressesthe source buffer into the destination buffer. sourceLen is the byte length ofthe source buffer. Upon entry, destLen is the total size of the destinationbuffer, which must be large enough to hold the entire uncompressed data. (Thesize of the uncompressed data must have been saved previously by the compressorand transmitted to the decompressor by some mechanism outside the scope of thiscompression library.) Upon exit, destLen is the actual size of the compressedbuffer.

Thisfunction can be used to decompress a whole file at once if the input file ismmap'ed.

 

uncompressreturns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERRORif the input data was corrupted.

 

 

typedefvoidp gzFile;

gzFilegzopen (const char *path, const char *mode);

 

打开一个gzip文件进行读/,modefopen("rb"" wb")一样.也可以包括压缩级别如:"wb9",或着一个策略"f"作为过滤数据"wb", "h"是为了"huffman" 压缩,:"wb1h".

gzopen

如果文件不能被打开或是没有足够的内存,gzopen将返回NULL.

 

gzFilegzdopen (int fd, const char *mode);

 

gzdopen()associates a gzFile with the file descriptor fd. File descriptors are obtainedfrom calls like open, dup, creat, pipe or fileno (in the file has beenpreviously opened with fopen). The mode parameter is as in gzopen.

Thenext call of gzclose on the returned gzFile will also close the file descriptorfd, just like fclose(fdopen(fd), mode) closes the file descriptor fd. If youwant to keep fd open, use gzdopen(dup(fd), mode).

 

gzdopenreturns NULL if there was insufficient memory to allocate the (de)compressionstate.

 

 

intgzsetparams (gzFile file, int level, int strategy);

Dynamicallyupdate the compression level or strategy. See the description of deflateInit2for the meaning of these parameters.

gzsetparamsreturns Z_OK if success, or Z_STREAM_ERROR if the file was not opened forwriting.

 

 

intgzread (gzFile file, voidp buf, unsigned len);

Readsthe given number of uncompressed bytes from the compressed file. If the inputfile was not in gzip format, gzread copies the given number of bytes into thebuffer.

gzreadreturns the number of uncompressed bytes actually read (0 for end of file, -1for error).

 

 

intgzwrite (gzFile file, const voidp buf, unsigned len);

Writesthe given number of uncompressed bytes into the compressed file. gzwritereturns the number of uncompressed bytes actually written ( case of error).

 

intVA gzprintf (gzFile file, const char *format, ...);

Converts,formats, and writes the args to the compressed file under control of the formatstring, as in fprintf. gzprintf returns the number of uncompressed bytesactually written (0 incase of error).

 

intgzputs (gzFile file, const char *s);

Writesthe given null-terminated string to the compressed file, excluding theterminating null character.

gzputsreturns the number of characters written, or -1 in case of error.

 

 

char* gzgets (gzFile file, char *buf, int len);

Readsbytes from the compressed file until len-1 characters are read, or a newlinecharacter is read and transferred to buf, or an end-of-file condition isencountered. The string is then terminated with a null character.

gzgetsreturns buf, or Z_NULL in case of error.

 

 

intgzputc (gzFile file, int c);

Writesc, converted to an unsigned char, into the compressed file. gzputc returns thevalue that was written, or -1 incase of error.

 

intgzgetc (gzFile file);

Readsone byte from the compressed file. gzgetc returns this byte or case of end of file or error.

 

intgzflush (gzFile file, int flush);

Flushesall pending output into the compressed file. The parameter flush is as in thedeflate() function. The return value is the zlib error number (see functiongzerror below). gzflush returns Z_OK if the flush parameter is Z_FINISH and alloutput could be flushed.

gzflushshould be called only when strictly necessary because it can degradecompression.

 

 

z_off_tgzseek (gzFile file, z_off_t offset, int whence);

Setsthe starting position for the next gzread or gzwrite on the given compressedfile. The offset represents a number of bytes in the uncompressed data stream.The whence parameter is defined as in lseek(2); the value SEEK_END is notsupported.

Ifthe file is opened for reading, this function is emulated but can be extremelyslow. If the file is opened for writing, only forward seeks are supported ;gzseek then compresses a sequence of zeroes up to the new starting position.

 

gzseekreturns the resulting offset location as measured in bytes from the beginningof the uncompressed stream, or -1 incase of error, in particular if the file is opened for writing and the newstarting position would be before the current position.

 

 

intgzrewind (gzFile file);

Rewindsthe given file. This function is supported only for reading.

gzrewind(file)is equivalent to (int)gzseek(file, 0L,SEEK_SET)

 

 

z_off_tgztell (gzFile file);

Returnsthe starting position for the next gzread or gzwrite on the given compressedfile. This position represents a number of bytes in the uncompressed datastream.

gztell(file)is equivalent to gzseek(file, 0L,SEEK_CUR)

 

 

intgzeof (gzFile file);

Returns1 when EOF has previously been detected reading the given input stream,otherwise zero.

 

intgzclose (gzFile file);

Flushesall pending output if necessary, closes the compressed file and deallocates allthe (de)compression state. The return value is the zlib error number (seefunction gzerror below).

 

constchar * gzerror (gzFile file, int *errnum);

Returnsthe error message for the last error which occurred on the given compressedfile. errnum is set to zlib error number. If an error occurred in the filesystem and not in the compression library, errnum is set to Z_ERRNO and theapplication may consult errno to get the exact error code.

 

 

--------------------------------------------------------------------------------

 

基本函数:

函数列表:

 

constchar * zlibVersion (void);

intdeflateInit (z_streamp strm, int level);

intdeflate (z_streamp strm, int flush);

intdeflateEnd (z_streamp strm);

intinflateInit (z_streamp strm);

intinflate (z_streamp strm, int flush);

intinflateEnd (z_streamp strm);

函数说明:

 

constchar * zlibVersion (void);

应用程序会比较zlibVersionZLIB_VERSION的一致性。

如果第一个字不同,说明zlib和应用程序使用的zlib.h是不一致的。这个检查将被defalteInitinfalteInit自动调用。

 

intdeflateInit (z_streamp strm, int level);

为压缩初始化内部流的状态。

Initializesthe internal stream state for compression. The fields zalloc, zfree and opaquemust be initialized before by the caller. If zalloc and zfree are set toZ_NULL, deflateInit updates them to use default allocation functions.

Thecompression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 givesbest speed, 9 gives best compression, 0 gives no compression at all (the inputdata is simply copied a block at a time).

 

Z_DEFAULT_COMPRESSIONrequests a default compromise between speed and compression (currentlyequivalent to level 6).

 

deflateInitreturns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR ifthe zlib library version (zlib_version) is incompatible with the versionassumed by the caller (ZLIB_VERSION). msg is set to null if there is no errormessage. deflateInit does not perform any compression: this will be done bydeflate().

 

 

intdeflate (z_streamp strm, int flush);

deflatecompresses as much data as possible, and stops when the input buffer becomesempty or the output buffer becomes full. It may introduce some output latency(reading input without producing any output) except when forced to flush.

Thedetailed semantics are as follows. deflate performs one or both of thefollowing actions:

 

Compressmore input starting at next_in and update next_in and avail_in accordingly. Ifnot all input can be processed (because there is not enough room in the outputbuffer), next_in and avail_in are updated and processing will resume at thispoint for the next call of deflate().

Providemore output starting at next_out and update next_out and avail_out accordingly.This action is forced if the parameter flush is non zero. Forcing flushfrequently degrades the compression ratio, so this parameter should be set onlywhen necessary (in interactive applications). Some output may be provided evenif flush is not set.

Beforethe call of deflate(), the application should ensure that at least one of theactions is possible, by providing more input and/or consuming more output, andupdating avail_in or avail_out accordingly ; avail_out should never be zerobefore the call. The application can consume the compressed output when itwants, for example when the output buffer is full (avail_out == 0), or after eachcall of deflate(). If deflate returns Z_OK and with zero avail_out, it must becalled again after making room in the output buffer because there might be moreoutput pending.

 

Ifthe parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed tothe output buffer and the output is aligned on a byte boundary, so that thedecompressor can get all input data available so far. (In particular avail_inis zero after the call if enough output space has been provided before thecall.) Flushing may degrade compression forsome compression algorithms and so it should be used only when necessary.

 

Ifflush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, andthe compression state is reset so that decompression can restart from this pointif previous compressed data has been damaged or if random access is desired.Using Z_FULL_FLUSH too often can seriously degrade the compression.

 

Ifdeflate returns with avail_out == 0, this function must be called again withthe same value of the flush parameter and more output space (updatedavail_out), until the flush is complete (deflate returns with non-zeroavail_out).

 

Ifthe parameter flush is set to Z_FINISH, pending input is processed, pendingoutput is flushed and deflate returns with Z_STREAM_END if there was enoughoutput space ; if deflate returns with Z_OK, this function must be called againwith Z_FINISH and more output space (updated avail_out) but no more input data,until it returns with Z_STREAM_END or an error. After deflate has returnedZ_STREAM_END, the only possible operations on the stream are deflateReset ordeflateEnd.

 

Z_FINISHcan be used immediately after deflateInit if all the compression is to be donein a single step. In this case, avail_out must be at least 0.1% larger thanavail_in plus 12 bytes. If deflate does not return Z_STREAM_END, then it mustbe called again as described above.

 

deflate()sets strm-> adler to the adler32 checksum of all input read so far (that is,total_in bytes).

 

deflate()may update data_type if it can make a good guess about the input data type(Z_ASCII or Z_BINARY). In doubt, the data is considered binary. This field isonly for information purposes and does not affect the compression algorithm inany manner.

 

deflate()returns Z_OK if some progress has been made (more input processed or moreoutput produced), Z_STREAM_END if all input has been consumed and all outputhas been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if thestream state was inconsistent (for example if next_in or next_out was NULL),Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out waszero).

 

 

intdeflateEnd (z_streamp strm);

Alldynamically allocated data structures for this stream are freed. This functiondiscards any unprocessed input and does not flush any pending output.

deflateEndreturns Z_OK if success, Z_STREAM_ERROR if the stream state was inconsistent,Z_DATA_ERROR if the stream was freed prematurely (some input or output wasdiscarded). In the error case, msg may be set but then points to a staticstring (which must not be deallocated).

 

 

intinflateInit (z_streamp strm);

Initializesthe internal stream state for decompression. The fields next_in, avail_in,zalloc, zfree and opaque must be initialized before by the caller. If next_inis not Z_NULL and avail_in is large enough (the exact value depends on thecompression method), inflateInit determines the compression method from thezlib header and allocates all data structures accordingly ; otherwise theallocation will be deferred to the first call of inflate. If zalloc and zfreeare set to Z_NULL, inflateInit updates them to use default allocationfunctions.

inflateInitreturns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_VERSION_ERROR if the zlib library version is incompatible with the versionassumed by the caller. msg is set to null if there is no error message.inflateInit does not perform any decompression apart from reading the zlibheader if present: this will be done by inflate(). (So next_in and avail_in maybe modified, but next_out and avail_out are unchanged.)

 

 

intinflate (z_streamp strm, int flush);

inflatedecompresses as much data as possible, and stops when the input buffer becomesempty or the output buffer becomes full. It may some introduce some outputlatency (reading input without producing any output) except when forced toflush.

Thedetailed semantics are as follows. inflate performs one or both of thefollowing actions:

 

Decompressmore input starting at next_in and update next_in and avail_in accordingly. Ifnot all input can be processed (because there is not enough room in the outputbuffer), next_in is updated and processing will resume at this point for thenext call of inflate().

Providemore output starting at next_out and update next_out and avail_out accordingly.inflate() provides as much output as possible, until there is no more inputdata or no more space in the output buffer (see below about the flushparameter).

Beforethe call of inflate(), the application should ensure that at least one of theactions is possible, by providing more input and/or consuming more output, andupdating the next_* and avail_* values accordingly. The application can consumethe uncompressed output when it wants, for example when the output buffer isfull (avail_out == 0), or after each call of inflate(). If inflate returns Z_OKand with zero avail_out, it must be called again after making room in theoutput buffer because there might be more output pending.

 

Ifthe parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much output aspossible to the output buffer. The flushing behavior of inflate is notspecified for values of the flush parameter other than Z_SYNC_FLUSH andZ_FINISH, but the current implementation actually flushes as much output aspossible anyway.

 

inflate()should normally be called until it returns Z_STREAM_END or an error. However ifall decompression is to be performed in a single step (a single call ofinflate), the parameter flush should be set to Z_FINISH. In this case allpending input is processed and all pending output is flushed ; avail_out mustbe large enough to hold all the uncompressed data. (The size of theuncompressed data may have been saved by the compressor for this purpose.) Thenext operation on this stream must be inflateEnd to deallocate thedecompression state. The use of Z_FINISH is never required, but can be used toinform inflate that a faster routine may be used for the single inflate() call.

 

If apreset dictionary is needed at this point (see inflateSetDictionary below),inflate sets strm-adler to the adler32 checksum of the dictionary chosen by thecompressor and returns Z_NEED_DICT ; otherwise it sets strm-> adler to theadler32 checksum of all output produced so far (that is, total_out bytes) andreturns Z_OK, Z_STREAM_END or an error code as described below. At the end ofthe stream, inflate() checks that its computed adler32 checksum is equal tothat saved by the compressor and returns Z_STREAM_END only if the checksum is correct.

 

inflate()returns Z_OK if some progress has been made (more input processed or moreoutput produced), Z_STREAM_END if the end of the compressed data has beenreached and all uncompressed output has been produced, Z_NEED_DICT if a presetdictionary is needed at this point, Z_DATA_ERROR if the input data wascorrupted (input stream not conforming to the zlib format or incorrect adler32checksum), Z_STREAM_ERROR if the stream structure was inconsistent (for exampleif next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,Z_BUF_ERROR if no progress is possible or if there was not enough room in theoutput buffer when Z_FINISH is used. In the Z_DATA_ERROR case, the applicationmay then call inflateSync to look for a good compression block.

 

 

intinflateEnd (z_streamp strm);

所有为这个stream动态分派的数据结构在这被释放。 这个函数丢弃所有未处理的输入和不输出任何未决的输出。

如果成功, inflateEnd 返回 Z_OK ;如果stream是不一致的 返回Z_STREAM_ERROR

在错误情形中,msg信息可能被设置,然后指向一个静态字符串。

 

 

 

--------------------------------------------------------------------------------

 

高级函数:

以下函数应用于特殊应用程序:

函数列表:

 

intdeflateInit2 (z_streamp strm,

intdeflateSetDictionary (z_streamp strm, const Bytef *dictionary, uIntdictLength);

intdeflateCopy (z_streamp dest, z_streamp source);

intdeflateReset (z_streamp strm);

intdeflateParams (z_streamp strm, int level, int strategy);

intinflateInit2 (z_streamp strm, int windowBits);

intinflateSetDictionary (z_streamp strm, const Bytef *dictionary, uIntdictLength);

intinflateSync (z_streamp strm);

intinflateReset (z_streamp strm);

函数说明:

 

intdeflateInit2 (z_streamp strm, int level, int method, int windowBits, intmemLevel, int strategy);

 

Thisis another version of deflateInit with more compression options. The fieldsnext_in, zalloc, zfree and opaque must be initialized before by the caller.

Themethod parameter is the compression method. It must be Z_DEFLATED in thisversion of the library.

 

ThewindowBits parameter is the base two logarithm of the window size (the size ofthe history buffer). It should be in the range 8..15 for this version of thelibrary. Larger values of this parameter result in better compression at theexpense of memory usage. The default value is 15 if deflateInit is usedinstead.

 

ThememLevel parameter specifies how much memory should be allocated for the internalcompression state. memLevel=1 uses minimum memory but is slow and reducescompression ratio ; memLevel=9 uses maximum memory for optimal speed. Thedefault value is 8. See zconf.h for total memory usage as a function ofwindowBits and memLevel.

 

Thestrategy parameter is used to tune the compression algorithm. Use the valueZ_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a filter(or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no stringmatch). Filtered data consists mostly of small values with a somewhat randomdistribution. In this case, the compression algorithm is tuned to compress thembetter. The effect of Z_FILTERED is to force more Huffman coding and lessstring matching ; it is somewhat intermediate between Z_DEFAULT andZ_HUFFMAN_ONLY. The strategy parameter only affects the compression ratio butnot the correctness of the compressed output even if it is not setappropriately.

 

deflateInit2returns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_STREAM_ERROR if a parameter is invalid (such as an invalid method). msg isset to null if there is no error message. deflateInit2 does not perform anycompression: this will be done by deflate().

 

 

intdeflateSetDictionary (z_streamp strm, const Bytef *dictionary, uIntdictLength);

Initializesthe compression dictionary from the given byte sequence without producing anycompressed output. This function must be called immediately after deflateInit,deflateInit2 or deflateReset, before any call of deflate. The compressor anddecompressor must use exactly the same dictionary (see inflateSetDictionary).

Thedictionary should consist of strings (byte sequences) that are likely to beencountered later in the data to be compressed, with the most commonly usedstrings preferably put towards the end of the dictionary. Using a dictionary ismost useful when the data to be compressed is short and can be predicted withgood accuracy ; the data can then be compressed better than with the defaultempty dictionary.

 

Dependingon the size of the compression data structures selected by deflateInit ordeflateInit2, a part of the dictionary may in effect be discarded, for exampleif the dictionary is larger than the window size in deflate or deflate2. Thusthe strings most likely to be useful should be put at the end of thedictionary, not at the front.

 

Uponreturn of this function, strm-> adler is set to the Adler32 value of thedictionary ; the decompressor may later use this value to determine whichdictionary has been used by the compressor. (The Adler32 value applies to thewhole dictionary even if only a subset of the dictionary is actually used bythe compressor.)

 

deflateSetDictionaryreturns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (such asNULL dictionary) or the stream state is inconsistent (for example if deflatehas already been called for this stream or if the compression method is bsort).deflateSetDictionary does not perform any compression: this will be done bydeflate().

 

 

intdeflateCopy (z_streamp dest, z_streamp source);

Setsthe destination stream as a complete copy of the source stream.

Thisfunction can be useful when several compression strategies will be tried, forexample when there are several ways of pre-processing the input data with afilter. The streams that will be discarded should then be freed by callingdeflateEnd. Note that deflateCopy duplicates the internal compression statewhich can be quite large, so this strategy is slow and can consume lots ofmemory.

 

deflateCopyreturns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_STREAM_ERROR if the source stream state was inconsistent (such as zallocbeing NULL). msg is left unchanged in both source and destination.

 

 

intdeflateReset (z_streamp strm);

Thisfunction is equivalent to deflateEnd followed by deflateInit, but does not freeand reallocate all the internal compression state. The stream will keep thesame compression level and any other attributes that may have been set bydeflateInit2.

deflateResetreturns Z_OK if success, or Z_STREAM_ERROR if the source stream state wasinconsistent (such as zalloc or state being NULL).

 

 

intdeflateParams (z_streamp strm, int level, int strategy);

Dynamicallyupdate the compression level and compression strategy. The interpretation oflevel and strategy is as in deflateInit2. This can be used to switch betweencompression and straight copy of the input data, or to switch to a differentkind of input data requiring a different strategy. If the compression level ischanged, the input available so far is compressed with the old level (and maybe flushed); the new level will take effect only at the next call of deflate().

Beforethe call of deflateParams, the stream state must be set as for a call ofdeflate(), since the currently available input may have to be compressed andflushed. In particular, strm-> avail_out must be non-zero.

 

deflateParamsreturns Z_OK if success, Z_STREAM_ERROR if the source stream state wasinconsistent or if a parameter was invalid, Z_BUF_ERROR if strm->avail_outwas zero.

 

 

intinflateInit2 (z_streamp strm, int windowBits);

Thisis another version of inflateInit with an extra parameter. The fields next_in,avail_in, zalloc, zfree and opaque must be initialized before by the caller.

ThewindowBits parameter is the base two logarithm of the maximum window size (thesize of the history buffer). It should be in the range 8..15 for this versionof the library. The default value is 15 if inflateInit is used instead. If acompressed stream with a larger window size is given as input, inflate() willreturn with the error code Z_DATA_ERROR instead of trying to allocate a largerwindow.

 

inflateInit2returns Z_OK if success, Z_MEM_ERROR if there was not enough memory,Z_STREAM_ERROR if a parameter is invalid (such as a negative memLevel). msg isset to null if there is no error message. inflateInit2 does not perform anydecompression apart from reading the zlib header if present: this will be doneby inflate(). (So next_in and avail_in may be modified, but next_out andavail_out are unchanged.)

 

 

intinflateSetDictionary (z_streamp strm, const Bytef *dictionary, uIntdictLength);

Initializesthe decompression dictionary from the given uncompressed byte sequence. Thisfunction must be called immediately after a call of inflate if this callreturned Z_NEED_DICT. The dictionary chosen by the compressor can be determinedfrom the Adler32 value returned by this call of inflate. The compressor anddecompressor must use exactly the same dictionary (see deflateSetDictionary).

inflateSetDictionaryreturns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (such as NULLdictionary) or the stream state is inconsistent, Z_DATA_ERROR if the givendictionary doesn't match the expected one (incorrect Adler32 value).inflateSetDictionary does not perform any decompression: this will be done bysubsequent calls of inflate().

 

 

intinflateSync (z_streamp strm);

Skipsinvalid compressed data until a full flush point (see above the description ofdeflate with Z_FULL_FLUSH) can be found, or until all available input isskipped. No output is provided.

inflateSyncreturns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more inputwas provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERRORif the stream structure was inconsistent. In the success case, the applicationmay save the current current value of total_in which indicates where validcompressed data was found. In the error case, the application may repeatedlycall inflateSync, providing more input each time, until success or end of theinput data.

 

 

intinflateReset (z_streamp strm);

这个函数伴随inflateInit,inflateEnd是等价的,但不释放和在分配所有的内部解压缩状态。

这个stream保持被inflateInit2设置的属性。

如果成功, inflateReset 返回 Z_OK ;如果stream是不一致的 返回Z_STREAM_ERROR

 

 

--------------------------------------------------------------------------------

 

校验函数

这些函数和压缩是没有关系的.但是被公开是因为他们在程序使用压缩库时,可能是有用的。

函数列表:

 

uLongadler32 (uLong adler, const Bytef *buf, uInt len);

uLongcrc32 (uLong crc, const Bytef *buf, uInt len);

函数说明:

 

uLongadler32 (uLong adler, const Bytef *buf, uInt len);

 

Updatea running Adler-32 checksum with the bytes buf[0..len-1] and return the updatedchecksum. If buf is NULL, this function returns the required initial value forthe checksum.

AnAdler-32 checksum is almost as reliable as a CRC32 but can be computed muchfaster. Usage example:

 

 

uLong adler =adler32(0L, Z_NULL, 0);

 

while(read_buffer(buffer, length) != EOF) {

adler =adler32(adler, buffer, length);

}

if (adler != original_adler)error();

uLongcrc32 (uLong crc, const Bytef *buf, uInt len);

Updatea running crc with the bytes buf[0..len-1] and return the updated crc. If bufis NULL, this function returns the required initial value for the crc. Pre- andpost-conditioning (one's complement) is performed within this function so itshouldn't be done by the application. Usage example:

 

uLong crc = crc32(0L,Z_NULL, 0);

 

while(read_buffer(buffer, length) != EOF) {

crc =crc32(crc, buffer, length);

if (crc !=original_crc) error();

 

--------------------------------------------------------------------------------

 

structz_stream_s

typedefstruct z_stream_s {

Bytef

uInt

uLong

 

Bytef

uInt

uLong

 

char

struct internal_state FAR*state; /* not visible by applications */

 

alloc_func zalloc;

free_func

voidpf

 

int

uLong

uLong

}z_stream ;

 

typedefz_stream FAR * z_streamp;  ?

 

Theapplication must update next_in and avail_in when avail_in has dropped to zero.It must update next_out and avail_out when avail_out has dropped to zero. Theapplication must initialize zalloc, zfree and opaque before calling the initfunction. All other fields are set by the compression library and must not beupdated by the application.

Theopaque value provided by the application will be passed as the first parameterfor calls of zalloc and zfree. This can be useful for custom memory management.The compression library attaches no meaning to the opaque value.

 

zallocmust return Z_NULL if there is not enough memory for the object. If zlib isused in a multi-threaded application, zalloc and zfree must be thread safe.

 

On16-bit systems, the functions zalloc and zfree must be able to allocate exactly65536 bytes, but will not be required to allocate more than this if the symbolMAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned byzalloc for objects of exactly 65536 bytes *must* have their offset normalizedto zero. The default allocation function provided by this library ensures this(see zutil.c). To reduce memory requirements and avoid any allocation of 64Kobjects, at the expense of compression ratio, compile the library with-DMAX_WBITS=14 (see zconf.h).

 

Thefields total_in and total_out can be used for statistics or progress reports.After compression, total_in holds the total size of the uncompressed data andmay be saved for use in the decompressor (particularly if the decompressorwants to decompress everything in a single step).

 

 

--------------------------------------------------------------------------------

 

常量:

#defineZ_NO_FLUSH     0

#defineZ_PARTIAL_FLUSH 1

/* 将要被删除, 使用Z_SYNC_FLUSH 代替他们 */

#defineZ_SYNC_FLUSH    2

#defineZ_FULL_FLUSH    3

#defineZ_FINISH4

/*Allowed flush values ; see deflate() below for details */

 

#defineZ_OK 0

#defineZ_STREAM_END    1

#defineZ_NEED_DICT     2

#defineZ_ERRNO(-1)

#defineZ_STREAM_ERROR (-2)

#defineZ_DATA_ERROR   (-3)

#defineZ_MEM_ERROR    (-4)

#defineZ_BUF_ERROR    (-5)

#defineZ_VERSION_ERROR (-6)

/*

 

#defineZ_NO_COMPRESSION0

#defineZ_BEST_SPEED1

#defineZ_BEST_COMPRESSION9

#defineZ_DEFAULT_COMPRESSION  (-1)

/*

 

#defineZ_FILTERED1

#defineZ_HUFFMAN_ONLY2

#defineZ_DEFAULT_STRATEGY    0

/*

 

#defineZ_BINARY   0

#defineZ_ASCII    1

#defineZ_UNKNOWN  2

/*Possible values of the data_type field */

 

#defineZ_DEFLATED   8

/*The deflate compression method (the only one supported in this version) */

 

#defineZ_NULL  0/* 用于初始化zalloc, zfree, opaque */

 

#definezlib_version zlibVersion()

/*

 

--------------------------------------------------------------------------------

 

Misc

deflateInit inflateInit 是检查zlib版本和z_stream的编译器view的宏.

另外一些函数:

constchar * zError (int err);

intinflateSyncPoint (z_streamp z);

constuLongf * get_crc_table (void);

 

--------------------------------------------------------------------------------

 

posted on 2009-01-01 16:22 肥仔 阅读(6185) 评论(0)  编辑 收藏 引用 所属分类: 压缩 & 解压


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理