2 package Compress::Zlib;
9 use Scalar::Util qw(dualvar);
11 use Compress::Zlib::Common;
12 use Compress::Zlib::ParseParameters;
17 our ($VERSION, $XS_VERSION, @ISA, @EXPORT, $AUTOLOAD);
19 $VERSION = '2.000_05';
20 $XS_VERSION = $VERSION;
21 $VERSION = eval $VERSION;
24 # Items to export into callers namespace by default. Note: do not export
25 # names by default without a very good reason. Use EXPORT_OK instead.
26 # Do not simply export all your public functions/methods/constants.
28 deflateInit inflateInit
78 ($constname = $AUTOLOAD) =~ s/.*:://;
79 my ($error, $val) = constant($constname);
80 Carp::croak $error if $error;
82 *{$AUTOLOAD} = sub { $val };
86 use constant FLAG_APPEND => 1 ;
87 use constant FLAG_CRC => 2 ;
88 use constant FLAG_ADLER => 4 ;
89 use constant FLAG_CONSUME_INPUT => 8 ;
93 XSLoader::load('Compress::Zlib', $XS_VERSION);
98 local @ISA = qw(DynaLoader);
99 bootstrap Compress::Zlib $XS_VERSION ;
102 # Preloaded methods go here.
104 require IO::Compress::Gzip;
105 require IO::Uncompress::Gunzip;
110 "need dictionary", # Z_NEED_DICT 2
111 "stream end", # Z_STREAM_END 1
113 "file error", # Z_ERRNO (-1)
114 "stream error", # Z_STREAM_ERROR (-2)
115 "data error", # Z_DATA_ERROR (-3)
116 "insufficient memory", # Z_MEM_ERROR (-4)
117 "buffer error", # Z_BUF_ERROR (-5)
118 "incompatible version",# Z_VERSION_ERROR(-6)
127 $Compress::Zlib::gzerrno = 0 ;
129 elsif ($value == Z_ERRNO() || $value > 2) {
130 $Compress::Zlib::gzerrno = $! ;
133 $Compress::Zlib::gzerrno = dualvar($value+0, $my_z_errmsg[2 - $value]);
142 my $test_eof = shift ;
144 my $value = $gz->errorNo() || 0 ;
147 #my $gz = $self->[0] ;
148 # gzread uses Z_STREAM_END to denote a successful end
149 $value = Z_STREAM_END() if $gz->eof() && $value == 0 ;
157 my ($file, $mode) = @_ ;
160 my %defOpts = (Level => Z_DEFAULT_COMPRESSION(),
161 Strategy => Z_DEFAULT_STRATEGY(),
165 $writing = ! ($mode =~ /r/i) ;
166 $writing = ($mode =~ /[wa]/i) ;
168 $defOpts{Level} = $1 if $mode =~ /(\d)/;
169 $defOpts{Strategy} = Z_FILTERED() if $mode =~ /f/i;
170 $defOpts{Strategy} = Z_HUFFMAN_ONLY() if $mode =~ /h/i;
172 my $infDef = $writing ? 'deflate' : 'inflate';
175 croak "gzopen: file parameter is not a filehandle or filename"
176 unless isaFilehandle $file || isaFilename $file ;
178 return undef unless $mode =~ /[rwa]/i ;
183 $gz = new IO::Compress::Gzip($file, Minimal => 1, AutoClose => 1, %defOpts)
184 or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError;
187 $gz = new IO::Uncompress::Gunzip($file, Append => 0, AutoClose => 1, Strict => 0)
188 or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
194 bless [$gz, $infDef], 'Compress::Zlib::gzFile';
197 sub Compress::Zlib::gzFile::gzread
201 return _set_gzerr(Z_STREAM_ERROR())
202 if $self->[1] ne 'inflate';
204 return 0 if $self->gzeof();
206 my $gz = $self->[0] ;
207 my $status = $gz->read($_[0], defined $_[1] ? $_[1] : 4096) ;
208 $_[0] = "" if ! defined $_[0] ;
213 sub Compress::Zlib::gzFile::gzreadline
217 my $gz = $self->[0] ;
218 $_[0] = $gz->getline() ;
220 return defined $_[0] ? length $_[0] : 0 ;
223 sub Compress::Zlib::gzFile::gzwrite
226 my $gz = $self->[0] ;
228 return _set_gzerr(Z_STREAM_ERROR())
229 if $self->[1] ne 'deflate';
231 my $status = $gz->write($_[0]) ;
236 sub Compress::Zlib::gzFile::gztell
239 my $gz = $self->[0] ;
240 my $status = $gz->tell() ;
245 sub Compress::Zlib::gzFile::gzseek
251 my $gz = $self->[0] ;
253 eval { $status = $gz->seek($offset, $whence) ; };
257 $error =~ s/^.*: /gzseek: /;
258 $error =~ s/ at .* line \d+\s*$//;
265 sub Compress::Zlib::gzFile::gzflush
270 my $gz = $self->[0] ;
271 my $status = $gz->flush($f) ;
276 sub Compress::Zlib::gzFile::gzclose
279 my $gz = $self->[0] ;
281 my $status = $gz->close() ;
286 sub Compress::Zlib::gzFile::gzeof
289 my $gz = $self->[0] ;
292 if $self->[1] ne 'inflate';
294 my $status = $gz->eof() ;
299 sub Compress::Zlib::gzFile::gzsetparams
302 croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
305 my $gz = $self->[0] ;
307 my $strategy = shift;
309 return _set_gzerr(Z_STREAM_ERROR())
310 if $self->[1] ne 'deflate';
312 my $status = *$gz->{Deflate}->deflateParams(-Level => $level,
313 -Strategy => $strategy);
318 sub Compress::Zlib::gzFile::gzerror
321 my $gz = $self->[0] ;
323 return $Compress::Zlib::gzerrno ;
326 sub Compress::Zlib::Deflate::new
329 my ($got) = ParseParameters(0,
331 'AppendOutput' => [Parse_boolean, 0],
332 'CRC32' => [Parse_boolean, 0],
333 'ADLER32' => [Parse_boolean, 0],
334 'Bufsize' => [Parse_unsigned, 4096],
336 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
337 'Method' => [Parse_unsigned, Z_DEFLATED()],
338 'WindowBits' => [Parse_signed, MAX_WBITS()],
339 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
340 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
341 'Dictionary' => [Parse_any, ""],
345 croak "Compress::Zlib::Deflate::new: Bufsize must be >= 1, you specified " .
346 $got->value('Bufsize')
347 unless $got->value('Bufsize') >= 1;
350 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
351 $flags |= FLAG_CRC if $got->value('CRC32') ;
352 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
355 $got->value('Level'),
356 $got->value('Method'),
357 $got->value('WindowBits'),
358 $got->value('MemLevel'),
359 $got->value('Strategy'),
360 $got->value('Bufsize'),
361 $got->value('Dictionary')) ;
365 sub Compress::Zlib::Inflate::new
368 my ($got) = ParseParameters(0,
370 'AppendOutput' => [Parse_boolean, 0],
371 'CRC32' => [Parse_boolean, 0],
372 'ADLER32' => [Parse_boolean, 0],
373 'ConsumeInput' => [Parse_boolean, 1],
374 'Bufsize' => [Parse_unsigned, 4096],
376 'WindowBits' => [Parse_signed, MAX_WBITS()],
377 'Dictionary' => [Parse_any, ""],
381 croak "Compress::Zlib::Inflate::new: Bufsize must be >= 1, you specified " .
382 $got->value('Bufsize')
383 unless $got->value('Bufsize') >= 1;
386 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
387 $flags |= FLAG_CRC if $got->value('CRC32') ;
388 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
389 $flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
391 _inflateInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
392 $got->value('Dictionary')) ;
395 sub Compress::Zlib::InflateScan::new
398 my ($got) = ParseParameters(0,
400 'CRC32' => [Parse_boolean, 0],
401 'ADLER32' => [Parse_boolean, 0],
402 'Bufsize' => [Parse_unsigned, 4096],
404 'WindowBits' => [Parse_signed, -MAX_WBITS()],
405 'Dictionary' => [Parse_any, ""],
409 croak "Compress::Zlib::InflateScan::new: Bufsize must be >= 1, you specified " .
410 $got->value('Bufsize')
411 unless $got->value('Bufsize') >= 1;
414 #$flags |= FLAG_APPEND if $got->value('AppendOutput') ;
415 $flags |= FLAG_CRC if $got->value('CRC32') ;
416 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
417 #$flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
419 _inflateScanInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
423 sub Compress::Zlib::inflateScanStream::createDeflateStream
426 my ($got) = ParseParameters(0,
428 'AppendOutput' => [Parse_boolean, 0],
429 'CRC32' => [Parse_boolean, 0],
430 'ADLER32' => [Parse_boolean, 0],
431 'Bufsize' => [Parse_unsigned, 4096],
433 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
434 'Method' => [Parse_unsigned, Z_DEFLATED()],
435 'WindowBits' => [Parse_signed, - MAX_WBITS()],
436 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
437 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
440 croak "Compress::Zlib::InflateScan::createDeflateStream: Bufsize must be >= 1, you specified " .
441 $got->value('Bufsize')
442 unless $got->value('Bufsize') >= 1;
445 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
446 $flags |= FLAG_CRC if $got->value('CRC32') ;
447 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
449 $pkg->_createDeflateStream($flags,
450 $got->value('Level'),
451 $got->value('Method'),
452 $got->value('WindowBits'),
453 $got->value('MemLevel'),
454 $got->value('Strategy'),
455 $got->value('Bufsize'),
461 sub Compress::Zlib::deflateStream::deflateParams
464 my ($got) = ParseParameters(0, {
465 'Level' => [Parse_signed, undef],
466 'Strategy' => [Parse_unsigned, undef],
467 'Bufsize' => [Parse_unsigned, undef],
471 croak "Compress::Zlib::deflateParams needs Level and/or Strategy"
472 unless $got->parsed('Level') + $got->parsed('Strategy') +
473 $got->parsed('Bufsize');
475 croak "Compress::Zlib::Inflate::deflateParams: Bufsize must be >= 1, you specified " .
476 $got->value('Bufsize')
477 if $got->parsed('Bufsize') && $got->value('Bufsize') <= 1;
480 $flags |= 1 if $got->parsed('Level') ;
481 $flags |= 2 if $got->parsed('Strategy') ;
482 $flags |= 4 if $got->parsed('Bufsize') ;
484 $self->_deflateParams($flags, $got->value('Level'),
485 $got->value('Strategy'), $got->value('Bufsize'));
491 my ($x, $output, $err, $in) =('', '', '', '') ;
495 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
501 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
503 $x = new Compress::Zlib::Deflate -AppendOutput => 1, -Level => $level
506 $err = $x->deflate($in, $output) ;
507 return undef unless $err == Z_OK() ;
509 $err = $x->flush($output) ;
510 return undef unless $err == Z_OK() ;
518 my ($x, $output, $err, $in) =('', '', '', '') ;
522 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
528 $x = new Compress::Zlib::Inflate -ConsumeInput => 0 or return undef ;
530 $err = $x->inflate($in, $output) ;
531 return undef unless $err == Z_STREAM_END() ;
537 ### This stuff is for backward compat. with Compress::Zlib 1.x
542 my ($got) = ParseParameters(0,
544 'Bufsize' => [Parse_unsigned, 4096],
545 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
546 'Method' => [Parse_unsigned, Z_DEFLATED()],
547 'WindowBits' => [Parse_signed, MAX_WBITS()],
548 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
549 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
550 'Dictionary' => [Parse_any, ""],
553 croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " .
554 $got->value('Bufsize')
555 unless $got->value('Bufsize') >= 1;
560 ($obj{def}, $status) =
562 $got->value('Level'),
563 $got->value('Method'),
564 $got->value('WindowBits'),
565 $got->value('MemLevel'),
566 $got->value('Strategy'),
567 $got->value('Bufsize'),
568 $got->value('Dictionary')) ;
570 my $x = ($status == Z_OK() ? bless \%obj, "Zlib::OldDeflate" : undef) ;
571 return wantarray ? ($x, $status) : $x ;
576 my ($got) = ParseParameters(0,
578 'Bufsize' => [Parse_unsigned, 4096],
579 'WindowBits' => [Parse_signed, MAX_WBITS()],
580 'Dictionary' => [Parse_any, ""],
584 croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " .
585 $got->value('Bufsize')
586 unless $got->value('Bufsize') >= 1;
590 ($obj{def}, $status) = _inflateInit(FLAG_CONSUME_INPUT,
591 $got->value('WindowBits'),
592 $got->value('Bufsize'),
593 $got->value('Dictionary')) ;
595 my $x = ($status == Z_OK() ? bless \%obj, "Zlib::OldInflate" : undef) ;
597 wantarray ? ($x, $status) : $x ;
600 package Zlib::OldDeflate ;
608 my $status = $self->{def}->deflate($_[0], $output) ;
610 wantarray ? ($output, $status) : $output ;
617 my $flag = shift || Compress::Zlib::Z_FINISH();
618 my $status = $self->{def}->flush($output, $flag) ;
620 wantarray ? ($output, $status) : $output ;
626 $self->{def}->deflateParams(@_) ;
632 $self->{def}->msg() ;
638 $self->{def}->total_in() ;
644 $self->{def}->total_out() ;
650 $self->{def}->dict_adler() ;
656 $self->{def}->get_Level() ;
662 $self->{def}->get_Strategy() ;
668 # $self->{def}->DispStream($_[0]) ;
671 package Zlib::OldInflate ;
677 my $status = $self->{def}->inflate($_[0], $output) ;
678 wantarray ? ($output, $status) : $output ;
684 $self->{def}->inflateSync($_[0]) ;
690 $self->{def}->msg() ;
696 $self->{def}->total_in() ;
702 $self->{def}->total_out() ;
708 $self->{def}->dict_adler() ;
714 # $self->{def}->DispStream($_[0]) ;
717 package Compress::Zlib ;
719 use Compress::Gzip::Constants;
723 my $x = new Compress::Zlib::Deflate(
727 -Level => Z_BEST_COMPRESSION(),
728 -WindowBits => - MAX_WBITS(),
732 # write a minimal gzip header
733 my $output = GZIP_MINIMUM_HEADER ;
735 # if the deflation buffer isn't a reference, make it one
736 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
738 my $status = $x->deflate($string, \$output) ;
742 $status = $x->flush(\$output) ;
746 return $output . pack("V V", $x->crc32(), $x->total_in()) ;
751 sub _removeGzipHeader($)
755 return Z_DATA_ERROR()
756 if length($$string) < GZIP_MIN_HEADER_SIZE ;
758 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
759 unpack ('CCCCVCC', $$string);
761 return Z_DATA_ERROR()
762 unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
763 $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
764 substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
767 if ($flags & GZIP_FLG_FEXTRA)
769 return Z_DATA_ERROR()
770 if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
772 my ($extra_len) = unpack ('v', $$string);
773 $extra_len += GZIP_FEXTRA_HEADER_SIZE;
774 return Z_DATA_ERROR()
775 if length($$string) < $extra_len ;
777 substr($$string, 0, $extra_len) = '';
781 if ($flags & GZIP_FLG_FNAME)
783 my $name_end = index ($$string, GZIP_NULL_BYTE);
784 return Z_DATA_ERROR()
786 substr($$string, 0, $name_end + 1) = '';
790 if ($flags & GZIP_FLG_FCOMMENT)
792 my $comment_end = index ($$string, GZIP_NULL_BYTE);
793 return Z_DATA_ERROR()
794 if $comment_end == -1 ;
795 substr($$string, 0, $comment_end + 1) = '';
799 if ($flags & GZIP_FLG_FHCRC)
801 return Z_DATA_ERROR()
802 if length ($$string) < GZIP_FHCRC_SIZE ;
803 substr($$string, 0, GZIP_FHCRC_SIZE) = '';
812 # if the buffer isn't a reference, make it one
813 my $string = (ref $_[0] ? $_[0] : \$_[0]);
815 _removeGzipHeader($string) == Z_OK()
818 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
819 my $x = new Compress::Zlib::Inflate({-WindowBits => - MAX_WBITS(),
820 -Bufsize => $bufsize})
825 my $status = $x->inflate($string, $output);
827 unless $status == Z_STREAM_END();
829 if (length $$string >= 8)
831 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
832 substr($$string, 0, 8) = '';
834 unless $len == length($output) and
835 $crc == crc32($output);
844 # Autoload methods go after __END__, and are processed by the autosplit program.
852 Compress::Zlib - Interface to zlib compression library
856 use Compress::Zlib 2 ;
858 ($d, $status) = new Compress::Zlib::Deflate( [OPT] ) ;
859 $status = $d->deflate($input, $output) ;
860 $status = $d->flush($output [, $flush_type]) ;
861 $d->deflateParams(OPTS) ;
862 $d->deflateTune(OPTS) ;
873 ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) ;
874 $status = $i->inflate($input, $output) ;
875 $status = $i->inflateSync($input) ;
884 $dest = compress($source) ;
885 $dest = uncompress($source) ;
887 $gz = gzopen($filename or filehandle, $mode) ;
888 $bytesread = $gz->gzread($buffer [,$size]) ;
889 $bytesread = $gz->gzreadline($line) ;
890 $byteswritten = $gz->gzwrite($buffer) ;
891 $status = $gz->gzflush($flush) ;
892 $offset = $gz->gztell() ;
893 $status = $gz->gzseek($offset, $whence) ;
894 $status = $gz->gzclose() ;
895 $status = $gz->gzeof() ;
896 $status = $gz->gzsetparams($level, $strategy) ;
897 $errstring = $gz->gzerror() ;
900 $dest = Compress::Zlib::memGzip($buffer) ;
901 $dest = Compress::Zlib::memGunzip($buffer) ;
903 $crc = adler32($buffer [,$crc]) ;
904 $crc = crc32($buffer [,$crc]) ;
906 $crc = adler32_combine($crc1, $crc2, $len2)l
907 $crc = crc32_combine($adler1, $adler2, $len2)
912 # Compress::Zlib 1.x legacy interface
914 ($d, $status) = deflateInit( [OPT] ) ;
915 ($out, $status) = $d->deflate($buffer) ;
916 $status = $d->deflateParams([OPT]) ;
917 ($out, $status) = $d->flush() ;
923 ($i, $status) = inflateInit( [OPT] ) ;
924 ($out, $status) = $i->inflate($buffer) ;
925 $status = $i->inflateSync($buffer) ;
934 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
935 compression library (see L</AUTHOR> for details about where to get
937 The I<zlib> library allows reading and writing of
938 compressed data streams that conform to RFC1950, RFC1951 and RFC1952
940 Most of the I<zlib> functionality is available in I<Compress::Zlib>.
942 Unless you are working with legacy code, or you need to work directly
943 with the low-level zlib interface, it is recommended that applications
944 use one of the newer C<IO::*> interfaces provided with this module.
946 The C<Compress::Zlib> module can be split into two general areas of
947 functionality, namely a low-level in-memory compression/decompression
948 interface and a simple read/write interface to I<gzip> files.
950 Each of these areas will be discussed separately below.
953 =head1 GZIP INTERFACE
955 A number of functions are supplied in I<zlib> for reading and writing
956 I<gzip> files that conform to RFC1952. This module provides an interface
959 If you are upgrading from C<Compress::Zlib> 1.x, the following enhancements
960 have been made to the C<gzopen> interface:
966 If you want to to open either STDIN or STDOUT with C<gzopen>, you can
967 optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
972 In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open the
973 underlying file. This made things especially tricky when a Perl filehandle was
974 passed to C<gzopen>. Behind the scenes the numeric C file descriptor had to be
975 extracted from the Perl filehandle and this passed to the zlib library.
977 Apart from being non-portable to some operating systems, this made it difficult
978 to use C<gzopen> in situations where you wanted to extract/create a gzip data
979 stream that is embedded in a larger file, without having to resort to opening
980 and closing the file multiple times.
982 In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been completely
983 rewritten to use the L<IO::Compress::Gzip|IO::Compress::Gzip> for writing gzip files and
984 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for reading gzip files.
988 Addition of C<gzseek> to provide a restricted C<seek> interface.
996 A more complete and flexible interface for reading/writing gzip files/buffers
997 is included with this module. See L<IO::Compress::Gzip|IO::Compress::Gzip> and
998 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for more details.
1002 =item B<$gz = gzopen($filename, $mode)>
1004 =item B<$gz = gzopen($filehandle, $mode)>
1006 This function opens either the I<gzip> file C<$filename> for reading or writing
1007 or attaches to the opened filehandle, C<$filehandle>. It returns an object on
1008 success and C<undef> on failure.
1010 When writing a gzip file this interface will always create the smallest
1011 possible gzip header (exactly 10 bytes). If you want control over the
1012 information stored in the gzip header (like the original filename or a comment)
1013 use L<IO::Compress::Gzip|IO::Compress::Gzip> instead.
1015 The second parameter, C<$mode>, is used to specify whether the file is
1016 opened for reading or writing and to optionally specify a compression
1017 level and compression strategy when writing. The format of the C<$mode>
1018 parameter is similar to the mode parameter to the 'C' function C<fopen>,
1019 so "rb" is used to open for reading and "wb" for writing.
1021 To specify a compression level when writing, append a digit between 0
1022 and 9 to the mode string -- 0 means no compression and 9 means maximum
1024 If no compression level is specified Z_DEFAULT_COMPRESSION is used.
1026 To specify the compression strategy when writing, append 'f' for filtered
1027 data, 'h' for Huffman only compression, or 'R' for run-length encoding.
1028 If no strategy is specified Z_DEFAULT_STRATEGY is used.
1030 So, for example, "wb9" means open for writing with the maximum compression
1031 using the default strategy and "wb4R" means open for writing with compression
1032 level 4 and run-length encoding.
1034 Refer to the I<zlib> documentation for the exact format of the C<$mode>
1038 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
1040 Reads C<$size> bytes from the compressed file into C<$buffer>. If
1041 C<$size> is not specified, it will default to 4096. If the scalar
1042 C<$buffer> is not large enough, it will be extended automatically.
1044 Returns the number of bytes actually read. On EOF it returns 0 and in
1045 the case of an error, -1.
1047 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
1049 Reads the next line from the compressed file into C<$line>.
1051 Returns the number of bytes actually read. On EOF it returns 0 and in
1052 the case of an error, -1.
1054 It is legal to intermix calls to C<gzread> and C<gzreadline>.
1056 In addition, C<gzreadline> fully supports the use of of the variable C<$/>
1057 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
1058 determine what constitutes an end of line. Both paragraph mode and file
1059 slurp mode are supported.
1062 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
1064 Writes the contents of C<$buffer> to the compressed file. Returns the
1065 number of bytes actually written, or 0 on error.
1067 =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
1069 Flushes all pending output into the compressed file.
1071 This method takes an optional parameter, C<$flush_type>, that controls
1072 how the flushing will be carried out. By default the C<$flush_type>
1073 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1074 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1075 strongly recommended that you only set the C<flush_type> parameter if
1076 you fully understand the implications of what it does - overuse of C<flush>
1077 can seriously degrade the level of compression achieved. See the C<zlib>
1078 documentation for details.
1080 Returns 1 on success, 0 on failure.
1083 =item B<$offset = $gz-E<gt>gztell() ;>
1085 Returns the uncompressed file offset.
1087 =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
1089 Sets the file position of the
1091 Provides a sub-set of the C<seek> functionality, with the restriction
1092 that it is only legal to seek forward in the compressed file.
1093 It is a fatal error to attempt to seek backward.
1095 When opened for writing, empty parts of the file will have NULL (0x00)
1096 bytes written to them.
1098 The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
1100 Returns 1 on success, 0 on failure.
1102 =item B<$gz-E<gt>gzclose>
1104 Closes the compressed file. Any pending data is flushed to the file
1105 before it is closed.
1107 Returns 1 on success, 0 on failure.
1109 =item B<$gz-E<gt>gzsetparams($level, $strategy>
1111 Change settings for the deflate stream C<$gz>.
1113 The list of the valid options is shown below. Options not specified
1114 will remain unchanged.
1116 Note: This method is only available if you are running zlib 1.0.6 or better.
1122 Defines the compression level. Valid values are 0 through 9,
1123 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1124 C<Z_DEFAULT_COMPRESSION>.
1128 Defines the strategy used to tune the compression. The valid values are
1129 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1133 =item B<$gz-E<gt>gzerror>
1135 Returns the I<zlib> error message or number for the last operation
1136 associated with C<$gz>. The return value will be the I<zlib> error
1137 number when used in a numeric context and the I<zlib> error message
1138 when used in a string context. The I<zlib> error number constants,
1139 shown below, are available for use.
1151 The C<$gzerrno> scalar holds the error code associated with the most
1152 recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
1153 I<not> associated with a particular file.
1155 As with C<gzerror()> it returns an error number in numeric context and
1156 an error message in string context. Unlike C<gzerror()> though, the
1157 error message will correspond to the I<zlib> message when the error is
1158 associated with I<zlib> itself, or the UNIX error message when it is
1159 not (i.e. I<zlib> returned C<Z_ERRORNO>).
1161 As there is an overlap between the error numbers used by I<zlib> and
1162 UNIX, C<$gzerrno> should only be used to check for the presence of
1163 I<an> error in numeric context. Use C<gzerror()> to check for specific
1164 I<zlib> errors. The I<gzcat> example below shows how the variable can
1172 Here is an example script which uses the interface. It implements a
1178 use Compress::Zlib ;
1180 # use stdin if no files supplied
1181 @ARGV = '-' unless @ARGV ;
1183 foreach my $file (@ARGV) {
1186 my $gz = gzopen($file, "rb")
1187 or die "Cannot open $file: $gzerrno\n" ;
1189 print $buffer while $gz->gzread($buffer) > 0 ;
1191 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
1192 if $gzerrno != Z_STREAM_END ;
1197 Below is a script which makes use of C<gzreadline>. It implements a
1198 very simple I<grep> like script.
1203 use Compress::Zlib ;
1205 die "Usage: gzgrep pattern [file...]\n"
1208 my $pattern = shift ;
1210 # use stdin if no files supplied
1211 @ARGV = '-' unless @ARGV ;
1213 foreach my $file (@ARGV) {
1214 my $gz = gzopen($file, "rb")
1215 or die "Cannot open $file: $gzerrno\n" ;
1217 while ($gz->gzreadline($_) > 0) {
1218 print if /$pattern/ ;
1221 die "Error reading from $file: $gzerrno\n"
1222 if $gzerrno != Z_STREAM_END ;
1227 This script, I<gzstream>, does the opposite of the I<gzcat> script
1228 above. It reads from standard input and writes a gzip data stream to
1234 use Compress::Zlib ;
1236 binmode STDOUT; # gzopen only sets it on the fd
1238 my $gz = gzopen(\*STDOUT, "wb")
1239 or die "Cannot open stdout: $gzerrno\n" ;
1243 or die "error writing: $gzerrno\n" ;
1248 =head2 Compress::Zlib::memGzip
1250 This function is used to create an in-memory gzip file with the minimum
1251 possible gzip header (exactly 10 bytes).
1253 $dest = Compress::Zlib::memGzip($buffer) ;
1255 If successful, it returns the in-memory gzip file, otherwise it returns
1258 The C<$buffer> parameter can either be a scalar or a scalar reference.
1260 See L<IO::Compress::Gzip|IO::Compress::Gzip> for an alternative way to carry out in-memory gzip
1263 =head2 Compress::Zlib::memGunzip
1265 This function is used to uncompress an in-memory gzip file.
1267 $dest = Compress::Zlib::memGunzip($buffer) ;
1269 If successful, it returns the uncompressed gzip file, otherwise it
1272 The C<$buffer> parameter can either be a scalar or a scalar reference. The
1273 contents of the C<$buffer> parameter are destroyed after calling this function.
1275 See L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for an alternative way to carry out in-memory gzip
1278 =head1 COMPRESS/UNCOMPRESS
1280 Two functions are provided to perform in-memory compression/uncompression of
1281 RFC 1950 data streams. They are called C<compress> and C<uncompress>.
1285 =item B<$dest = compress($source [, $level] ) ;>
1287 Compresses C<$source>. If successful it returns the compressed
1288 data. Otherwise it returns I<undef>.
1290 The source buffer, C<$source>, can either be a scalar or a scalar
1293 The C<$level> parameter defines the compression level. Valid values are
1294 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
1295 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
1296 If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
1299 =item B<$dest = uncompress($source) ;>
1301 Uncompresses C<$source>. If successful it returns the uncompressed
1302 data. Otherwise it returns I<undef>.
1304 The source buffer can either be a scalar or a scalar reference.
1308 Please note: the two functions defined above are I<not> compatible with
1309 the Unix commands of the same name.
1311 See L<IO::Compress::Deflate|IO::Compress::Deflate> and L<IO::Uncompress::Inflate|IO::Uncompress::Inflate> included with
1312 this distribution for an alternative interface for reading/writing RFC 1950
1315 =head1 CHECKSUM FUNCTIONS
1317 Two functions are provided by I<zlib> to calculate checksums. For the
1318 Perl interface, the order of the two parameters in both functions has
1319 been reversed. This allows both running checksums and one off
1320 calculations to be done.
1322 $crc = adler32($buffer [,$crc]) ;
1323 $crc = crc32($buffer [,$crc]) ;
1325 The buffer parameters can either be a scalar or a scalar reference.
1327 If the $crc parameters is C<undef>, the crc value will be reset.
1329 If you have built this module with zlib 1.2.3 or better, two more
1330 CRC-related functions are available.
1332 $crc = adler32_combine($crc1, $crc2, $len2)l
1333 $crc = crc32_combine($adler1, $adler2, $len2)
1335 These functions allow checksums to be merged.
1337 =head1 Compress::Zlib::Deflate
1339 This section defines an interface that allows in-memory compression using
1340 the I<deflate> interface provided by zlib.
1342 Note: The interface defined in this section is different from version
1343 1.x of this module. The original deflate interface is still available
1344 for backward compatibility and is documented in the section
1345 L<Compress::Zlib 1.x Deflate Interface>.
1347 Here is a definition of the interface available:
1350 =head2 B<($d, $status) = new Compress::Zlib::Deflate( [OPT] ) >
1352 Initialises a deflation object.
1354 If you are familiar with the I<zlib> library, it combines the
1355 features of the I<zlib> functions C<deflateInit>, C<deflateInit2>
1356 and C<deflateSetDictionary>.
1358 If successful, it will return the initialised deflation object, C<$d>
1359 and a C<$status> of C<Z_OK> in a list context. In scalar context it
1360 returns the deflation object, C<$d>, only.
1362 If not successful, the returned deflation object, C<$d>, will be
1363 I<undef> and C<$status> will hold the a I<zlib> error code.
1365 The function optionally takes a number of named options specified as
1366 C<-Name =E<gt> value> pairs. This allows individual options to be
1367 tailored without having to specify them all in the parameter list.
1369 For backward compatibility, it is also possible to pass the parameters
1370 as a reference to a hash containing the name=>value pairs.
1372 Below is a list of the valid options:
1378 Defines the compression level. Valid values are 0 through 9,
1379 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1380 C<Z_DEFAULT_COMPRESSION>.
1382 The default is C<-Level =E<gt> Z_DEFAULT_COMPRESSION>.
1386 Defines the compression method. The only valid value at present (and
1387 the default) is C<-Method =E<gt> Z_DEFLATED>.
1389 =item B<-WindowBits>
1391 For a definition of the meaning and valid values for C<WindowBits>
1392 refer to the I<zlib> documentation for I<deflateInit2>.
1394 Defaults to C<-WindowBits =E<gt> MAX_WBITS>.
1398 For a definition of the meaning and valid values for C<MemLevel>
1399 refer to the I<zlib> documentation for I<deflateInit2>.
1401 Defaults to C<-MemLevel =E<gt> MAX_MEM_LEVEL>.
1405 Defines the strategy used to tune the compression. The valid values are
1406 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED>, C<Z_RLE>, C<Z_FIXED> and
1409 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1411 =item B<-Dictionary>
1413 When a dictionary is specified I<Compress::Zlib> will automatically
1414 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1415 Adler32 value for the dictionary can be obtained by calling the method
1416 C<$d-E<gt>dict_adler()>.
1418 The default is no dictionary.
1422 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1423 and C<$d-E<gt>flush> methods. If the buffer has to be
1424 reallocated to increase the size, it will grow in increments of
1427 The default buffer size is 4096.
1429 =item B<-AppendOutput>
1431 This option controls how data is written to the output buffer by the
1432 C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1434 If the C<AppendOutput> option is set to false, the output buffers in the
1435 C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods will be truncated before
1436 uncompressed data is written to them.
1438 If the option is set to true, uncompressed data will be appended to the
1439 output buffer in the C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1441 This option defaults to false.
1445 If set to true, a crc32 checksum of the uncompressed data will be
1446 calculated. Use the C<$d-E<gt>crc32> method to retrieve this value.
1448 This option defaults to false.
1453 If set to true, an adler32 checksum of the uncompressed data will be
1454 calculated. Use the C<$d-E<gt>adler32> method to retrieve this value.
1456 This option defaults to false.
1461 Here is an example of using the C<Compress::Zlib::Deflate> optional
1462 parameter list to override the default buffer size and compression
1463 level. All other options will take their default values.
1465 my $d = new Compress::Zlib::Deflate ( -Bufsize => 300,
1466 -Level => Z_BEST_SPEED ) ;
1469 =head2 B<$status = $d-E<gt>deflate($input, $output)>
1471 Deflates the contents of C<$input> and writes the compressed data to
1474 The C<$input> and C<$output> parameters can be either scalars or scalar
1477 When finished, C<$input> will be completely processed (assuming there
1478 were no errors). If the deflation was successful it writes the deflated
1479 data to C<$output> and returns a status value of C<Z_OK>.
1481 On error, it returns a I<zlib> error code.
1483 If the C<AppendOutput> option is set to true in the constructor for
1484 the C<$d> object, the compressed data will be appended to C<$output>. If
1485 it is false, C<$output> will be truncated before any compressed data is
1488 B<Note>: This method will not necessarily write compressed data to
1489 C<$output> every time it is called. So do not assume that there has been
1490 an error if the contents of C<$output> is empty on returning from
1491 this method. As long as the return code from the method is C<Z_OK>,
1492 the deflate has succeeded.
1494 =head2 B<$status = $d-E<gt>flush($output [, $flush_type]) >
1496 Typically used to finish the deflation. Any pending output will be
1497 written to C<$output>.
1499 Returns C<Z_OK> if successful.
1501 Note that flushing can seriously degrade the compression ratio, so it
1502 should only be used to terminate a decompression (using C<Z_FINISH>) or
1503 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1505 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1506 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1507 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1508 C<flush_type> parameter if you fully understand the implications of
1509 what it does. See the C<zlib> documentation for details.
1511 If the C<AppendOutput> option is set to true in the constructor for
1512 the C<$d> object, the compressed data will be appended to C<$output>. If
1513 it is false, C<$output> will be truncated before any compressed data is
1516 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1518 Change settings for the deflate object C<$d>.
1520 The list of the valid options is shown below. Options not specified
1521 will remain unchanged.
1528 Defines the compression level. Valid values are 0 through 9,
1529 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1530 C<Z_DEFAULT_COMPRESSION>.
1534 Defines the strategy used to tune the compression. The valid values are
1535 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1539 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1540 and C<$d-E<gt>flush> methods. If the buffer has to be
1541 reallocated to increase the size, it will grow in increments of
1547 =head2 B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)>
1549 Tune the internal settings for the deflate object C<$d>. This option is
1550 only available if you are running zlib 1.2.2.3 or better.
1552 Refer to the documentation in zlib.h for instructions on how to fly
1555 =head2 B<$d-E<gt>dict_adler()>
1557 Returns the adler32 value for the dictionary.
1559 =head2 B<$d-E<gt>crc32()>
1561 Returns the crc32 value for the uncompressed data to date.
1563 If the C<CRC32> option is not enabled in the constructor for this object,
1564 this method will always return 0;
1566 =head2 B<$d-E<gt>adler32()>
1568 Returns the adler32 value for the uncompressed data to date.
1570 =head2 B<$d-E<gt>msg()>
1572 Returns the last error message generated by zlib.
1574 =head2 B<$d-E<gt>total_in()>
1576 Returns the total number of bytes uncompressed bytes input to deflate.
1578 =head2 B<$d-E<gt>total_out()>
1580 Returns the total number of compressed bytes output from deflate.
1582 =head2 B<$d-E<gt>get_Strategy()>
1584 Returns the deflation strategy currently used. Valid values are
1585 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1588 =head2 B<$d-E<gt>get_Level()>
1590 Returns the compression level being used.
1592 =head2 B<$d-E<gt>get_BufSize()>
1594 Returns the buffer size used to carry out the compression.
1599 Here is a trivial example of using C<deflate>. It simply reads standard
1600 input, deflates it and writes it to standard output.
1605 use Compress::Zlib 2 ;
1609 my $x = new Compress::Zlib::Deflate
1610 or die "Cannot create a deflation stream\n" ;
1612 my ($output, $status) ;
1615 $status = $x->deflate($_, $output) ;
1618 or die "deflation failed\n" ;
1623 $status = $x->flush($output) ;
1626 or die "deflation failed\n" ;
1630 =head1 Compress::Zlib::Inflate
1632 This section defines an interface that allows in-memory uncompression using
1633 the I<inflate> interface provided by zlib.
1635 Note: The interface defined in this section is different from version
1636 1.x of this module. The original inflate interface is still available
1637 for backward compatibility and is documented in the section
1638 L<Compress::Zlib 1.x Inflate Interface>.
1640 Here is a definition of the interface:
1643 =head2 B< ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) >
1645 Initialises an inflation object.
1647 In a list context it returns the inflation object, C<$i>, and the
1648 I<zlib> status code (C<$status>). In a scalar context it returns the
1649 inflation object only.
1651 If successful, C<$i> will hold the inflation object and C<$status> will
1654 If not successful, C<$i> will be I<undef> and C<$status> will hold the
1657 The function optionally takes a number of named options specified as
1658 C<-Name =E<gt> value> pairs. This allows individual options to be
1659 tailored without having to specify them all in the parameter list.
1661 For backward compatibility, it is also possible to pass the parameters
1662 as a reference to a hash containing the name=E<gt>value pairs.
1664 Here is a list of the valid options:
1668 =item B<-WindowBits>
1670 For a definition of the meaning and valid values for C<WindowBits>
1671 refer to the I<zlib> documentation for I<inflateInit2>.
1673 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1677 Sets the initial size for the output buffer used by the C<$i-E<gt>inflate>
1678 method. If the output buffer in this method has to be reallocated to
1679 increase the size, it will grow in increments of C<Bufsize>.
1683 =item B<-Dictionary>
1685 The default is no dictionary.
1687 =item B<-AppendOutput>
1689 This option controls how data is written to the output buffer by the
1690 C<$i-E<gt>inflate> method.
1692 If the option is set to false, the output buffer in the C<$i-E<gt>inflate>
1693 method will be truncated before uncompressed data is written to it.
1695 If the option is set to true, uncompressed data will be appended to the
1696 output buffer by the C<$i-E<gt>inflate> method.
1698 This option defaults to false.
1703 If set to true, a crc32 checksum of the uncompressed data will be
1704 calculated. Use the C<$i-E<gt>crc32> method to retrieve this value.
1706 This option defaults to false.
1710 If set to true, an adler32 checksum of the uncompressed data will be
1711 calculated. Use the C<$i-E<gt>adler32> method to retrieve this value.
1713 This option defaults to false.
1715 =item B<-ConsumeInput>
1717 If set to true, this option will remove compressed data from the input
1718 buffer of the the C< $i-E<gt>inflate > method as the inflate progresses.
1720 This option can be useful when you are processing compressed data that is
1721 embedded in another file/buffer. In this case the data that immediately
1722 follows the compressed stream will be left in the input buffer.
1724 This option defaults to true.
1728 Here is an example of using an optional parameter to override the default
1731 my ($i, $status) = new Compress::Zlib::Inflate( -Bufsize => 300 ) ;
1733 =head2 B< $status = $i-E<gt>inflate($input, $output) >
1735 Inflates the complete contents of C<$input> and writes the uncompressed
1736 data to C<$output>. The C<$input> and C<$output> parameters can either be
1737 scalars or scalar references.
1739 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1740 compressed data has been successfully reached.
1742 If not successful C<$status> will hold the I<zlib> error code.
1744 If the C<ConsumeInput> option has been set to true when the
1745 C<Compress::Zlib::Inflate> object is created, the C<$input> parameter
1746 is modified by C<inflate>. On completion it will contain what remains
1747 of the input buffer after inflation. In practice, this means that when
1748 the return status is C<Z_OK> the C<$input> parameter will contain an
1749 empty string, and when the return status is C<Z_STREAM_END> the C<$input>
1750 parameter will contains what (if anything) was stored in the input buffer
1751 after the deflated data stream.
1753 This feature is useful when processing a file format that encapsulates
1754 a compressed data stream (e.g. gzip, zip) and there is useful data
1755 immediately after the deflation stream.
1757 If the C<AppendOutput> option is set to true in the constructor for
1758 this object, the uncompressed data will be appended to C<$output>. If
1759 it is false, C<$output> will be truncated before any uncompressed data
1762 =head2 B<$status = $i-E<gt>inflateSync($input)>
1764 This method can be used to attempt to recover good data from a compressed
1765 data stream that is partially corrupt.
1766 It scans C<$input> until it reaches either a I<full flush point> or the
1769 If a I<full flush point> is found, C<Z_OK> is returned and C<$input>
1770 will be have all data up to the flush point removed. This data can then be
1771 passed to the C<$i-E<gt>inflate> method to be uncompressed.
1773 Any other return code means that a flush point was not found. If more
1774 data is available, C<inflateSync> can be called repeatedly with more
1775 compressed data until the flush point is found.
1777 Note I<full flush points> are not present by default in compressed
1778 data streams. They must have been added explicitly when the data stream
1779 was created by calling C<Compress::Deflate::flush> with C<Z_FULL_FLUSH>.
1782 =head2 B<$i-E<gt>dict_adler()>
1784 Returns the adler32 value for the dictionary.
1786 =head2 B<$i-E<gt>crc32()>
1788 Returns the crc32 value for the uncompressed data to date.
1790 If the C<CRC32> option is not enabled in the constructor for this object,
1791 this method will always return 0;
1793 =head2 B<$i-E<gt>adler32()>
1795 Returns the adler32 value for the uncompressed data to date.
1797 If the C<ADLER32> option is not enabled in the constructor for this object,
1798 this method will always return 0;
1800 =head2 B<$i-E<gt>msg()>
1802 Returns the last error message generated by zlib.
1804 =head2 B<$i-E<gt>total_in()>
1806 Returns the total number of bytes compressed bytes input to inflate.
1808 =head2 B<$i-E<gt>total_out()>
1810 Returns the total number of uncompressed bytes output from inflate.
1812 =head2 B<$d-E<gt>get_BufSize()>
1814 Returns the buffer size used to carry out the decompression.
1818 Here is an example of using C<inflate>.
1823 use Compress::Zlib 2 ;
1825 my $x = new Compress::Zlib::Inflate()
1826 or die "Cannot create a inflation stream\n" ;
1832 my ($output, $status) ;
1833 while (read(STDIN, $input, 4096))
1835 $status = $x->inflate(\$input, $output) ;
1838 if $status == Z_OK or $status == Z_STREAM_END ;
1840 last if $status != Z_OK ;
1843 die "inflation failed\n"
1844 unless $status == Z_STREAM_END ;
1846 =head1 Compress::Zlib 1.x Deflate Interface
1848 This section defines the interface available in C<Compress::Zlib> version
1849 1.x that allows in-memory compression using the I<deflate> interface
1852 Here is a definition of the interface available:
1855 =head2 B<($d, $status) = deflateInit( [OPT] )>
1857 Initialises a deflation stream.
1859 It combines the features of the I<zlib> functions C<deflateInit>,
1860 C<deflateInit2> and C<deflateSetDictionary>.
1862 If successful, it will return the initialised deflation stream, C<$d>
1863 and C<$status> of C<Z_OK> in a list context. In scalar context it
1864 returns the deflation stream, C<$d>, only.
1866 If not successful, the returned deflation stream (C<$d>) will be
1867 I<undef> and C<$status> will hold the exact I<zlib> error code.
1869 The function optionally takes a number of named options specified as
1870 C<-Name=E<gt>value> pairs. This allows individual options to be
1871 tailored without having to specify them all in the parameter list.
1873 For backward compatibility, it is also possible to pass the parameters
1874 as a reference to a hash containing the name=>value pairs.
1876 The function takes one optional parameter, a reference to a hash. The
1877 contents of the hash allow the deflation interface to be tailored.
1879 Here is a list of the valid options:
1885 Defines the compression level. Valid values are 0 through 9,
1886 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1887 C<Z_DEFAULT_COMPRESSION>.
1889 The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
1893 Defines the compression method. The only valid value at present (and
1894 the default) is C<-Method =E<gt>Z_DEFLATED>.
1896 =item B<-WindowBits>
1898 For a definition of the meaning and valid values for C<WindowBits>
1899 refer to the I<zlib> documentation for I<deflateInit2>.
1901 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1905 For a definition of the meaning and valid values for C<MemLevel>
1906 refer to the I<zlib> documentation for I<deflateInit2>.
1908 Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
1912 Defines the strategy used to tune the compression. The valid values are
1913 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1915 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1917 =item B<-Dictionary>
1919 When a dictionary is specified I<Compress::Zlib> will automatically
1920 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1921 Adler32 value for the dictionary can be obtained by calling the method
1922 C<$d->dict_adler()>.
1924 The default is no dictionary.
1928 Sets the initial size for the deflation buffer. If the buffer has to be
1929 reallocated to increase the size, it will grow in increments of
1932 The default is 4096.
1936 Here is an example of using the C<deflateInit> optional parameter list
1937 to override the default buffer size and compression level. All other
1938 options will take their default values.
1940 deflateInit( -Bufsize => 300,
1941 -Level => Z_BEST_SPEED ) ;
1944 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1947 Deflates the contents of C<$buffer>. The buffer can either be a scalar
1948 or a scalar reference. When finished, C<$buffer> will be
1949 completely processed (assuming there were no errors). If the deflation
1950 was successful it returns the deflated output, C<$out>, and a status
1951 value, C<$status>, of C<Z_OK>.
1953 On error, C<$out> will be I<undef> and C<$status> will contain the
1956 In a scalar context C<deflate> will return C<$out> only.
1958 As with the I<deflate> function in I<zlib>, it is not necessarily the
1959 case that any output will be produced by this method. So don't rely on
1960 the fact that C<$out> is empty for an error test.
1963 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
1965 Typically used to finish the deflation. Any pending output will be
1966 returned via C<$out>.
1967 C<$status> will have a value C<Z_OK> if successful.
1969 In a scalar context C<flush> will return C<$out> only.
1971 Note that flushing can seriously degrade the compression ratio, so it
1972 should only be used to terminate a decompression (using C<Z_FINISH>) or
1973 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1975 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1976 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1977 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1978 C<flush_type> parameter if you fully understand the implications of
1979 what it does. See the C<zlib> documentation for details.
1981 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1983 Change settings for the deflate stream C<$d>.
1985 The list of the valid options is shown below. Options not specified
1986 will remain unchanged.
1992 Defines the compression level. Valid values are 0 through 9,
1993 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1994 C<Z_DEFAULT_COMPRESSION>.
1998 Defines the strategy used to tune the compression. The valid values are
1999 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
2003 =head2 B<$d-E<gt>dict_adler()>
2005 Returns the adler32 value for the dictionary.
2007 =head2 B<$d-E<gt>msg()>
2009 Returns the last error message generated by zlib.
2011 =head2 B<$d-E<gt>total_in()>
2013 Returns the total number of bytes uncompressed bytes input to deflate.
2015 =head2 B<$d-E<gt>total_out()>
2017 Returns the total number of compressed bytes output from deflate.
2022 Here is a trivial example of using C<deflate>. It simply reads standard
2023 input, deflates it and writes it to standard output.
2028 use Compress::Zlib ;
2032 my $x = deflateInit()
2033 or die "Cannot create a deflation stream\n" ;
2035 my ($output, $status) ;
2038 ($output, $status) = $x->deflate($_) ;
2041 or die "deflation failed\n" ;
2046 ($output, $status) = $x->flush() ;
2049 or die "deflation failed\n" ;
2053 =head1 Compress::Zlib 1.x Inflate Interface
2055 This section defines the interface available in C<Compress::Zlib> version
2056 1.x that allows in-memory uncompression using the I<deflate> interface
2059 Here is a definition of the interface:
2062 =head2 B<($i, $status) = inflateInit()>
2064 Initialises an inflation stream.
2066 In a list context it returns the inflation stream, C<$i>, and the
2067 I<zlib> status code (C<$status>). In a scalar context it returns the
2068 inflation stream only.
2070 If successful, C<$i> will hold the inflation stream and C<$status> will
2073 If not successful, C<$i> will be I<undef> and C<$status> will hold the
2076 The function optionally takes a number of named options specified as
2077 C<-Name=E<gt>value> pairs. This allows individual options to be
2078 tailored without having to specify them all in the parameter list.
2080 For backward compatibility, it is also possible to pass the parameters
2081 as a reference to a hash containing the name=>value pairs.
2083 The function takes one optional parameter, a reference to a hash. The
2084 contents of the hash allow the deflation interface to be tailored.
2086 Here is a list of the valid options:
2090 =item B<-WindowBits>
2092 For a definition of the meaning and valid values for C<WindowBits>
2093 refer to the I<zlib> documentation for I<inflateInit2>.
2095 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
2099 Sets the initial size for the inflation buffer. If the buffer has to be
2100 reallocated to increase the size, it will grow in increments of
2105 =item B<-Dictionary>
2107 The default is no dictionary.
2111 Here is an example of using the C<inflateInit> optional parameter to
2112 override the default buffer size.
2114 inflateInit( -Bufsize => 300 ) ;
2116 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
2118 Inflates the complete contents of C<$buffer>. The buffer can either be
2119 a scalar or a scalar reference.
2121 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
2122 compressed data has been successfully reached.
2123 If not successful, C<$out> will be I<undef> and C<$status> will hold
2124 the I<zlib> error code.
2126 The C<$buffer> parameter is modified by C<inflate>. On completion it
2127 will contain what remains of the input buffer after inflation. This
2128 means that C<$buffer> will be an empty string when the return status is
2129 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
2130 parameter will contains what (if anything) was stored in the input
2131 buffer after the deflated data stream.
2133 This feature is useful when processing a file format that encapsulates
2134 a compressed data stream (e.g. gzip, zip).
2136 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
2138 Scans C<$buffer> until it reaches either a I<full flush point> or the
2141 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
2142 will be have all data up to the flush point removed. This can then be
2143 passed to the C<deflate> method.
2145 Any other return code means that a flush point was not found. If more
2146 data is available, C<inflateSync> can be called repeatedly with more
2147 compressed data until the flush point is found.
2150 =head2 B<$i-E<gt>dict_adler()>
2152 Returns the adler32 value for the dictionary.
2154 =head2 B<$i-E<gt>msg()>
2156 Returns the last error message generated by zlib.
2158 =head2 B<$i-E<gt>total_in()>
2160 Returns the total number of bytes compressed bytes input to inflate.
2162 =head2 B<$i-E<gt>total_out()>
2164 Returns the total number of uncompressed bytes output from inflate.
2168 Here is an example of using C<inflate>.
2173 use Compress::Zlib ;
2175 my $x = inflateInit()
2176 or die "Cannot create a inflation stream\n" ;
2182 my ($output, $status) ;
2183 while (read(STDIN, $input, 4096))
2185 ($output, $status) = $x->inflate(\$input) ;
2188 if $status == Z_OK or $status == Z_STREAM_END ;
2190 last if $status != Z_OK ;
2193 die "inflation failed\n"
2194 unless $status == Z_STREAM_END ;
2196 =head1 ACCESSING ZIP FILES
2198 Although it is possible (with some effort on your part) to use this
2199 module to access .zip files, there is a module on CPAN that will do all
2200 the hard work for you. Check out the C<Archive::Zip> module on CPAN at
2202 http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz
2207 All the I<zlib> constants are automatically imported when you make use
2208 of I<Compress::Zlib>.
2213 L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, L<IO::Compress::RawDeflate>, L<IO::Uncompress::RawInflate>, L<IO::Uncompress::AnyInflate>
2215 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
2217 L<File::GlobMapper|File::GlobMapper>, L<Archive::Tar|Archive::Zip>,
2218 L<IO::Zlib|IO::Zlib>
2220 For RFC 1950, 1951 and 1952 see
2221 F<http://www.faqs.org/rfcs/rfc1950.html>,
2222 F<http://www.faqs.org/rfcs/rfc1951.html> and
2223 F<http://www.faqs.org/rfcs/rfc1952.html>
2225 The primary site for the gzip program is F<http://www.gzip.org>.
2229 The I<Compress::Zlib> module was written by Paul Marquess,
2230 F<pmqs@cpan.org>. The latest copy of the module can be
2231 found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
2233 The I<zlib> compression library was written by Jean-loup Gailly
2234 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
2236 The primary site for the I<zlib> compression library is
2237 F<http://www.zlib.org>.
2239 =head1 MODIFICATION HISTORY
2241 See the Changes file.
2243 =head1 COPYRIGHT AND LICENSE
2246 Copyright (c) 1995-2005 Paul Marquess. All rights reserved.
2247 This program is free software; you can redistribute it and/or
2248 modify it under the same terms as Perl itself.