2 package Compress::Zlib;
9 use Scalar::Util qw(dualvar);
11 use IO::Compress::Base::Common 2.004 ;
12 use Compress::Raw::Zlib 2.004 ;
13 use IO::Compress::Gzip 2.004 ;
14 use IO::Uncompress::Gunzip 2.004 ;
19 our ($VERSION, $XS_VERSION, @ISA, @EXPORT, $AUTOLOAD);
22 $XS_VERSION = $VERSION;
23 $VERSION = eval $VERSION;
26 # Items to export into callers namespace by default. Note: do not export
27 # names by default without a very good reason. Use EXPORT_OK instead.
28 # Do not simply export all your public functions/methods/constants.
30 deflateInit inflateInit
37 push @EXPORT, @Compress::Raw::Zlib::EXPORT ;
41 *zlib_version = \&Compress::Raw::Zlib::zlib_version;
46 ($constname = $AUTOLOAD) =~ s/.*:://;
47 my ($error, $val) = Compress::Raw::Zlib::constant($constname);
48 Carp::croak $error if $error;
50 *{$AUTOLOAD} = sub { $val };
54 use constant FLAG_APPEND => 1 ;
55 use constant FLAG_CRC => 2 ;
56 use constant FLAG_ADLER => 4 ;
57 use constant FLAG_CONSUME_INPUT => 8 ;
62 "need dictionary", # Z_NEED_DICT 2
63 "stream end", # Z_STREAM_END 1
65 "file error", # Z_ERRNO (-1)
66 "stream error", # Z_STREAM_ERROR (-2)
67 "data error", # Z_DATA_ERROR (-3)
68 "insufficient memory", # Z_MEM_ERROR (-4)
69 "buffer error", # Z_BUF_ERROR (-5)
70 "incompatible version",# Z_VERSION_ERROR(-6)
79 $Compress::Zlib::gzerrno = 0 ;
81 elsif ($value == Z_ERRNO() || $value > 2) {
82 $Compress::Zlib::gzerrno = $! ;
85 $Compress::Zlib::gzerrno = dualvar($value+0, $my_z_errmsg[2 - $value]);
94 my $test_eof = shift ;
96 my $value = $gz->errorNo() || 0 ;
99 #my $gz = $self->[0] ;
100 # gzread uses Z_STREAM_END to denote a successful end
101 $value = Z_STREAM_END() if $gz->eof() && $value == 0 ;
109 my ($file, $mode) = @_ ;
112 my %defOpts = (Level => Z_DEFAULT_COMPRESSION(),
113 Strategy => Z_DEFAULT_STRATEGY(),
117 $writing = ! ($mode =~ /r/i) ;
118 $writing = ($mode =~ /[wa]/i) ;
120 $defOpts{Level} = $1 if $mode =~ /(\d)/;
121 $defOpts{Strategy} = Z_FILTERED() if $mode =~ /f/i;
122 $defOpts{Strategy} = Z_HUFFMAN_ONLY() if $mode =~ /h/i;
123 $defOpts{Append} = 1 if $mode =~ /a/i;
125 my $infDef = $writing ? 'deflate' : 'inflate';
128 croak "gzopen: file parameter is not a filehandle or filename"
129 unless isaFilehandle $file || isaFilename $file ||
130 (ref $file && ref $file eq 'SCALAR');
132 return undef unless $mode =~ /[rwa]/i ;
137 $gz = new IO::Compress::Gzip($file, Minimal => 1, AutoClose => 1,
139 or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError;
142 $gz = new IO::Uncompress::Gunzip($file,
148 or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
154 bless [$gz, $infDef], 'Compress::Zlib::gzFile';
157 sub Compress::Zlib::gzFile::gzread
161 return _set_gzerr(Z_STREAM_ERROR())
162 if $self->[1] ne 'inflate';
164 my $len = defined $_[1] ? $_[1] : 4096 ;
166 if ($self->gzeof() || $len == 0) {
167 # Zap the output buffer to match ver 1 behaviour.
172 my $gz = $self->[0] ;
173 my $status = $gz->read($_[0], $len) ;
178 sub Compress::Zlib::gzFile::gzreadline
182 my $gz = $self->[0] ;
183 $_[0] = $gz->getline() ;
185 return defined $_[0] ? length $_[0] : 0 ;
188 sub Compress::Zlib::gzFile::gzwrite
191 my $gz = $self->[0] ;
193 return _set_gzerr(Z_STREAM_ERROR())
194 if $self->[1] ne 'deflate';
196 my $status = $gz->write($_[0]) ;
201 sub Compress::Zlib::gzFile::gztell
204 my $gz = $self->[0] ;
205 my $status = $gz->tell() ;
210 sub Compress::Zlib::gzFile::gzseek
216 my $gz = $self->[0] ;
218 eval { $status = $gz->seek($offset, $whence) ; };
222 $error =~ s/^.*: /gzseek: /;
223 $error =~ s/ at .* line \d+\s*$//;
230 sub Compress::Zlib::gzFile::gzflush
235 my $gz = $self->[0] ;
236 my $status = $gz->flush($f) ;
241 sub Compress::Zlib::gzFile::gzclose
244 my $gz = $self->[0] ;
246 my $status = $gz->close() ;
251 sub Compress::Zlib::gzFile::gzeof
254 my $gz = $self->[0] ;
257 if $self->[1] ne 'inflate';
259 my $status = $gz->eof() ;
264 sub Compress::Zlib::gzFile::gzsetparams
267 croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
270 my $gz = $self->[0] ;
272 my $strategy = shift;
274 return _set_gzerr(Z_STREAM_ERROR())
275 if $self->[1] ne 'deflate';
277 my $status = *$gz->{Compress}->deflateParams(-Level => $level,
278 -Strategy => $strategy);
283 sub Compress::Zlib::gzFile::gzerror
286 my $gz = $self->[0] ;
288 return $Compress::Zlib::gzerrno ;
294 my ($x, $output, $err, $in) =('', '', '', '') ;
298 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
304 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
306 $x = new Compress::Raw::Zlib::Deflate -AppendOutput => 1, -Level => $level
309 $err = $x->deflate($in, $output) ;
310 return undef unless $err == Z_OK() ;
312 $err = $x->flush($output) ;
313 return undef unless $err == Z_OK() ;
321 my ($x, $output, $err, $in) =('', '', '', '') ;
325 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
331 $x = new Compress::Raw::Zlib::Inflate -ConsumeInput => 0 or return undef ;
333 $err = $x->inflate($in, $output) ;
334 return undef unless $err == Z_STREAM_END() ;
343 my ($got) = ParseParameters(0,
345 'Bufsize' => [1, 1, Parse_unsigned, 4096],
346 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
347 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
348 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
349 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
350 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
351 'Dictionary' => [1, 1, Parse_any, ""],
354 croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " .
355 $got->value('Bufsize')
356 unless $got->value('Bufsize') >= 1;
362 Compress::Raw::Zlib::_deflateInit(0,
363 $got->value('Level'),
364 $got->value('Method'),
365 $got->value('WindowBits'),
366 $got->value('MemLevel'),
367 $got->value('Strategy'),
368 $got->value('Bufsize'),
369 $got->value('Dictionary')) ;
371 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldDeflate" : undef) ;
372 return wantarray ? ($x, $status) : $x ;
377 my ($got) = ParseParameters(0,
379 'Bufsize' => [1, 1, Parse_unsigned, 4096],
380 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
381 'Dictionary' => [1, 1, Parse_any, ""],
385 croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " .
386 $got->value('Bufsize')
387 unless $got->value('Bufsize') >= 1;
391 ($obj, $status) = Compress::Raw::Zlib::_inflateInit(FLAG_CONSUME_INPUT,
392 $got->value('WindowBits'),
393 $got->value('Bufsize'),
394 $got->value('Dictionary')) ;
396 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldInflate" : undef) ;
398 wantarray ? ($x, $status) : $x ;
401 package Zlib::OldDeflate ;
404 @ISA = qw(Compress::Raw::Zlib::deflateStream);
412 my $status = $self->SUPER::deflate($_[0], $output) ;
413 wantarray ? ($output, $status) : $output ;
420 my $flag = shift || Compress::Zlib::Z_FINISH();
421 my $status = $self->SUPER::flush($output, $flag) ;
423 wantarray ? ($output, $status) : $output ;
426 package Zlib::OldInflate ;
429 @ISA = qw(Compress::Raw::Zlib::inflateStream);
435 my $status = $self->SUPER::inflate($_[0], $output) ;
436 wantarray ? ($output, $status) : $output ;
439 package Compress::Zlib ;
441 use IO::Compress::Gzip::Constants 2.004 ;
447 # if the deflation buffer isn't a reference, make it one
448 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
450 IO::Compress::Gzip::gzip($string, \$out, Minimal => 1)
457 sub _removeGzipHeader($)
461 return Z_DATA_ERROR()
462 if length($$string) < GZIP_MIN_HEADER_SIZE ;
464 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
465 unpack ('CCCCVCC', $$string);
467 return Z_DATA_ERROR()
468 unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
469 $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
470 substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
473 if ($flags & GZIP_FLG_FEXTRA)
475 return Z_DATA_ERROR()
476 if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
478 my ($extra_len) = unpack ('v', $$string);
479 $extra_len += GZIP_FEXTRA_HEADER_SIZE;
480 return Z_DATA_ERROR()
481 if length($$string) < $extra_len ;
483 substr($$string, 0, $extra_len) = '';
487 if ($flags & GZIP_FLG_FNAME)
489 my $name_end = index ($$string, GZIP_NULL_BYTE);
490 return Z_DATA_ERROR()
492 substr($$string, 0, $name_end + 1) = '';
496 if ($flags & GZIP_FLG_FCOMMENT)
498 my $comment_end = index ($$string, GZIP_NULL_BYTE);
499 return Z_DATA_ERROR()
500 if $comment_end == -1 ;
501 substr($$string, 0, $comment_end + 1) = '';
505 if ($flags & GZIP_FLG_FHCRC)
507 return Z_DATA_ERROR()
508 if length ($$string) < GZIP_FHCRC_SIZE ;
509 substr($$string, 0, GZIP_FHCRC_SIZE) = '';
518 # if the buffer isn't a reference, make it one
519 my $string = (ref $_[0] ? $_[0] : \$_[0]);
521 _removeGzipHeader($string) == Z_OK()
524 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
525 my $x = new Compress::Raw::Zlib::Inflate({-WindowBits => - MAX_WBITS(),
526 -Bufsize => $bufsize})
531 my $status = $x->inflate($string, $output);
533 unless $status == Z_STREAM_END();
535 if (length $$string >= 8)
537 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
538 substr($$string, 0, 8) = '';
540 unless $len == length($output) and
541 $crc == crc32($output);
550 # Autoload methods go after __END__, and are processed by the autosplit program.
558 Compress::Zlib - Interface to zlib compression library
564 ($d, $status) = deflateInit( [OPT] ) ;
565 $status = $d->deflate($input, $output) ;
566 $status = $d->flush($output [, $flush_type]) ;
567 $d->deflateParams(OPTS) ;
568 $d->deflateTune(OPTS) ;
579 ($i, $status) = inflateInit( [OPT] ) ;
580 $status = $i->inflate($input, $output [, $eof]) ;
581 $status = $i->inflateSync($input) ;
590 $dest = compress($source) ;
591 $dest = uncompress($source) ;
593 $gz = gzopen($filename or filehandle, $mode) ;
594 $bytesread = $gz->gzread($buffer [,$size]) ;
595 $bytesread = $gz->gzreadline($line) ;
596 $byteswritten = $gz->gzwrite($buffer) ;
597 $status = $gz->gzflush($flush) ;
598 $offset = $gz->gztell() ;
599 $status = $gz->gzseek($offset, $whence) ;
600 $status = $gz->gzclose() ;
601 $status = $gz->gzeof() ;
602 $status = $gz->gzsetparams($level, $strategy) ;
603 $errstring = $gz->gzerror() ;
606 $dest = Compress::Zlib::memGzip($buffer) ;
607 $dest = Compress::Zlib::memGunzip($buffer) ;
609 $crc = adler32($buffer [,$crc]) ;
610 $crc = crc32($buffer [,$crc]) ;
612 $crc = adler32_combine($crc1, $crc2, $len2)l
613 $crc = crc32_combine($adler1, $adler2, $len2)
622 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
623 compression library (see L</AUTHOR> for details about where to get
626 The C<Compress::Zlib> module can be split into two general areas of
627 functionality, namely a simple read/write interface to I<gzip> files
628 and a low-level in-memory compression/decompression interface.
630 Each of these areas will be discussed in the following sections.
632 =head2 Notes for users of Compress::Zlib version 1
634 The main change in C<Compress::Zlib> version 2.x is that it does not now
635 interface directly to the zlib library. Instead it uses the
636 C<IO::Compress::Gzip> and C<IO::Uncompress::Gunzip> modules for
637 reading/writing gzip files, and the C<Compress::Raw::Zlib> module for some
638 low-level zlib access.
640 The interface provided by version 2 should be 100% backward compatible with
641 version 1. If you find a difference in the expected behaviour please
642 contact the author (See L</AUTHOR>). See L<GZIP INTERFACE>
644 If you are writing new code, your first port of call should be to use one
647 =head1 GZIP INTERFACE
649 A number of functions are supplied in I<zlib> for reading and writing
650 I<gzip> files that conform to RFC 1952. This module provides an interface
653 If you have previously used C<Compress::Zlib> 1.x, the following
654 enhancements/changes have been made to the C<gzopen> interface:
660 If you want to to open either STDIN or STDOUT with C<gzopen>, you can now
661 optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
666 In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open
667 the underlying file. This made things especially tricky when a Perl
668 filehandle was passed to C<gzopen>. Behind the scenes the numeric C file
669 descriptor had to be extracted from the Perl filehandle and this passed to
672 Apart from being non-portable to some operating systems, this made it
673 difficult to use C<gzopen> in situations where you wanted to extract/create
674 a gzip data stream that is embedded in a larger file, without having to
675 resort to opening and closing the file multiple times.
677 It also made it impossible to pass a perl filehandle that wasn't associated
678 with a real filesystem file, like, say, an C<IO::String>.
680 In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been
681 completely rewritten to use the L<IO::Compress::Gzip|IO::Compress::Gzip>
682 for writing gzip files and L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>
683 for reading gzip files. None of the limitations mentioned above apply.
687 Addition of C<gzseek> to provide a restricted C<seek> interface.
695 A more complete and flexible interface for reading/writing gzip
696 files/buffers is included with the module C<IO-Compress-Zlib>. See
697 L<IO::Compress::Gzip|IO::Compress::Gzip> and
698 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for more details.
702 =item B<$gz = gzopen($filename, $mode)>
704 =item B<$gz = gzopen($filehandle, $mode)>
706 This function opens either the I<gzip> file C<$filename> for reading or
707 writing or attaches to the opened filehandle, C<$filehandle>.
708 It returns an object on success and C<undef> on failure.
710 When writing a gzip file this interface will I<always> create the smallest
711 possible gzip header (exactly 10 bytes). If you want greater control over
712 what gets stored in the gzip header (like the original filename or a
713 comment) use L<IO::Compress::Gzip|IO::Compress::Gzip> instead. Similarly if
714 you want to read the contents of the gzip header use
715 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>.
717 The second parameter, C<$mode>, is used to specify whether the file is
718 opened for reading or writing and to optionally specify a compression
719 level and compression strategy when writing. The format of the C<$mode>
720 parameter is similar to the mode parameter to the 'C' function C<fopen>,
721 so "rb" is used to open for reading, "wb" for writing and "ab" for
722 appending (writing at the end of the file).
724 To specify a compression level when writing, append a digit between 0
725 and 9 to the mode string -- 0 means no compression and 9 means maximum
727 If no compression level is specified Z_DEFAULT_COMPRESSION is used.
729 To specify the compression strategy when writing, append 'f' for filtered
730 data, 'h' for Huffman only compression, or 'R' for run-length encoding.
731 If no strategy is specified Z_DEFAULT_STRATEGY is used.
733 So, for example, "wb9" means open for writing with the maximum compression
734 using the default strategy and "wb4R" means open for writing with compression
735 level 4 and run-length encoding.
737 Refer to the I<zlib> documentation for the exact format of the C<$mode>
740 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
742 Reads C<$size> bytes from the compressed file into C<$buffer>. If
743 C<$size> is not specified, it will default to 4096. If the scalar
744 C<$buffer> is not large enough, it will be extended automatically.
746 Returns the number of bytes actually read. On EOF it returns 0 and in
747 the case of an error, -1.
749 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
751 Reads the next line from the compressed file into C<$line>.
753 Returns the number of bytes actually read. On EOF it returns 0 and in
754 the case of an error, -1.
756 It is legal to intermix calls to C<gzread> and C<gzreadline>.
758 In addition, C<gzreadline> fully supports the use of of the variable C<$/>
759 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
760 determine what constitutes an end of line. Both paragraph mode and file
761 slurp mode are supported.
764 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
766 Writes the contents of C<$buffer> to the compressed file. Returns the
767 number of bytes actually written, or 0 on error.
769 =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
771 Flushes all pending output into the compressed file.
773 This method takes an optional parameter, C<$flush_type>, that controls
774 how the flushing will be carried out. By default the C<$flush_type>
775 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
776 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
777 strongly recommended that you only set the C<flush_type> parameter if
778 you fully understand the implications of what it does - overuse of C<flush>
779 can seriously degrade the level of compression achieved. See the C<zlib>
780 documentation for details.
782 Returns 1 on success, 0 on failure.
785 =item B<$offset = $gz-E<gt>gztell() ;>
787 Returns the uncompressed file offset.
789 =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
791 Provides a sub-set of the C<seek> functionality, with the restriction
792 that it is only legal to seek forward in the compressed file.
793 It is a fatal error to attempt to seek backward.
795 When opened for writing, empty parts of the file will have NULL (0x00)
796 bytes written to them.
798 The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
800 Returns 1 on success, 0 on failure.
802 =item B<$gz-E<gt>gzclose>
804 Closes the compressed file. Any pending data is flushed to the file
807 Returns 1 on success, 0 on failure.
809 =item B<$gz-E<gt>gzsetparams($level, $strategy>
811 Change settings for the deflate stream C<$gz>.
813 The list of the valid options is shown below. Options not specified
814 will remain unchanged.
816 Note: This method is only available if you are running zlib 1.0.6 or better.
822 Defines the compression level. Valid values are 0 through 9,
823 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
824 C<Z_DEFAULT_COMPRESSION>.
828 Defines the strategy used to tune the compression. The valid values are
829 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
833 =item B<$gz-E<gt>gzerror>
835 Returns the I<zlib> error message or number for the last operation
836 associated with C<$gz>. The return value will be the I<zlib> error
837 number when used in a numeric context and the I<zlib> error message
838 when used in a string context. The I<zlib> error number constants,
839 shown below, are available for use.
851 The C<$gzerrno> scalar holds the error code associated with the most
852 recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
853 I<not> associated with a particular file.
855 As with C<gzerror()> it returns an error number in numeric context and
856 an error message in string context. Unlike C<gzerror()> though, the
857 error message will correspond to the I<zlib> message when the error is
858 associated with I<zlib> itself, or the UNIX error message when it is
859 not (i.e. I<zlib> returned C<Z_ERRORNO>).
861 As there is an overlap between the error numbers used by I<zlib> and
862 UNIX, C<$gzerrno> should only be used to check for the presence of
863 I<an> error in numeric context. Use C<gzerror()> to check for specific
864 I<zlib> errors. The I<gzcat> example below shows how the variable can
872 Here is an example script which uses the interface. It implements a
880 # use stdin if no files supplied
881 @ARGV = '-' unless @ARGV ;
883 foreach my $file (@ARGV) {
886 my $gz = gzopen($file, "rb")
887 or die "Cannot open $file: $gzerrno\n" ;
889 print $buffer while $gz->gzread($buffer) > 0 ;
891 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
892 if $gzerrno != Z_STREAM_END ;
897 Below is a script which makes use of C<gzreadline>. It implements a
898 very simple I<grep> like script.
905 die "Usage: gzgrep pattern [file...]\n"
908 my $pattern = shift ;
910 # use stdin if no files supplied
911 @ARGV = '-' unless @ARGV ;
913 foreach my $file (@ARGV) {
914 my $gz = gzopen($file, "rb")
915 or die "Cannot open $file: $gzerrno\n" ;
917 while ($gz->gzreadline($_) > 0) {
918 print if /$pattern/ ;
921 die "Error reading from $file: $gzerrno\n"
922 if $gzerrno != Z_STREAM_END ;
927 This script, I<gzstream>, does the opposite of the I<gzcat> script
928 above. It reads from standard input and writes a gzip data stream to
936 binmode STDOUT; # gzopen only sets it on the fd
938 my $gz = gzopen(\*STDOUT, "wb")
939 or die "Cannot open stdout: $gzerrno\n" ;
943 or die "error writing: $gzerrno\n" ;
948 =head2 Compress::Zlib::memGzip
950 This function is used to create an in-memory gzip file with the minimum
951 possible gzip header (exactly 10 bytes).
953 $dest = Compress::Zlib::memGzip($buffer) ;
955 If successful, it returns the in-memory gzip file, otherwise it returns
958 The C<$buffer> parameter can either be a scalar or a scalar reference.
960 See L<IO::Compress::Gzip|IO::Compress::Gzip> for an alternative way to
961 carry out in-memory gzip compression.
963 =head2 Compress::Zlib::memGunzip
965 This function is used to uncompress an in-memory gzip file.
967 $dest = Compress::Zlib::memGunzip($buffer) ;
969 If successful, it returns the uncompressed gzip file, otherwise it
972 The C<$buffer> parameter can either be a scalar or a scalar reference. The
973 contents of the C<$buffer> parameter are destroyed after calling this function.
975 See L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for an alternative way
976 to carry out in-memory gzip uncompression.
978 =head1 COMPRESS/UNCOMPRESS
980 Two functions are provided to perform in-memory compression/uncompression of
981 RFC 1950 data streams. They are called C<compress> and C<uncompress>.
985 =item B<$dest = compress($source [, $level] ) ;>
987 Compresses C<$source>. If successful it returns the compressed
988 data. Otherwise it returns I<undef>.
990 The source buffer, C<$source>, can either be a scalar or a scalar
993 The C<$level> parameter defines the compression level. Valid values are
994 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
995 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
996 If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
999 =item B<$dest = uncompress($source) ;>
1001 Uncompresses C<$source>. If successful it returns the uncompressed
1002 data. Otherwise it returns I<undef>.
1004 The source buffer can either be a scalar or a scalar reference.
1008 Please note: the two functions defined above are I<not> compatible with
1009 the Unix commands of the same name.
1011 See L<IO::Deflate|IO::Deflate> and L<IO::Inflate|IO::Inflate> included with
1012 this distribution for an alternative interface for reading/writing RFC 1950
1016 =head1 Deflate Interface
1018 This section defines an interface that allows in-memory compression using
1019 the I<deflate> interface provided by zlib.
1021 Here is a definition of the interface available:
1024 =head2 B<($d, $status) = deflateInit( [OPT] )>
1026 Initialises a deflation stream.
1028 It combines the features of the I<zlib> functions C<deflateInit>,
1029 C<deflateInit2> and C<deflateSetDictionary>.
1031 If successful, it will return the initialised deflation stream, C<$d>
1032 and C<$status> of C<Z_OK> in a list context. In scalar context it
1033 returns the deflation stream, C<$d>, only.
1035 If not successful, the returned deflation stream (C<$d>) will be
1036 I<undef> and C<$status> will hold the exact I<zlib> error code.
1038 The function optionally takes a number of named options specified as
1039 C<< -Name=>value >> pairs. This allows individual options to be
1040 tailored without having to specify them all in the parameter list.
1042 For backward compatibility, it is also possible to pass the parameters
1043 as a reference to a hash containing the name=>value pairs.
1045 The function takes one optional parameter, a reference to a hash. The
1046 contents of the hash allow the deflation interface to be tailored.
1048 Here is a list of the valid options:
1054 Defines the compression level. Valid values are 0 through 9,
1055 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1056 C<Z_DEFAULT_COMPRESSION>.
1058 The default is Z_DEFAULT_COMPRESSION.
1062 Defines the compression method. The only valid value at present (and
1063 the default) is Z_DEFLATED.
1065 =item B<-WindowBits>
1067 To create an RFC 1950 data stream, set C<WindowBits> to a positive number.
1069 To create an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1071 For a full definition of the meaning and valid values for C<WindowBits> refer
1072 to the I<zlib> documentation for I<deflateInit2>.
1074 Defaults to MAX_WBITS.
1078 For a definition of the meaning and valid values for C<MemLevel>
1079 refer to the I<zlib> documentation for I<deflateInit2>.
1081 Defaults to MAX_MEM_LEVEL.
1085 Defines the strategy used to tune the compression. The valid values are
1086 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1088 The default is Z_DEFAULT_STRATEGY.
1090 =item B<-Dictionary>
1092 When a dictionary is specified I<Compress::Zlib> will automatically
1093 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1094 Adler32 value for the dictionary can be obtained by calling the method
1095 C<$d->dict_adler()>.
1097 The default is no dictionary.
1101 Sets the initial size for the deflation buffer. If the buffer has to be
1102 reallocated to increase the size, it will grow in increments of
1105 The default is 4096.
1109 Here is an example of using the C<deflateInit> optional parameter list
1110 to override the default buffer size and compression level. All other
1111 options will take their default values.
1113 deflateInit( -Bufsize => 300,
1114 -Level => Z_BEST_SPEED ) ;
1117 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1120 Deflates the contents of C<$buffer>. The buffer can either be a scalar
1121 or a scalar reference. When finished, C<$buffer> will be
1122 completely processed (assuming there were no errors). If the deflation
1123 was successful it returns the deflated output, C<$out>, and a status
1124 value, C<$status>, of C<Z_OK>.
1126 On error, C<$out> will be I<undef> and C<$status> will contain the
1129 In a scalar context C<deflate> will return C<$out> only.
1131 As with the I<deflate> function in I<zlib>, it is not necessarily the
1132 case that any output will be produced by this method. So don't rely on
1133 the fact that C<$out> is empty for an error test.
1136 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
1138 Typically used to finish the deflation. Any pending output will be
1139 returned via C<$out>.
1140 C<$status> will have a value C<Z_OK> if successful.
1142 In a scalar context C<flush> will return C<$out> only.
1144 Note that flushing can seriously degrade the compression ratio, so it
1145 should only be used to terminate a decompression (using C<Z_FINISH>) or
1146 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1148 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1149 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1150 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1151 C<flush_type> parameter if you fully understand the implications of
1152 what it does. See the C<zlib> documentation for details.
1154 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1156 Change settings for the deflate stream C<$d>.
1158 The list of the valid options is shown below. Options not specified
1159 will remain unchanged.
1165 Defines the compression level. Valid values are 0 through 9,
1166 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1167 C<Z_DEFAULT_COMPRESSION>.
1171 Defines the strategy used to tune the compression. The valid values are
1172 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1176 =head2 B<$d-E<gt>dict_adler()>
1178 Returns the adler32 value for the dictionary.
1180 =head2 B<$d-E<gt>msg()>
1182 Returns the last error message generated by zlib.
1184 =head2 B<$d-E<gt>total_in()>
1186 Returns the total number of bytes uncompressed bytes input to deflate.
1188 =head2 B<$d-E<gt>total_out()>
1190 Returns the total number of compressed bytes output from deflate.
1195 Here is a trivial example of using C<deflate>. It simply reads standard
1196 input, deflates it and writes it to standard output.
1201 use Compress::Zlib ;
1205 my $x = deflateInit()
1206 or die "Cannot create a deflation stream\n" ;
1208 my ($output, $status) ;
1211 ($output, $status) = $x->deflate($_) ;
1214 or die "deflation failed\n" ;
1219 ($output, $status) = $x->flush() ;
1222 or die "deflation failed\n" ;
1226 =head1 Inflate Interface
1228 This section defines the interface available that allows in-memory
1229 uncompression using the I<deflate> interface provided by zlib.
1231 Here is a definition of the interface:
1234 =head2 B<($i, $status) = inflateInit()>
1236 Initialises an inflation stream.
1238 In a list context it returns the inflation stream, C<$i>, and the
1239 I<zlib> status code in C<$status>. In a scalar context it returns the
1240 inflation stream only.
1242 If successful, C<$i> will hold the inflation stream and C<$status> will
1245 If not successful, C<$i> will be I<undef> and C<$status> will hold the
1248 The function optionally takes a number of named options specified as
1249 C<< -Name=>value >> pairs. This allows individual options to be
1250 tailored without having to specify them all in the parameter list.
1252 For backward compatibility, it is also possible to pass the parameters
1253 as a reference to a hash containing the name=>value pairs.
1255 The function takes one optional parameter, a reference to a hash. The
1256 contents of the hash allow the deflation interface to be tailored.
1258 Here is a list of the valid options:
1262 =item B<-WindowBits>
1264 To uncompress an RFC 1950 data stream, set C<WindowBits> to a positive number.
1266 To uncompress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1268 For a full definition of the meaning and valid values for C<WindowBits> refer
1269 to the I<zlib> documentation for I<inflateInit2>.
1271 Defaults to MAX_WBITS.
1275 Sets the initial size for the inflation buffer. If the buffer has to be
1276 reallocated to increase the size, it will grow in increments of
1281 =item B<-Dictionary>
1283 The default is no dictionary.
1287 Here is an example of using the C<inflateInit> optional parameter to
1288 override the default buffer size.
1290 inflateInit( -Bufsize => 300 ) ;
1292 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
1294 Inflates the complete contents of C<$buffer>. The buffer can either be
1295 a scalar or a scalar reference.
1297 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1298 compressed data has been successfully reached.
1299 If not successful, C<$out> will be I<undef> and C<$status> will hold
1300 the I<zlib> error code.
1302 The C<$buffer> parameter is modified by C<inflate>. On completion it
1303 will contain what remains of the input buffer after inflation. This
1304 means that C<$buffer> will be an empty string when the return status is
1305 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
1306 parameter will contains what (if anything) was stored in the input
1307 buffer after the deflated data stream.
1309 This feature is useful when processing a file format that encapsulates
1310 a compressed data stream (e.g. gzip, zip).
1312 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
1314 Scans C<$buffer> until it reaches either a I<full flush point> or the
1317 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
1318 will be have all data up to the flush point removed. This can then be
1319 passed to the C<deflate> method.
1321 Any other return code means that a flush point was not found. If more
1322 data is available, C<inflateSync> can be called repeatedly with more
1323 compressed data until the flush point is found.
1326 =head2 B<$i-E<gt>dict_adler()>
1328 Returns the adler32 value for the dictionary.
1330 =head2 B<$i-E<gt>msg()>
1332 Returns the last error message generated by zlib.
1334 =head2 B<$i-E<gt>total_in()>
1336 Returns the total number of bytes compressed bytes input to inflate.
1338 =head2 B<$i-E<gt>total_out()>
1340 Returns the total number of uncompressed bytes output from inflate.
1344 Here is an example of using C<inflate>.
1349 use Compress::Zlib ;
1351 my $x = inflateInit()
1352 or die "Cannot create a inflation stream\n" ;
1358 my ($output, $status) ;
1359 while (read(STDIN, $input, 4096))
1361 ($output, $status) = $x->inflate(\$input) ;
1364 if $status == Z_OK or $status == Z_STREAM_END ;
1366 last if $status != Z_OK ;
1369 die "inflation failed\n"
1370 unless $status == Z_STREAM_END ;
1372 =head1 CHECKSUM FUNCTIONS
1374 Two functions are provided by I<zlib> to calculate checksums. For the
1375 Perl interface, the order of the two parameters in both functions has
1376 been reversed. This allows both running checksums and one off
1377 calculations to be done.
1379 $crc = adler32($buffer [,$crc]) ;
1380 $crc = crc32($buffer [,$crc]) ;
1382 The buffer parameters can either be a scalar or a scalar reference.
1384 If the $crc parameters is C<undef>, the crc value will be reset.
1386 If you have built this module with zlib 1.2.3 or better, two more
1387 CRC-related functions are available.
1389 $crc = adler32_combine($crc1, $crc2, $len2)l
1390 $crc = crc32_combine($adler1, $adler2, $len2)
1392 These functions allow checksums to be merged.
1396 All the I<zlib> constants are automatically imported when you make use
1397 of I<Compress::Zlib>.
1402 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::Compress::Bzip2>, L<IO::Uncompress::Bunzip2>, L<IO::Compress::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
1404 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1406 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1407 L<Archive::Tar|Archive::Tar>,
1408 L<IO::Zlib|IO::Zlib>
1411 For RFC 1950, 1951 and 1952 see
1412 F<http://www.faqs.org/rfcs/rfc1950.html>,
1413 F<http://www.faqs.org/rfcs/rfc1951.html> and
1414 F<http://www.faqs.org/rfcs/rfc1952.html>
1416 The I<zlib> compression library was written by Jean-loup Gailly
1417 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1419 The primary site for the I<zlib> compression library is
1420 F<http://www.zlib.org>.
1422 The primary site for gzip is F<http://www.gzip.org>.
1429 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1433 =head1 MODIFICATION HISTORY
1435 See the Changes file.
1437 =head1 COPYRIGHT AND LICENSE
1439 Copyright (c) 1995-2007 Paul Marquess. All rights reserved.
1441 This program is free software; you can redistribute it and/or
1442 modify it under the same terms as Perl itself.