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_06';
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,
185 or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError;
188 $gz = new IO::Uncompress::Gunzip($file,
191 AutoClose => 1, Strict => 0)
192 or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
198 bless [$gz, $infDef], 'Compress::Zlib::gzFile';
201 sub Compress::Zlib::gzFile::gzread
205 return _set_gzerr(Z_STREAM_ERROR())
206 if $self->[1] ne 'inflate';
208 return 0 if $self->gzeof();
210 my $gz = $self->[0] ;
211 my $status = $gz->read($_[0], defined $_[1] ? $_[1] : 4096) ;
212 $_[0] = "" if ! defined $_[0] ;
217 sub Compress::Zlib::gzFile::gzreadline
221 my $gz = $self->[0] ;
222 $_[0] = $gz->getline() ;
224 return defined $_[0] ? length $_[0] : 0 ;
227 sub Compress::Zlib::gzFile::gzwrite
230 my $gz = $self->[0] ;
232 return _set_gzerr(Z_STREAM_ERROR())
233 if $self->[1] ne 'deflate';
235 my $status = $gz->write($_[0]) ;
240 sub Compress::Zlib::gzFile::gztell
243 my $gz = $self->[0] ;
244 my $status = $gz->tell() ;
249 sub Compress::Zlib::gzFile::gzseek
255 my $gz = $self->[0] ;
257 eval { $status = $gz->seek($offset, $whence) ; };
261 $error =~ s/^.*: /gzseek: /;
262 $error =~ s/ at .* line \d+\s*$//;
269 sub Compress::Zlib::gzFile::gzflush
274 my $gz = $self->[0] ;
275 my $status = $gz->flush($f) ;
280 sub Compress::Zlib::gzFile::gzclose
283 my $gz = $self->[0] ;
285 my $status = $gz->close() ;
290 sub Compress::Zlib::gzFile::gzeof
293 my $gz = $self->[0] ;
296 if $self->[1] ne 'inflate';
298 my $status = $gz->eof() ;
303 sub Compress::Zlib::gzFile::gzsetparams
306 croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
309 my $gz = $self->[0] ;
311 my $strategy = shift;
313 return _set_gzerr(Z_STREAM_ERROR())
314 if $self->[1] ne 'deflate';
316 my $status = *$gz->{Deflate}->deflateParams(-Level => $level,
317 -Strategy => $strategy);
322 sub Compress::Zlib::gzFile::gzerror
325 my $gz = $self->[0] ;
327 return $Compress::Zlib::gzerrno ;
330 sub Compress::Zlib::Deflate::new
333 my ($got) = ParseParameters(0,
335 'AppendOutput' => [Parse_boolean, 0],
336 'CRC32' => [Parse_boolean, 0],
337 'ADLER32' => [Parse_boolean, 0],
338 'Bufsize' => [Parse_unsigned, 4096],
340 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
341 'Method' => [Parse_unsigned, Z_DEFLATED()],
342 'WindowBits' => [Parse_signed, MAX_WBITS()],
343 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
344 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
345 'Dictionary' => [Parse_any, ""],
349 croak "Compress::Zlib::Deflate::new: Bufsize must be >= 1, you specified " .
350 $got->value('Bufsize')
351 unless $got->value('Bufsize') >= 1;
354 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
355 $flags |= FLAG_CRC if $got->value('CRC32') ;
356 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
359 $got->value('Level'),
360 $got->value('Method'),
361 $got->value('WindowBits'),
362 $got->value('MemLevel'),
363 $got->value('Strategy'),
364 $got->value('Bufsize'),
365 $got->value('Dictionary')) ;
369 sub Compress::Zlib::Inflate::new
372 my ($got) = ParseParameters(0,
374 'AppendOutput' => [Parse_boolean, 0],
375 'CRC32' => [Parse_boolean, 0],
376 'ADLER32' => [Parse_boolean, 0],
377 'ConsumeInput' => [Parse_boolean, 1],
378 'Bufsize' => [Parse_unsigned, 4096],
380 'WindowBits' => [Parse_signed, MAX_WBITS()],
381 'Dictionary' => [Parse_any, ""],
385 croak "Compress::Zlib::Inflate::new: Bufsize must be >= 1, you specified " .
386 $got->value('Bufsize')
387 unless $got->value('Bufsize') >= 1;
390 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
391 $flags |= FLAG_CRC if $got->value('CRC32') ;
392 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
393 $flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
395 _inflateInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
396 $got->value('Dictionary')) ;
399 sub Compress::Zlib::InflateScan::new
402 my ($got) = ParseParameters(0,
404 'CRC32' => [Parse_boolean, 0],
405 'ADLER32' => [Parse_boolean, 0],
406 'Bufsize' => [Parse_unsigned, 4096],
408 'WindowBits' => [Parse_signed, -MAX_WBITS()],
409 'Dictionary' => [Parse_any, ""],
413 croak "Compress::Zlib::InflateScan::new: Bufsize must be >= 1, you specified " .
414 $got->value('Bufsize')
415 unless $got->value('Bufsize') >= 1;
418 #$flags |= FLAG_APPEND if $got->value('AppendOutput') ;
419 $flags |= FLAG_CRC if $got->value('CRC32') ;
420 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
421 #$flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
423 _inflateScanInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
427 sub Compress::Zlib::inflateScanStream::createDeflateStream
430 my ($got) = ParseParameters(0,
432 'AppendOutput' => [Parse_boolean, 0],
433 'CRC32' => [Parse_boolean, 0],
434 'ADLER32' => [Parse_boolean, 0],
435 'Bufsize' => [Parse_unsigned, 4096],
437 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
438 'Method' => [Parse_unsigned, Z_DEFLATED()],
439 'WindowBits' => [Parse_signed, - MAX_WBITS()],
440 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
441 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
444 croak "Compress::Zlib::InflateScan::createDeflateStream: Bufsize must be >= 1, you specified " .
445 $got->value('Bufsize')
446 unless $got->value('Bufsize') >= 1;
449 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
450 $flags |= FLAG_CRC if $got->value('CRC32') ;
451 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
453 $pkg->_createDeflateStream($flags,
454 $got->value('Level'),
455 $got->value('Method'),
456 $got->value('WindowBits'),
457 $got->value('MemLevel'),
458 $got->value('Strategy'),
459 $got->value('Bufsize'),
465 sub Compress::Zlib::deflateStream::deflateParams
468 my ($got) = ParseParameters(0, {
469 'Level' => [Parse_signed, undef],
470 'Strategy' => [Parse_unsigned, undef],
471 'Bufsize' => [Parse_unsigned, undef],
475 croak "Compress::Zlib::deflateParams needs Level and/or Strategy"
476 unless $got->parsed('Level') + $got->parsed('Strategy') +
477 $got->parsed('Bufsize');
479 croak "Compress::Zlib::Inflate::deflateParams: Bufsize must be >= 1, you specified " .
480 $got->value('Bufsize')
481 if $got->parsed('Bufsize') && $got->value('Bufsize') <= 1;
484 $flags |= 1 if $got->parsed('Level') ;
485 $flags |= 2 if $got->parsed('Strategy') ;
486 $flags |= 4 if $got->parsed('Bufsize') ;
488 $self->_deflateParams($flags, $got->value('Level'),
489 $got->value('Strategy'), $got->value('Bufsize'));
495 my ($x, $output, $err, $in) =('', '', '', '') ;
499 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
505 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
507 $x = new Compress::Zlib::Deflate -AppendOutput => 1, -Level => $level
510 $err = $x->deflate($in, $output) ;
511 return undef unless $err == Z_OK() ;
513 $err = $x->flush($output) ;
514 return undef unless $err == Z_OK() ;
522 my ($x, $output, $err, $in) =('', '', '', '') ;
526 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
532 $x = new Compress::Zlib::Inflate -ConsumeInput => 0 or return undef ;
534 $err = $x->inflate($in, $output) ;
535 return undef unless $err == Z_STREAM_END() ;
541 ### This stuff is for backward compat. with Compress::Zlib 1.x
546 my ($got) = ParseParameters(0,
548 'Bufsize' => [Parse_unsigned, 4096],
549 'Level' => [Parse_signed, Z_DEFAULT_COMPRESSION()],
550 'Method' => [Parse_unsigned, Z_DEFLATED()],
551 'WindowBits' => [Parse_signed, MAX_WBITS()],
552 'MemLevel' => [Parse_unsigned, MAX_MEM_LEVEL()],
553 'Strategy' => [Parse_unsigned, Z_DEFAULT_STRATEGY()],
554 'Dictionary' => [Parse_any, ""],
557 croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " .
558 $got->value('Bufsize')
559 unless $got->value('Bufsize') >= 1;
564 ($obj{def}, $status) =
566 $got->value('Level'),
567 $got->value('Method'),
568 $got->value('WindowBits'),
569 $got->value('MemLevel'),
570 $got->value('Strategy'),
571 $got->value('Bufsize'),
572 $got->value('Dictionary')) ;
574 my $x = ($status == Z_OK() ? bless \%obj, "Zlib::OldDeflate" : undef) ;
575 return wantarray ? ($x, $status) : $x ;
580 my ($got) = ParseParameters(0,
582 'Bufsize' => [Parse_unsigned, 4096],
583 'WindowBits' => [Parse_signed, MAX_WBITS()],
584 'Dictionary' => [Parse_any, ""],
588 croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " .
589 $got->value('Bufsize')
590 unless $got->value('Bufsize') >= 1;
594 ($obj{def}, $status) = _inflateInit(FLAG_CONSUME_INPUT,
595 $got->value('WindowBits'),
596 $got->value('Bufsize'),
597 $got->value('Dictionary')) ;
599 my $x = ($status == Z_OK() ? bless \%obj, "Zlib::OldInflate" : undef) ;
601 wantarray ? ($x, $status) : $x ;
604 package Zlib::OldDeflate ;
612 my $status = $self->{def}->deflate($_[0], $output) ;
614 wantarray ? ($output, $status) : $output ;
621 my $flag = shift || Compress::Zlib::Z_FINISH();
622 my $status = $self->{def}->flush($output, $flag) ;
624 wantarray ? ($output, $status) : $output ;
630 $self->{def}->deflateParams(@_) ;
636 $self->{def}->msg() ;
642 $self->{def}->total_in() ;
648 $self->{def}->total_out() ;
654 $self->{def}->dict_adler() ;
660 $self->{def}->get_Level() ;
666 $self->{def}->get_Strategy() ;
672 # $self->{def}->DispStream($_[0]) ;
675 package Zlib::OldInflate ;
681 my $status = $self->{def}->inflate($_[0], $output) ;
682 wantarray ? ($output, $status) : $output ;
688 $self->{def}->inflateSync($_[0]) ;
694 $self->{def}->msg() ;
700 $self->{def}->total_in() ;
706 $self->{def}->total_out() ;
712 $self->{def}->dict_adler() ;
718 # $self->{def}->DispStream($_[0]) ;
721 package Compress::Zlib ;
723 use Compress::Gzip::Constants;
727 my $x = new Compress::Zlib::Deflate(
731 -Level => Z_BEST_COMPRESSION(),
732 -WindowBits => - MAX_WBITS(),
736 # write a minimal gzip header
737 my $output = GZIP_MINIMUM_HEADER ;
739 # if the deflation buffer isn't a reference, make it one
740 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
742 my $status = $x->deflate($string, \$output) ;
746 $status = $x->flush(\$output) ;
750 return $output . pack("V V", $x->crc32(), $x->total_in()) ;
755 sub _removeGzipHeader($)
759 return Z_DATA_ERROR()
760 if length($$string) < GZIP_MIN_HEADER_SIZE ;
762 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
763 unpack ('CCCCVCC', $$string);
765 return Z_DATA_ERROR()
766 unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
767 $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
768 substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
771 if ($flags & GZIP_FLG_FEXTRA)
773 return Z_DATA_ERROR()
774 if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
776 my ($extra_len) = unpack ('v', $$string);
777 $extra_len += GZIP_FEXTRA_HEADER_SIZE;
778 return Z_DATA_ERROR()
779 if length($$string) < $extra_len ;
781 substr($$string, 0, $extra_len) = '';
785 if ($flags & GZIP_FLG_FNAME)
787 my $name_end = index ($$string, GZIP_NULL_BYTE);
788 return Z_DATA_ERROR()
790 substr($$string, 0, $name_end + 1) = '';
794 if ($flags & GZIP_FLG_FCOMMENT)
796 my $comment_end = index ($$string, GZIP_NULL_BYTE);
797 return Z_DATA_ERROR()
798 if $comment_end == -1 ;
799 substr($$string, 0, $comment_end + 1) = '';
803 if ($flags & GZIP_FLG_FHCRC)
805 return Z_DATA_ERROR()
806 if length ($$string) < GZIP_FHCRC_SIZE ;
807 substr($$string, 0, GZIP_FHCRC_SIZE) = '';
816 # if the buffer isn't a reference, make it one
817 my $string = (ref $_[0] ? $_[0] : \$_[0]);
819 _removeGzipHeader($string) == Z_OK()
822 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
823 my $x = new Compress::Zlib::Inflate({-WindowBits => - MAX_WBITS(),
824 -Bufsize => $bufsize})
829 my $status = $x->inflate($string, $output);
831 unless $status == Z_STREAM_END();
833 if (length $$string >= 8)
835 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
836 substr($$string, 0, 8) = '';
838 unless $len == length($output) and
839 $crc == crc32($output);
848 # Autoload methods go after __END__, and are processed by the autosplit program.
856 Compress::Zlib - Interface to zlib compression library
860 use Compress::Zlib 2 ;
862 ($d, $status) = new Compress::Zlib::Deflate( [OPT] ) ;
863 $status = $d->deflate($input, $output) ;
864 $status = $d->flush($output [, $flush_type]) ;
865 $d->deflateParams(OPTS) ;
866 $d->deflateTune(OPTS) ;
877 ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) ;
878 $status = $i->inflate($input, $output) ;
879 $status = $i->inflateSync($input) ;
888 $dest = compress($source) ;
889 $dest = uncompress($source) ;
891 $gz = gzopen($filename or filehandle, $mode) ;
892 $bytesread = $gz->gzread($buffer [,$size]) ;
893 $bytesread = $gz->gzreadline($line) ;
894 $byteswritten = $gz->gzwrite($buffer) ;
895 $status = $gz->gzflush($flush) ;
896 $offset = $gz->gztell() ;
897 $status = $gz->gzseek($offset, $whence) ;
898 $status = $gz->gzclose() ;
899 $status = $gz->gzeof() ;
900 $status = $gz->gzsetparams($level, $strategy) ;
901 $errstring = $gz->gzerror() ;
904 $dest = Compress::Zlib::memGzip($buffer) ;
905 $dest = Compress::Zlib::memGunzip($buffer) ;
907 $crc = adler32($buffer [,$crc]) ;
908 $crc = crc32($buffer [,$crc]) ;
910 $crc = adler32_combine($crc1, $crc2, $len2)l
911 $crc = crc32_combine($adler1, $adler2, $len2)
916 # Compress::Zlib 1.x legacy interface
918 ($d, $status) = deflateInit( [OPT] ) ;
919 ($out, $status) = $d->deflate($buffer) ;
920 $status = $d->deflateParams([OPT]) ;
921 ($out, $status) = $d->flush() ;
927 ($i, $status) = inflateInit( [OPT] ) ;
928 ($out, $status) = $i->inflate($buffer) ;
929 $status = $i->inflateSync($buffer) ;
938 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
939 compression library (see L</AUTHOR> for details about where to get
941 The I<zlib> library allows reading and writing of
942 compressed data streams that conform to RFC1950, RFC1951 and RFC1952
944 Most of the I<zlib> functionality is available in I<Compress::Zlib>.
946 Unless you are working with legacy code, or you need to work directly
947 with the low-level zlib interface, it is recommended that applications
948 use one of the newer C<IO::*> interfaces provided with this module.
950 The C<Compress::Zlib> module can be split into two general areas of
951 functionality, namely a low-level in-memory compression/decompression
952 interface and a simple read/write interface to I<gzip> files.
954 Each of these areas will be discussed separately below.
957 =head1 GZIP INTERFACE
959 A number of functions are supplied in I<zlib> for reading and writing
960 I<gzip> files that conform to RFC1952. This module provides an interface
963 If you are upgrading from C<Compress::Zlib> 1.x, the following enhancements
964 have been made to the C<gzopen> interface:
970 If you want to to open either STDIN or STDOUT with C<gzopen>, you can
971 optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
976 In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open the
977 underlying file. This made things especially tricky when a Perl filehandle was
978 passed to C<gzopen>. Behind the scenes the numeric C file descriptor had to be
979 extracted from the Perl filehandle and this passed to the zlib library.
981 Apart from being non-portable to some operating systems, this made it difficult
982 to use C<gzopen> in situations where you wanted to extract/create a gzip data
983 stream that is embedded in a larger file, without having to resort to opening
984 and closing the file multiple times.
986 In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been completely
987 rewritten to use the L<IO::Compress::Gzip|IO::Compress::Gzip> for writing gzip files and
988 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for reading gzip files.
992 Addition of C<gzseek> to provide a restricted C<seek> interface.
1000 A more complete and flexible interface for reading/writing gzip files/buffers
1001 is included with this module. See L<IO::Compress::Gzip|IO::Compress::Gzip> and
1002 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for more details.
1006 =item B<$gz = gzopen($filename, $mode)>
1008 =item B<$gz = gzopen($filehandle, $mode)>
1010 This function opens either the I<gzip> file C<$filename> for reading or writing
1011 or attaches to the opened filehandle, C<$filehandle>. It returns an object on
1012 success and C<undef> on failure.
1014 When writing a gzip file this interface will always create the smallest
1015 possible gzip header (exactly 10 bytes). If you want control over the
1016 information stored in the gzip header (like the original filename or a comment)
1017 use L<IO::Compress::Gzip|IO::Compress::Gzip> instead.
1019 The second parameter, C<$mode>, is used to specify whether the file is
1020 opened for reading or writing and to optionally specify a compression
1021 level and compression strategy when writing. The format of the C<$mode>
1022 parameter is similar to the mode parameter to the 'C' function C<fopen>,
1023 so "rb" is used to open for reading and "wb" for writing.
1025 To specify a compression level when writing, append a digit between 0
1026 and 9 to the mode string -- 0 means no compression and 9 means maximum
1028 If no compression level is specified Z_DEFAULT_COMPRESSION is used.
1030 To specify the compression strategy when writing, append 'f' for filtered
1031 data, 'h' for Huffman only compression, or 'R' for run-length encoding.
1032 If no strategy is specified Z_DEFAULT_STRATEGY is used.
1034 So, for example, "wb9" means open for writing with the maximum compression
1035 using the default strategy and "wb4R" means open for writing with compression
1036 level 4 and run-length encoding.
1038 Refer to the I<zlib> documentation for the exact format of the C<$mode>
1042 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
1044 Reads C<$size> bytes from the compressed file into C<$buffer>. If
1045 C<$size> is not specified, it will default to 4096. If the scalar
1046 C<$buffer> is not large enough, it will be extended automatically.
1048 Returns the number of bytes actually read. On EOF it returns 0 and in
1049 the case of an error, -1.
1051 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
1053 Reads the next line from the compressed file into C<$line>.
1055 Returns the number of bytes actually read. On EOF it returns 0 and in
1056 the case of an error, -1.
1058 It is legal to intermix calls to C<gzread> and C<gzreadline>.
1060 In addition, C<gzreadline> fully supports the use of of the variable C<$/>
1061 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
1062 determine what constitutes an end of line. Both paragraph mode and file
1063 slurp mode are supported.
1066 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
1068 Writes the contents of C<$buffer> to the compressed file. Returns the
1069 number of bytes actually written, or 0 on error.
1071 =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
1073 Flushes all pending output into the compressed file.
1075 This method takes an optional parameter, C<$flush_type>, that controls
1076 how the flushing will be carried out. By default the C<$flush_type>
1077 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1078 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1079 strongly recommended that you only set the C<flush_type> parameter if
1080 you fully understand the implications of what it does - overuse of C<flush>
1081 can seriously degrade the level of compression achieved. See the C<zlib>
1082 documentation for details.
1084 Returns 1 on success, 0 on failure.
1087 =item B<$offset = $gz-E<gt>gztell() ;>
1089 Returns the uncompressed file offset.
1091 =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
1093 Sets the file position of the
1095 Provides a sub-set of the C<seek> functionality, with the restriction
1096 that it is only legal to seek forward in the compressed file.
1097 It is a fatal error to attempt to seek backward.
1099 When opened for writing, empty parts of the file will have NULL (0x00)
1100 bytes written to them.
1102 The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
1104 Returns 1 on success, 0 on failure.
1106 =item B<$gz-E<gt>gzclose>
1108 Closes the compressed file. Any pending data is flushed to the file
1109 before it is closed.
1111 Returns 1 on success, 0 on failure.
1113 =item B<$gz-E<gt>gzsetparams($level, $strategy>
1115 Change settings for the deflate stream C<$gz>.
1117 The list of the valid options is shown below. Options not specified
1118 will remain unchanged.
1120 Note: This method is only available if you are running zlib 1.0.6 or better.
1126 Defines the compression level. Valid values are 0 through 9,
1127 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1128 C<Z_DEFAULT_COMPRESSION>.
1132 Defines the strategy used to tune the compression. The valid values are
1133 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1137 =item B<$gz-E<gt>gzerror>
1139 Returns the I<zlib> error message or number for the last operation
1140 associated with C<$gz>. The return value will be the I<zlib> error
1141 number when used in a numeric context and the I<zlib> error message
1142 when used in a string context. The I<zlib> error number constants,
1143 shown below, are available for use.
1155 The C<$gzerrno> scalar holds the error code associated with the most
1156 recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
1157 I<not> associated with a particular file.
1159 As with C<gzerror()> it returns an error number in numeric context and
1160 an error message in string context. Unlike C<gzerror()> though, the
1161 error message will correspond to the I<zlib> message when the error is
1162 associated with I<zlib> itself, or the UNIX error message when it is
1163 not (i.e. I<zlib> returned C<Z_ERRORNO>).
1165 As there is an overlap between the error numbers used by I<zlib> and
1166 UNIX, C<$gzerrno> should only be used to check for the presence of
1167 I<an> error in numeric context. Use C<gzerror()> to check for specific
1168 I<zlib> errors. The I<gzcat> example below shows how the variable can
1176 Here is an example script which uses the interface. It implements a
1182 use Compress::Zlib ;
1184 # use stdin if no files supplied
1185 @ARGV = '-' unless @ARGV ;
1187 foreach my $file (@ARGV) {
1190 my $gz = gzopen($file, "rb")
1191 or die "Cannot open $file: $gzerrno\n" ;
1193 print $buffer while $gz->gzread($buffer) > 0 ;
1195 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
1196 if $gzerrno != Z_STREAM_END ;
1201 Below is a script which makes use of C<gzreadline>. It implements a
1202 very simple I<grep> like script.
1207 use Compress::Zlib ;
1209 die "Usage: gzgrep pattern [file...]\n"
1212 my $pattern = shift ;
1214 # use stdin if no files supplied
1215 @ARGV = '-' unless @ARGV ;
1217 foreach my $file (@ARGV) {
1218 my $gz = gzopen($file, "rb")
1219 or die "Cannot open $file: $gzerrno\n" ;
1221 while ($gz->gzreadline($_) > 0) {
1222 print if /$pattern/ ;
1225 die "Error reading from $file: $gzerrno\n"
1226 if $gzerrno != Z_STREAM_END ;
1231 This script, I<gzstream>, does the opposite of the I<gzcat> script
1232 above. It reads from standard input and writes a gzip data stream to
1238 use Compress::Zlib ;
1240 binmode STDOUT; # gzopen only sets it on the fd
1242 my $gz = gzopen(\*STDOUT, "wb")
1243 or die "Cannot open stdout: $gzerrno\n" ;
1247 or die "error writing: $gzerrno\n" ;
1252 =head2 Compress::Zlib::memGzip
1254 This function is used to create an in-memory gzip file with the minimum
1255 possible gzip header (exactly 10 bytes).
1257 $dest = Compress::Zlib::memGzip($buffer) ;
1259 If successful, it returns the in-memory gzip file, otherwise it returns
1262 The C<$buffer> parameter can either be a scalar or a scalar reference.
1264 See L<IO::Compress::Gzip|IO::Compress::Gzip> for an alternative way to carry out in-memory gzip
1267 =head2 Compress::Zlib::memGunzip
1269 This function is used to uncompress an in-memory gzip file.
1271 $dest = Compress::Zlib::memGunzip($buffer) ;
1273 If successful, it returns the uncompressed gzip file, otherwise it
1276 The C<$buffer> parameter can either be a scalar or a scalar reference. The
1277 contents of the C<$buffer> parameter are destroyed after calling this function.
1279 See L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for an alternative way to carry out in-memory gzip
1282 =head1 COMPRESS/UNCOMPRESS
1284 Two functions are provided to perform in-memory compression/uncompression of
1285 RFC 1950 data streams. They are called C<compress> and C<uncompress>.
1289 =item B<$dest = compress($source [, $level] ) ;>
1291 Compresses C<$source>. If successful it returns the compressed
1292 data. Otherwise it returns I<undef>.
1294 The source buffer, C<$source>, can either be a scalar or a scalar
1297 The C<$level> parameter defines the compression level. Valid values are
1298 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
1299 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
1300 If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
1303 =item B<$dest = uncompress($source) ;>
1305 Uncompresses C<$source>. If successful it returns the uncompressed
1306 data. Otherwise it returns I<undef>.
1308 The source buffer can either be a scalar or a scalar reference.
1312 Please note: the two functions defined above are I<not> compatible with
1313 the Unix commands of the same name.
1315 See L<IO::Compress::Deflate|IO::Compress::Deflate> and L<IO::Uncompress::Inflate|IO::Uncompress::Inflate> included with
1316 this distribution for an alternative interface for reading/writing RFC 1950
1319 =head1 CHECKSUM FUNCTIONS
1321 Two functions are provided by I<zlib> to calculate checksums. For the
1322 Perl interface, the order of the two parameters in both functions has
1323 been reversed. This allows both running checksums and one off
1324 calculations to be done.
1326 $crc = adler32($buffer [,$crc]) ;
1327 $crc = crc32($buffer [,$crc]) ;
1329 The buffer parameters can either be a scalar or a scalar reference.
1331 If the $crc parameters is C<undef>, the crc value will be reset.
1333 If you have built this module with zlib 1.2.3 or better, two more
1334 CRC-related functions are available.
1336 $crc = adler32_combine($crc1, $crc2, $len2)l
1337 $crc = crc32_combine($adler1, $adler2, $len2)
1339 These functions allow checksums to be merged.
1341 =head1 Compress::Zlib::Deflate
1343 This section defines an interface that allows in-memory compression using
1344 the I<deflate> interface provided by zlib.
1346 Note: The interface defined in this section is different from version
1347 1.x of this module. The original deflate interface is still available
1348 for backward compatibility and is documented in the section
1349 L<Compress::Zlib 1.x Deflate Interface>.
1351 Here is a definition of the interface available:
1354 =head2 B<($d, $status) = new Compress::Zlib::Deflate( [OPT] ) >
1356 Initialises a deflation object.
1358 If you are familiar with the I<zlib> library, it combines the
1359 features of the I<zlib> functions C<deflateInit>, C<deflateInit2>
1360 and C<deflateSetDictionary>.
1362 If successful, it will return the initialised deflation object, C<$d>
1363 and a C<$status> of C<Z_OK> in a list context. In scalar context it
1364 returns the deflation object, C<$d>, only.
1366 If not successful, the returned deflation object, C<$d>, will be
1367 I<undef> and C<$status> will hold the a I<zlib> error code.
1369 The function optionally takes a number of named options specified as
1370 C<-Name =E<gt> value> pairs. This allows individual options to be
1371 tailored without having to specify them all in the parameter list.
1373 For backward compatibility, it is also possible to pass the parameters
1374 as a reference to a hash containing the name=>value pairs.
1376 Below is a list of the valid options:
1382 Defines the compression level. Valid values are 0 through 9,
1383 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1384 C<Z_DEFAULT_COMPRESSION>.
1386 The default is C<-Level =E<gt> Z_DEFAULT_COMPRESSION>.
1390 Defines the compression method. The only valid value at present (and
1391 the default) is C<-Method =E<gt> Z_DEFLATED>.
1393 =item B<-WindowBits>
1395 For a definition of the meaning and valid values for C<WindowBits>
1396 refer to the I<zlib> documentation for I<deflateInit2>.
1398 Defaults to C<-WindowBits =E<gt> MAX_WBITS>.
1402 For a definition of the meaning and valid values for C<MemLevel>
1403 refer to the I<zlib> documentation for I<deflateInit2>.
1405 Defaults to C<-MemLevel =E<gt> MAX_MEM_LEVEL>.
1409 Defines the strategy used to tune the compression. The valid values are
1410 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED>, C<Z_RLE>, C<Z_FIXED> and
1413 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1415 =item B<-Dictionary>
1417 When a dictionary is specified I<Compress::Zlib> will automatically
1418 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1419 Adler32 value for the dictionary can be obtained by calling the method
1420 C<$d-E<gt>dict_adler()>.
1422 The default is no dictionary.
1426 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1427 and C<$d-E<gt>flush> methods. If the buffer has to be
1428 reallocated to increase the size, it will grow in increments of
1431 The default buffer size is 4096.
1433 =item B<-AppendOutput>
1435 This option controls how data is written to the output buffer by the
1436 C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1438 If the C<AppendOutput> option is set to false, the output buffers in the
1439 C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods will be truncated before
1440 uncompressed data is written to them.
1442 If the option is set to true, uncompressed data will be appended to the
1443 output buffer in the C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1445 This option defaults to false.
1449 If set to true, a crc32 checksum of the uncompressed data will be
1450 calculated. Use the C<$d-E<gt>crc32> method to retrieve this value.
1452 This option defaults to false.
1457 If set to true, an adler32 checksum of the uncompressed data will be
1458 calculated. Use the C<$d-E<gt>adler32> method to retrieve this value.
1460 This option defaults to false.
1465 Here is an example of using the C<Compress::Zlib::Deflate> optional
1466 parameter list to override the default buffer size and compression
1467 level. All other options will take their default values.
1469 my $d = new Compress::Zlib::Deflate ( -Bufsize => 300,
1470 -Level => Z_BEST_SPEED ) ;
1473 =head2 B<$status = $d-E<gt>deflate($input, $output)>
1475 Deflates the contents of C<$input> and writes the compressed data to
1478 The C<$input> and C<$output> parameters can be either scalars or scalar
1481 When finished, C<$input> will be completely processed (assuming there
1482 were no errors). If the deflation was successful it writes the deflated
1483 data to C<$output> and returns a status value of C<Z_OK>.
1485 On error, it returns a I<zlib> error code.
1487 If the C<AppendOutput> option is set to true in the constructor for
1488 the C<$d> object, the compressed data will be appended to C<$output>. If
1489 it is false, C<$output> will be truncated before any compressed data is
1492 B<Note>: This method will not necessarily write compressed data to
1493 C<$output> every time it is called. So do not assume that there has been
1494 an error if the contents of C<$output> is empty on returning from
1495 this method. As long as the return code from the method is C<Z_OK>,
1496 the deflate has succeeded.
1498 =head2 B<$status = $d-E<gt>flush($output [, $flush_type]) >
1500 Typically used to finish the deflation. Any pending output will be
1501 written to C<$output>.
1503 Returns C<Z_OK> if successful.
1505 Note that flushing can seriously degrade the compression ratio, so it
1506 should only be used to terminate a decompression (using C<Z_FINISH>) or
1507 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1509 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1510 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1511 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1512 C<flush_type> parameter if you fully understand the implications of
1513 what it does. See the C<zlib> documentation for details.
1515 If the C<AppendOutput> option is set to true in the constructor for
1516 the C<$d> object, the compressed data will be appended to C<$output>. If
1517 it is false, C<$output> will be truncated before any compressed data is
1520 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1522 Change settings for the deflate object C<$d>.
1524 The list of the valid options is shown below. Options not specified
1525 will remain unchanged.
1532 Defines the compression level. Valid values are 0 through 9,
1533 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1534 C<Z_DEFAULT_COMPRESSION>.
1538 Defines the strategy used to tune the compression. The valid values are
1539 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1543 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1544 and C<$d-E<gt>flush> methods. If the buffer has to be
1545 reallocated to increase the size, it will grow in increments of
1551 =head2 B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)>
1553 Tune the internal settings for the deflate object C<$d>. This option is
1554 only available if you are running zlib 1.2.2.3 or better.
1556 Refer to the documentation in zlib.h for instructions on how to fly
1559 =head2 B<$d-E<gt>dict_adler()>
1561 Returns the adler32 value for the dictionary.
1563 =head2 B<$d-E<gt>crc32()>
1565 Returns the crc32 value for the uncompressed data to date.
1567 If the C<CRC32> option is not enabled in the constructor for this object,
1568 this method will always return 0;
1570 =head2 B<$d-E<gt>adler32()>
1572 Returns the adler32 value for the uncompressed data to date.
1574 =head2 B<$d-E<gt>msg()>
1576 Returns the last error message generated by zlib.
1578 =head2 B<$d-E<gt>total_in()>
1580 Returns the total number of bytes uncompressed bytes input to deflate.
1582 =head2 B<$d-E<gt>total_out()>
1584 Returns the total number of compressed bytes output from deflate.
1586 =head2 B<$d-E<gt>get_Strategy()>
1588 Returns the deflation strategy currently used. Valid values are
1589 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1592 =head2 B<$d-E<gt>get_Level()>
1594 Returns the compression level being used.
1596 =head2 B<$d-E<gt>get_BufSize()>
1598 Returns the buffer size used to carry out the compression.
1603 Here is a trivial example of using C<deflate>. It simply reads standard
1604 input, deflates it and writes it to standard output.
1609 use Compress::Zlib 2 ;
1613 my $x = new Compress::Zlib::Deflate
1614 or die "Cannot create a deflation stream\n" ;
1616 my ($output, $status) ;
1619 $status = $x->deflate($_, $output) ;
1622 or die "deflation failed\n" ;
1627 $status = $x->flush($output) ;
1630 or die "deflation failed\n" ;
1634 =head1 Compress::Zlib::Inflate
1636 This section defines an interface that allows in-memory uncompression using
1637 the I<inflate> interface provided by zlib.
1639 Note: The interface defined in this section is different from version
1640 1.x of this module. The original inflate interface is still available
1641 for backward compatibility and is documented in the section
1642 L<Compress::Zlib 1.x Inflate Interface>.
1644 Here is a definition of the interface:
1647 =head2 B< ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) >
1649 Initialises an inflation object.
1651 In a list context it returns the inflation object, C<$i>, and the
1652 I<zlib> status code (C<$status>). In a scalar context it returns the
1653 inflation object only.
1655 If successful, C<$i> will hold the inflation object and C<$status> will
1658 If not successful, C<$i> will be I<undef> and C<$status> will hold the
1661 The function optionally takes a number of named options specified as
1662 C<-Name =E<gt> value> pairs. This allows individual options to be
1663 tailored without having to specify them all in the parameter list.
1665 For backward compatibility, it is also possible to pass the parameters
1666 as a reference to a hash containing the name=E<gt>value pairs.
1668 Here is a list of the valid options:
1672 =item B<-WindowBits>
1674 For a definition of the meaning and valid values for C<WindowBits>
1675 refer to the I<zlib> documentation for I<inflateInit2>.
1677 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1681 Sets the initial size for the output buffer used by the C<$i-E<gt>inflate>
1682 method. If the output buffer in this method has to be reallocated to
1683 increase the size, it will grow in increments of C<Bufsize>.
1687 =item B<-Dictionary>
1689 The default is no dictionary.
1691 =item B<-AppendOutput>
1693 This option controls how data is written to the output buffer by the
1694 C<$i-E<gt>inflate> method.
1696 If the option is set to false, the output buffer in the C<$i-E<gt>inflate>
1697 method will be truncated before uncompressed data is written to it.
1699 If the option is set to true, uncompressed data will be appended to the
1700 output buffer by the C<$i-E<gt>inflate> method.
1702 This option defaults to false.
1707 If set to true, a crc32 checksum of the uncompressed data will be
1708 calculated. Use the C<$i-E<gt>crc32> method to retrieve this value.
1710 This option defaults to false.
1714 If set to true, an adler32 checksum of the uncompressed data will be
1715 calculated. Use the C<$i-E<gt>adler32> method to retrieve this value.
1717 This option defaults to false.
1719 =item B<-ConsumeInput>
1721 If set to true, this option will remove compressed data from the input
1722 buffer of the the C< $i-E<gt>inflate > method as the inflate progresses.
1724 This option can be useful when you are processing compressed data that is
1725 embedded in another file/buffer. In this case the data that immediately
1726 follows the compressed stream will be left in the input buffer.
1728 This option defaults to true.
1732 Here is an example of using an optional parameter to override the default
1735 my ($i, $status) = new Compress::Zlib::Inflate( -Bufsize => 300 ) ;
1737 =head2 B< $status = $i-E<gt>inflate($input, $output) >
1739 Inflates the complete contents of C<$input> and writes the uncompressed
1740 data to C<$output>. The C<$input> and C<$output> parameters can either be
1741 scalars or scalar references.
1743 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1744 compressed data has been successfully reached.
1746 If not successful C<$status> will hold the I<zlib> error code.
1748 If the C<ConsumeInput> option has been set to true when the
1749 C<Compress::Zlib::Inflate> object is created, the C<$input> parameter
1750 is modified by C<inflate>. On completion it will contain what remains
1751 of the input buffer after inflation. In practice, this means that when
1752 the return status is C<Z_OK> the C<$input> parameter will contain an
1753 empty string, and when the return status is C<Z_STREAM_END> the C<$input>
1754 parameter will contains what (if anything) was stored in the input buffer
1755 after the deflated data stream.
1757 This feature is useful when processing a file format that encapsulates
1758 a compressed data stream (e.g. gzip, zip) and there is useful data
1759 immediately after the deflation stream.
1761 If the C<AppendOutput> option is set to true in the constructor for
1762 this object, the uncompressed data will be appended to C<$output>. If
1763 it is false, C<$output> will be truncated before any uncompressed data
1766 =head2 B<$status = $i-E<gt>inflateSync($input)>
1768 This method can be used to attempt to recover good data from a compressed
1769 data stream that is partially corrupt.
1770 It scans C<$input> until it reaches either a I<full flush point> or the
1773 If a I<full flush point> is found, C<Z_OK> is returned and C<$input>
1774 will be have all data up to the flush point removed. This data can then be
1775 passed to the C<$i-E<gt>inflate> method to be uncompressed.
1777 Any other return code means that a flush point was not found. If more
1778 data is available, C<inflateSync> can be called repeatedly with more
1779 compressed data until the flush point is found.
1781 Note I<full flush points> are not present by default in compressed
1782 data streams. They must have been added explicitly when the data stream
1783 was created by calling C<Compress::Deflate::flush> with C<Z_FULL_FLUSH>.
1786 =head2 B<$i-E<gt>dict_adler()>
1788 Returns the adler32 value for the dictionary.
1790 =head2 B<$i-E<gt>crc32()>
1792 Returns the crc32 value for the uncompressed data to date.
1794 If the C<CRC32> option is not enabled in the constructor for this object,
1795 this method will always return 0;
1797 =head2 B<$i-E<gt>adler32()>
1799 Returns the adler32 value for the uncompressed data to date.
1801 If the C<ADLER32> option is not enabled in the constructor for this object,
1802 this method will always return 0;
1804 =head2 B<$i-E<gt>msg()>
1806 Returns the last error message generated by zlib.
1808 =head2 B<$i-E<gt>total_in()>
1810 Returns the total number of bytes compressed bytes input to inflate.
1812 =head2 B<$i-E<gt>total_out()>
1814 Returns the total number of uncompressed bytes output from inflate.
1816 =head2 B<$d-E<gt>get_BufSize()>
1818 Returns the buffer size used to carry out the decompression.
1822 Here is an example of using C<inflate>.
1827 use Compress::Zlib 2 ;
1829 my $x = new Compress::Zlib::Inflate()
1830 or die "Cannot create a inflation stream\n" ;
1836 my ($output, $status) ;
1837 while (read(STDIN, $input, 4096))
1839 $status = $x->inflate(\$input, $output) ;
1842 if $status == Z_OK or $status == Z_STREAM_END ;
1844 last if $status != Z_OK ;
1847 die "inflation failed\n"
1848 unless $status == Z_STREAM_END ;
1850 =head1 Compress::Zlib 1.x Deflate Interface
1852 This section defines the interface available in C<Compress::Zlib> version
1853 1.x that allows in-memory compression using the I<deflate> interface
1856 Here is a definition of the interface available:
1859 =head2 B<($d, $status) = deflateInit( [OPT] )>
1861 Initialises a deflation stream.
1863 It combines the features of the I<zlib> functions C<deflateInit>,
1864 C<deflateInit2> and C<deflateSetDictionary>.
1866 If successful, it will return the initialised deflation stream, C<$d>
1867 and C<$status> of C<Z_OK> in a list context. In scalar context it
1868 returns the deflation stream, C<$d>, only.
1870 If not successful, the returned deflation stream (C<$d>) will be
1871 I<undef> and C<$status> will hold the exact I<zlib> error code.
1873 The function optionally takes a number of named options specified as
1874 C<-Name=E<gt>value> pairs. This allows individual options to be
1875 tailored without having to specify them all in the parameter list.
1877 For backward compatibility, it is also possible to pass the parameters
1878 as a reference to a hash containing the name=>value pairs.
1880 The function takes one optional parameter, a reference to a hash. The
1881 contents of the hash allow the deflation interface to be tailored.
1883 Here is a list of the valid options:
1889 Defines the compression level. Valid values are 0 through 9,
1890 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1891 C<Z_DEFAULT_COMPRESSION>.
1893 The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
1897 Defines the compression method. The only valid value at present (and
1898 the default) is C<-Method =E<gt>Z_DEFLATED>.
1900 =item B<-WindowBits>
1902 For a definition of the meaning and valid values for C<WindowBits>
1903 refer to the I<zlib> documentation for I<deflateInit2>.
1905 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1909 For a definition of the meaning and valid values for C<MemLevel>
1910 refer to the I<zlib> documentation for I<deflateInit2>.
1912 Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
1916 Defines the strategy used to tune the compression. The valid values are
1917 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1919 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1921 =item B<-Dictionary>
1923 When a dictionary is specified I<Compress::Zlib> will automatically
1924 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1925 Adler32 value for the dictionary can be obtained by calling the method
1926 C<$d->dict_adler()>.
1928 The default is no dictionary.
1932 Sets the initial size for the deflation buffer. If the buffer has to be
1933 reallocated to increase the size, it will grow in increments of
1936 The default is 4096.
1940 Here is an example of using the C<deflateInit> optional parameter list
1941 to override the default buffer size and compression level. All other
1942 options will take their default values.
1944 deflateInit( -Bufsize => 300,
1945 -Level => Z_BEST_SPEED ) ;
1948 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1951 Deflates the contents of C<$buffer>. The buffer can either be a scalar
1952 or a scalar reference. When finished, C<$buffer> will be
1953 completely processed (assuming there were no errors). If the deflation
1954 was successful it returns the deflated output, C<$out>, and a status
1955 value, C<$status>, of C<Z_OK>.
1957 On error, C<$out> will be I<undef> and C<$status> will contain the
1960 In a scalar context C<deflate> will return C<$out> only.
1962 As with the I<deflate> function in I<zlib>, it is not necessarily the
1963 case that any output will be produced by this method. So don't rely on
1964 the fact that C<$out> is empty for an error test.
1967 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
1969 Typically used to finish the deflation. Any pending output will be
1970 returned via C<$out>.
1971 C<$status> will have a value C<Z_OK> if successful.
1973 In a scalar context C<flush> will return C<$out> only.
1975 Note that flushing can seriously degrade the compression ratio, so it
1976 should only be used to terminate a decompression (using C<Z_FINISH>) or
1977 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1979 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1980 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1981 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1982 C<flush_type> parameter if you fully understand the implications of
1983 what it does. See the C<zlib> documentation for details.
1985 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1987 Change settings for the deflate stream C<$d>.
1989 The list of the valid options is shown below. Options not specified
1990 will remain unchanged.
1996 Defines the compression level. Valid values are 0 through 9,
1997 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1998 C<Z_DEFAULT_COMPRESSION>.
2002 Defines the strategy used to tune the compression. The valid values are
2003 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
2007 =head2 B<$d-E<gt>dict_adler()>
2009 Returns the adler32 value for the dictionary.
2011 =head2 B<$d-E<gt>msg()>
2013 Returns the last error message generated by zlib.
2015 =head2 B<$d-E<gt>total_in()>
2017 Returns the total number of bytes uncompressed bytes input to deflate.
2019 =head2 B<$d-E<gt>total_out()>
2021 Returns the total number of compressed bytes output from deflate.
2026 Here is a trivial example of using C<deflate>. It simply reads standard
2027 input, deflates it and writes it to standard output.
2032 use Compress::Zlib ;
2036 my $x = deflateInit()
2037 or die "Cannot create a deflation stream\n" ;
2039 my ($output, $status) ;
2042 ($output, $status) = $x->deflate($_) ;
2045 or die "deflation failed\n" ;
2050 ($output, $status) = $x->flush() ;
2053 or die "deflation failed\n" ;
2057 =head1 Compress::Zlib 1.x Inflate Interface
2059 This section defines the interface available in C<Compress::Zlib> version
2060 1.x that allows in-memory uncompression using the I<deflate> interface
2063 Here is a definition of the interface:
2066 =head2 B<($i, $status) = inflateInit()>
2068 Initialises an inflation stream.
2070 In a list context it returns the inflation stream, C<$i>, and the
2071 I<zlib> status code (C<$status>). In a scalar context it returns the
2072 inflation stream only.
2074 If successful, C<$i> will hold the inflation stream and C<$status> will
2077 If not successful, C<$i> will be I<undef> and C<$status> will hold the
2080 The function optionally takes a number of named options specified as
2081 C<-Name=E<gt>value> pairs. This allows individual options to be
2082 tailored without having to specify them all in the parameter list.
2084 For backward compatibility, it is also possible to pass the parameters
2085 as a reference to a hash containing the name=>value pairs.
2087 The function takes one optional parameter, a reference to a hash. The
2088 contents of the hash allow the deflation interface to be tailored.
2090 Here is a list of the valid options:
2094 =item B<-WindowBits>
2096 For a definition of the meaning and valid values for C<WindowBits>
2097 refer to the I<zlib> documentation for I<inflateInit2>.
2099 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
2103 Sets the initial size for the inflation buffer. If the buffer has to be
2104 reallocated to increase the size, it will grow in increments of
2109 =item B<-Dictionary>
2111 The default is no dictionary.
2115 Here is an example of using the C<inflateInit> optional parameter to
2116 override the default buffer size.
2118 inflateInit( -Bufsize => 300 ) ;
2120 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
2122 Inflates the complete contents of C<$buffer>. The buffer can either be
2123 a scalar or a scalar reference.
2125 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
2126 compressed data has been successfully reached.
2127 If not successful, C<$out> will be I<undef> and C<$status> will hold
2128 the I<zlib> error code.
2130 The C<$buffer> parameter is modified by C<inflate>. On completion it
2131 will contain what remains of the input buffer after inflation. This
2132 means that C<$buffer> will be an empty string when the return status is
2133 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
2134 parameter will contains what (if anything) was stored in the input
2135 buffer after the deflated data stream.
2137 This feature is useful when processing a file format that encapsulates
2138 a compressed data stream (e.g. gzip, zip).
2140 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
2142 Scans C<$buffer> until it reaches either a I<full flush point> or the
2145 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
2146 will be have all data up to the flush point removed. This can then be
2147 passed to the C<deflate> method.
2149 Any other return code means that a flush point was not found. If more
2150 data is available, C<inflateSync> can be called repeatedly with more
2151 compressed data until the flush point is found.
2154 =head2 B<$i-E<gt>dict_adler()>
2156 Returns the adler32 value for the dictionary.
2158 =head2 B<$i-E<gt>msg()>
2160 Returns the last error message generated by zlib.
2162 =head2 B<$i-E<gt>total_in()>
2164 Returns the total number of bytes compressed bytes input to inflate.
2166 =head2 B<$i-E<gt>total_out()>
2168 Returns the total number of uncompressed bytes output from inflate.
2172 Here is an example of using C<inflate>.
2177 use Compress::Zlib ;
2179 my $x = inflateInit()
2180 or die "Cannot create a inflation stream\n" ;
2186 my ($output, $status) ;
2187 while (read(STDIN, $input, 4096))
2189 ($output, $status) = $x->inflate(\$input) ;
2192 if $status == Z_OK or $status == Z_STREAM_END ;
2194 last if $status != Z_OK ;
2197 die "inflation failed\n"
2198 unless $status == Z_STREAM_END ;
2200 =head1 ACCESSING ZIP FILES
2202 Although it is possible (with some effort on your part) to use this
2203 module to access .zip files, there is a module on CPAN that will do all
2204 the hard work for you. Check out the C<Archive::Zip> module on CPAN at
2206 http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz
2211 All the I<zlib> constants are automatically imported when you make use
2212 of I<Compress::Zlib>.
2217 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>
2219 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
2221 L<File::GlobMapper|File::GlobMapper>, L<Archive::Tar|Archive::Zip>,
2222 L<IO::Zlib|IO::Zlib>
2224 For RFC 1950, 1951 and 1952 see
2225 F<http://www.faqs.org/rfcs/rfc1950.html>,
2226 F<http://www.faqs.org/rfcs/rfc1951.html> and
2227 F<http://www.faqs.org/rfcs/rfc1952.html>
2229 The primary site for the gzip program is F<http://www.gzip.org>.
2233 The I<Compress::Zlib> module was written by Paul Marquess,
2234 F<pmqs@cpan.org>. The latest copy of the module can be
2235 found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
2237 The I<zlib> compression library was written by Jean-loup Gailly
2238 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
2240 The primary site for the I<zlib> compression library is
2241 F<http://www.zlib.org>.
2243 =head1 MODIFICATION HISTORY
2245 See the Changes file.
2247 =head1 COPYRIGHT AND LICENSE
2250 Copyright (c) 1995-2005 Paul Marquess. All rights reserved.
2251 This program is free software; you can redistribute it and/or
2252 modify it under the same terms as Perl itself.