2 package Compress::Zlib;
9 use Scalar::Util qw(dualvar);
11 use IO::Compress::Base::Common 2.005 ;
12 use Compress::Raw::Zlib 2.005 ;
13 use IO::Compress::Gzip 2.005 ;
14 use IO::Uncompress::Gunzip 2.005 ;
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 $] >= 5.008 and (utf8::downgrade($_[0], 1)
197 or croak "Wide character in gzwrite");
199 my $status = $gz->write($_[0]) ;
204 sub Compress::Zlib::gzFile::gztell
207 my $gz = $self->[0] ;
208 my $status = $gz->tell() ;
213 sub Compress::Zlib::gzFile::gzseek
219 my $gz = $self->[0] ;
221 eval { $status = $gz->seek($offset, $whence) ; };
225 $error =~ s/^.*: /gzseek: /;
226 $error =~ s/ at .* line \d+\s*$//;
233 sub Compress::Zlib::gzFile::gzflush
238 my $gz = $self->[0] ;
239 my $status = $gz->flush($f) ;
244 sub Compress::Zlib::gzFile::gzclose
247 my $gz = $self->[0] ;
249 my $status = $gz->close() ;
254 sub Compress::Zlib::gzFile::gzeof
257 my $gz = $self->[0] ;
260 if $self->[1] ne 'inflate';
262 my $status = $gz->eof() ;
267 sub Compress::Zlib::gzFile::gzsetparams
270 croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
273 my $gz = $self->[0] ;
275 my $strategy = shift;
277 return _set_gzerr(Z_STREAM_ERROR())
278 if $self->[1] ne 'deflate';
280 my $status = *$gz->{Compress}->deflateParams(-Level => $level,
281 -Strategy => $strategy);
286 sub Compress::Zlib::gzFile::gzerror
289 my $gz = $self->[0] ;
291 return $Compress::Zlib::gzerrno ;
297 my ($x, $output, $err, $in) =('', '', '', '') ;
301 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
307 $] >= 5.008 and (utf8::downgrade($$in, 1)
308 or croak "Wide character in compress");
310 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
312 $x = new Compress::Raw::Zlib::Deflate -AppendOutput => 1, -Level => $level
315 $err = $x->deflate($in, $output) ;
316 return undef unless $err == Z_OK() ;
318 $err = $x->flush($output) ;
319 return undef unless $err == Z_OK() ;
327 my ($x, $output, $err, $in) =('', '', '', '') ;
331 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
337 $] >= 5.008 and (utf8::downgrade($$in, 1)
338 or croak "Wide character in uncompress");
340 $x = new Compress::Raw::Zlib::Inflate -ConsumeInput => 0 or return undef ;
342 $err = $x->inflate($in, $output) ;
343 return undef unless $err == Z_STREAM_END() ;
352 my ($got) = ParseParameters(0,
354 'Bufsize' => [1, 1, Parse_unsigned, 4096],
355 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
356 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
357 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
358 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
359 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
360 'Dictionary' => [1, 1, Parse_any, ""],
363 croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " .
364 $got->value('Bufsize')
365 unless $got->value('Bufsize') >= 1;
371 Compress::Raw::Zlib::_deflateInit(0,
372 $got->value('Level'),
373 $got->value('Method'),
374 $got->value('WindowBits'),
375 $got->value('MemLevel'),
376 $got->value('Strategy'),
377 $got->value('Bufsize'),
378 $got->value('Dictionary')) ;
380 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldDeflate" : undef) ;
381 return wantarray ? ($x, $status) : $x ;
386 my ($got) = ParseParameters(0,
388 'Bufsize' => [1, 1, Parse_unsigned, 4096],
389 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
390 'Dictionary' => [1, 1, Parse_any, ""],
394 croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " .
395 $got->value('Bufsize')
396 unless $got->value('Bufsize') >= 1;
400 ($obj, $status) = Compress::Raw::Zlib::_inflateInit(FLAG_CONSUME_INPUT,
401 $got->value('WindowBits'),
402 $got->value('Bufsize'),
403 $got->value('Dictionary')) ;
405 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldInflate" : undef) ;
407 wantarray ? ($x, $status) : $x ;
410 package Zlib::OldDeflate ;
413 @ISA = qw(Compress::Raw::Zlib::deflateStream);
421 my $status = $self->SUPER::deflate($_[0], $output) ;
422 wantarray ? ($output, $status) : $output ;
429 my $flag = shift || Compress::Zlib::Z_FINISH();
430 my $status = $self->SUPER::flush($output, $flag) ;
432 wantarray ? ($output, $status) : $output ;
435 package Zlib::OldInflate ;
438 @ISA = qw(Compress::Raw::Zlib::inflateStream);
444 my $status = $self->SUPER::inflate($_[0], $output) ;
445 wantarray ? ($output, $status) : $output ;
448 package Compress::Zlib ;
450 use IO::Compress::Gzip::Constants 2.005 ;
456 # if the deflation buffer isn't a reference, make it one
457 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
459 $] >= 5.008 and (utf8::downgrade($$string, 1)
460 or croak "Wide character in memGzip");
462 IO::Compress::Gzip::gzip($string, \$out, Minimal => 1)
469 sub _removeGzipHeader($)
473 return Z_DATA_ERROR()
474 if length($$string) < GZIP_MIN_HEADER_SIZE ;
476 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
477 unpack ('CCCCVCC', $$string);
479 return Z_DATA_ERROR()
480 unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
481 $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
482 substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
485 if ($flags & GZIP_FLG_FEXTRA)
487 return Z_DATA_ERROR()
488 if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
490 my ($extra_len) = unpack ('v', $$string);
491 $extra_len += GZIP_FEXTRA_HEADER_SIZE;
492 return Z_DATA_ERROR()
493 if length($$string) < $extra_len ;
495 substr($$string, 0, $extra_len) = '';
499 if ($flags & GZIP_FLG_FNAME)
501 my $name_end = index ($$string, GZIP_NULL_BYTE);
502 return Z_DATA_ERROR()
504 substr($$string, 0, $name_end + 1) = '';
508 if ($flags & GZIP_FLG_FCOMMENT)
510 my $comment_end = index ($$string, GZIP_NULL_BYTE);
511 return Z_DATA_ERROR()
512 if $comment_end == -1 ;
513 substr($$string, 0, $comment_end + 1) = '';
517 if ($flags & GZIP_FLG_FHCRC)
519 return Z_DATA_ERROR()
520 if length ($$string) < GZIP_FHCRC_SIZE ;
521 substr($$string, 0, GZIP_FHCRC_SIZE) = '';
530 # if the buffer isn't a reference, make it one
531 my $string = (ref $_[0] ? $_[0] : \$_[0]);
533 $] >= 5.008 and (utf8::downgrade($$string, 1)
534 or croak "Wide character in memGunzip");
536 _removeGzipHeader($string) == Z_OK()
539 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
540 my $x = new Compress::Raw::Zlib::Inflate({-WindowBits => - MAX_WBITS(),
541 -Bufsize => $bufsize})
546 my $status = $x->inflate($string, $output);
548 unless $status == Z_STREAM_END();
550 if (length $$string >= 8)
552 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
553 substr($$string, 0, 8) = '';
555 unless $len == length($output) and
556 $crc == crc32($output);
565 # Autoload methods go after __END__, and are processed by the autosplit program.
573 Compress::Zlib - Interface to zlib compression library
579 ($d, $status) = deflateInit( [OPT] ) ;
580 $status = $d->deflate($input, $output) ;
581 $status = $d->flush($output [, $flush_type]) ;
582 $d->deflateParams(OPTS) ;
583 $d->deflateTune(OPTS) ;
594 ($i, $status) = inflateInit( [OPT] ) ;
595 $status = $i->inflate($input, $output [, $eof]) ;
596 $status = $i->inflateSync($input) ;
605 $dest = compress($source) ;
606 $dest = uncompress($source) ;
608 $gz = gzopen($filename or filehandle, $mode) ;
609 $bytesread = $gz->gzread($buffer [,$size]) ;
610 $bytesread = $gz->gzreadline($line) ;
611 $byteswritten = $gz->gzwrite($buffer) ;
612 $status = $gz->gzflush($flush) ;
613 $offset = $gz->gztell() ;
614 $status = $gz->gzseek($offset, $whence) ;
615 $status = $gz->gzclose() ;
616 $status = $gz->gzeof() ;
617 $status = $gz->gzsetparams($level, $strategy) ;
618 $errstring = $gz->gzerror() ;
621 $dest = Compress::Zlib::memGzip($buffer) ;
622 $dest = Compress::Zlib::memGunzip($buffer) ;
624 $crc = adler32($buffer [,$crc]) ;
625 $crc = crc32($buffer [,$crc]) ;
627 $crc = adler32_combine($crc1, $crc2, $len2)l
628 $crc = crc32_combine($adler1, $adler2, $len2)
637 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
638 compression library (see L</AUTHOR> for details about where to get
641 The C<Compress::Zlib> module can be split into two general areas of
642 functionality, namely a simple read/write interface to I<gzip> files
643 and a low-level in-memory compression/decompression interface.
645 Each of these areas will be discussed in the following sections.
647 =head2 Notes for users of Compress::Zlib version 1
649 The main change in C<Compress::Zlib> version 2.x is that it does not now
650 interface directly to the zlib library. Instead it uses the
651 C<IO::Compress::Gzip> and C<IO::Uncompress::Gunzip> modules for
652 reading/writing gzip files, and the C<Compress::Raw::Zlib> module for some
653 low-level zlib access.
655 The interface provided by version 2 should be 100% backward compatible with
656 version 1. If you find a difference in the expected behaviour please
657 contact the author (See L</AUTHOR>). See L<GZIP INTERFACE>
659 If you are writing new code, your first port of call should be to use one
662 =head1 GZIP INTERFACE
664 A number of functions are supplied in I<zlib> for reading and writing
665 I<gzip> files that conform to RFC 1952. This module provides an interface
668 If you have previously used C<Compress::Zlib> 1.x, the following
669 enhancements/changes have been made to the C<gzopen> interface:
675 If you want to to open either STDIN or STDOUT with C<gzopen>, you can now
676 optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
681 In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open
682 the underlying file. This made things especially tricky when a Perl
683 filehandle was passed to C<gzopen>. Behind the scenes the numeric C file
684 descriptor had to be extracted from the Perl filehandle and this passed to
687 Apart from being non-portable to some operating systems, this made it
688 difficult to use C<gzopen> in situations where you wanted to extract/create
689 a gzip data stream that is embedded in a larger file, without having to
690 resort to opening and closing the file multiple times.
692 It also made it impossible to pass a perl filehandle that wasn't associated
693 with a real filesystem file, like, say, an C<IO::String>.
695 In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been
696 completely rewritten to use the L<IO::Compress::Gzip|IO::Compress::Gzip>
697 for writing gzip files and L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>
698 for reading gzip files. None of the limitations mentioned above apply.
702 Addition of C<gzseek> to provide a restricted C<seek> interface.
710 A more complete and flexible interface for reading/writing gzip
711 files/buffers is included with the module C<IO-Compress-Zlib>. See
712 L<IO::Compress::Gzip|IO::Compress::Gzip> and
713 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for more details.
717 =item B<$gz = gzopen($filename, $mode)>
719 =item B<$gz = gzopen($filehandle, $mode)>
721 This function opens either the I<gzip> file C<$filename> for reading or
722 writing or attaches to the opened filehandle, C<$filehandle>.
723 It returns an object on success and C<undef> on failure.
725 When writing a gzip file this interface will I<always> create the smallest
726 possible gzip header (exactly 10 bytes). If you want greater control over
727 what gets stored in the gzip header (like the original filename or a
728 comment) use L<IO::Compress::Gzip|IO::Compress::Gzip> instead. Similarly if
729 you want to read the contents of the gzip header use
730 L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>.
732 The second parameter, C<$mode>, is used to specify whether the file is
733 opened for reading or writing and to optionally specify a compression
734 level and compression strategy when writing. The format of the C<$mode>
735 parameter is similar to the mode parameter to the 'C' function C<fopen>,
736 so "rb" is used to open for reading, "wb" for writing and "ab" for
737 appending (writing at the end of the file).
739 To specify a compression level when writing, append a digit between 0
740 and 9 to the mode string -- 0 means no compression and 9 means maximum
742 If no compression level is specified Z_DEFAULT_COMPRESSION is used.
744 To specify the compression strategy when writing, append 'f' for filtered
745 data, 'h' for Huffman only compression, or 'R' for run-length encoding.
746 If no strategy is specified Z_DEFAULT_STRATEGY is used.
748 So, for example, "wb9" means open for writing with the maximum compression
749 using the default strategy and "wb4R" means open for writing with compression
750 level 4 and run-length encoding.
752 Refer to the I<zlib> documentation for the exact format of the C<$mode>
755 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
757 Reads C<$size> bytes from the compressed file into C<$buffer>. If
758 C<$size> is not specified, it will default to 4096. If the scalar
759 C<$buffer> is not large enough, it will be extended automatically.
761 Returns the number of bytes actually read. On EOF it returns 0 and in
762 the case of an error, -1.
764 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
766 Reads the next line from the compressed file into C<$line>.
768 Returns the number of bytes actually read. On EOF it returns 0 and in
769 the case of an error, -1.
771 It is legal to intermix calls to C<gzread> and C<gzreadline>.
773 In addition, C<gzreadline> fully supports the use of of the variable C<$/>
774 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
775 determine what constitutes an end of line. Both paragraph mode and file
776 slurp mode are supported.
779 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
781 Writes the contents of C<$buffer> to the compressed file. Returns the
782 number of bytes actually written, or 0 on error.
784 =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
786 Flushes all pending output into the compressed file.
788 This method takes an optional parameter, C<$flush_type>, that controls
789 how the flushing will be carried out. By default the C<$flush_type>
790 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
791 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
792 strongly recommended that you only set the C<flush_type> parameter if
793 you fully understand the implications of what it does - overuse of C<flush>
794 can seriously degrade the level of compression achieved. See the C<zlib>
795 documentation for details.
797 Returns 1 on success, 0 on failure.
800 =item B<$offset = $gz-E<gt>gztell() ;>
802 Returns the uncompressed file offset.
804 =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
806 Provides a sub-set of the C<seek> functionality, with the restriction
807 that it is only legal to seek forward in the compressed file.
808 It is a fatal error to attempt to seek backward.
810 When opened for writing, empty parts of the file will have NULL (0x00)
811 bytes written to them.
813 The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
815 Returns 1 on success, 0 on failure.
817 =item B<$gz-E<gt>gzclose>
819 Closes the compressed file. Any pending data is flushed to the file
822 Returns 1 on success, 0 on failure.
824 =item B<$gz-E<gt>gzsetparams($level, $strategy>
826 Change settings for the deflate stream C<$gz>.
828 The list of the valid options is shown below. Options not specified
829 will remain unchanged.
831 Note: This method is only available if you are running zlib 1.0.6 or better.
837 Defines the compression level. Valid values are 0 through 9,
838 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
839 C<Z_DEFAULT_COMPRESSION>.
843 Defines the strategy used to tune the compression. The valid values are
844 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
848 =item B<$gz-E<gt>gzerror>
850 Returns the I<zlib> error message or number for the last operation
851 associated with C<$gz>. The return value will be the I<zlib> error
852 number when used in a numeric context and the I<zlib> error message
853 when used in a string context. The I<zlib> error number constants,
854 shown below, are available for use.
866 The C<$gzerrno> scalar holds the error code associated with the most
867 recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
868 I<not> associated with a particular file.
870 As with C<gzerror()> it returns an error number in numeric context and
871 an error message in string context. Unlike C<gzerror()> though, the
872 error message will correspond to the I<zlib> message when the error is
873 associated with I<zlib> itself, or the UNIX error message when it is
874 not (i.e. I<zlib> returned C<Z_ERRORNO>).
876 As there is an overlap between the error numbers used by I<zlib> and
877 UNIX, C<$gzerrno> should only be used to check for the presence of
878 I<an> error in numeric context. Use C<gzerror()> to check for specific
879 I<zlib> errors. The I<gzcat> example below shows how the variable can
887 Here is an example script which uses the interface. It implements a
895 # use stdin if no files supplied
896 @ARGV = '-' unless @ARGV ;
898 foreach my $file (@ARGV) {
901 my $gz = gzopen($file, "rb")
902 or die "Cannot open $file: $gzerrno\n" ;
904 print $buffer while $gz->gzread($buffer) > 0 ;
906 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
907 if $gzerrno != Z_STREAM_END ;
912 Below is a script which makes use of C<gzreadline>. It implements a
913 very simple I<grep> like script.
920 die "Usage: gzgrep pattern [file...]\n"
923 my $pattern = shift ;
925 # use stdin if no files supplied
926 @ARGV = '-' unless @ARGV ;
928 foreach my $file (@ARGV) {
929 my $gz = gzopen($file, "rb")
930 or die "Cannot open $file: $gzerrno\n" ;
932 while ($gz->gzreadline($_) > 0) {
933 print if /$pattern/ ;
936 die "Error reading from $file: $gzerrno\n"
937 if $gzerrno != Z_STREAM_END ;
942 This script, I<gzstream>, does the opposite of the I<gzcat> script
943 above. It reads from standard input and writes a gzip data stream to
951 binmode STDOUT; # gzopen only sets it on the fd
953 my $gz = gzopen(\*STDOUT, "wb")
954 or die "Cannot open stdout: $gzerrno\n" ;
958 or die "error writing: $gzerrno\n" ;
963 =head2 Compress::Zlib::memGzip
965 This function is used to create an in-memory gzip file with the minimum
966 possible gzip header (exactly 10 bytes).
968 $dest = Compress::Zlib::memGzip($buffer) ;
970 If successful, it returns the in-memory gzip file, otherwise it returns
973 The C<$buffer> parameter can either be a scalar or a scalar reference.
975 See L<IO::Compress::Gzip|IO::Compress::Gzip> for an alternative way to
976 carry out in-memory gzip compression.
978 =head2 Compress::Zlib::memGunzip
980 This function is used to uncompress an in-memory gzip file.
982 $dest = Compress::Zlib::memGunzip($buffer) ;
984 If successful, it returns the uncompressed gzip file, otherwise it
987 The C<$buffer> parameter can either be a scalar or a scalar reference. The
988 contents of the C<$buffer> parameter are destroyed after calling this function.
990 See L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for an alternative way
991 to carry out in-memory gzip uncompression.
993 =head1 COMPRESS/UNCOMPRESS
995 Two functions are provided to perform in-memory compression/uncompression of
996 RFC 1950 data streams. They are called C<compress> and C<uncompress>.
1000 =item B<$dest = compress($source [, $level] ) ;>
1002 Compresses C<$source>. If successful it returns the compressed
1003 data. Otherwise it returns I<undef>.
1005 The source buffer, C<$source>, can either be a scalar or a scalar
1008 The C<$level> parameter defines the compression level. Valid values are
1009 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
1010 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
1011 If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
1014 =item B<$dest = uncompress($source) ;>
1016 Uncompresses C<$source>. If successful it returns the uncompressed
1017 data. Otherwise it returns I<undef>.
1019 The source buffer can either be a scalar or a scalar reference.
1023 Please note: the two functions defined above are I<not> compatible with
1024 the Unix commands of the same name.
1026 See L<IO::Deflate|IO::Deflate> and L<IO::Inflate|IO::Inflate> included with
1027 this distribution for an alternative interface for reading/writing RFC 1950
1031 =head1 Deflate Interface
1033 This section defines an interface that allows in-memory compression using
1034 the I<deflate> interface provided by zlib.
1036 Here is a definition of the interface available:
1039 =head2 B<($d, $status) = deflateInit( [OPT] )>
1041 Initialises a deflation stream.
1043 It combines the features of the I<zlib> functions C<deflateInit>,
1044 C<deflateInit2> and C<deflateSetDictionary>.
1046 If successful, it will return the initialised deflation stream, C<$d>
1047 and C<$status> of C<Z_OK> in a list context. In scalar context it
1048 returns the deflation stream, C<$d>, only.
1050 If not successful, the returned deflation stream (C<$d>) will be
1051 I<undef> and C<$status> will hold the exact I<zlib> error code.
1053 The function optionally takes a number of named options specified as
1054 C<< -Name=>value >> pairs. This allows individual options to be
1055 tailored without having to specify them all in the parameter list.
1057 For backward compatibility, it is also possible to pass the parameters
1058 as a reference to a hash containing the name=>value pairs.
1060 The function takes one optional parameter, a reference to a hash. The
1061 contents of the hash allow the deflation interface to be tailored.
1063 Here is a list of the valid options:
1069 Defines the compression level. Valid values are 0 through 9,
1070 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1071 C<Z_DEFAULT_COMPRESSION>.
1073 The default is Z_DEFAULT_COMPRESSION.
1077 Defines the compression method. The only valid value at present (and
1078 the default) is Z_DEFLATED.
1080 =item B<-WindowBits>
1082 To create an RFC 1950 data stream, set C<WindowBits> to a positive number.
1084 To create an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1086 For a full definition of the meaning and valid values for C<WindowBits> refer
1087 to the I<zlib> documentation for I<deflateInit2>.
1089 Defaults to MAX_WBITS.
1093 For a definition of the meaning and valid values for C<MemLevel>
1094 refer to the I<zlib> documentation for I<deflateInit2>.
1096 Defaults to MAX_MEM_LEVEL.
1100 Defines the strategy used to tune the compression. The valid values are
1101 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1103 The default is Z_DEFAULT_STRATEGY.
1105 =item B<-Dictionary>
1107 When a dictionary is specified I<Compress::Zlib> will automatically
1108 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1109 Adler32 value for the dictionary can be obtained by calling the method
1110 C<$d->dict_adler()>.
1112 The default is no dictionary.
1116 Sets the initial size for the deflation buffer. If the buffer has to be
1117 reallocated to increase the size, it will grow in increments of
1120 The default is 4096.
1124 Here is an example of using the C<deflateInit> optional parameter list
1125 to override the default buffer size and compression level. All other
1126 options will take their default values.
1128 deflateInit( -Bufsize => 300,
1129 -Level => Z_BEST_SPEED ) ;
1132 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1135 Deflates the contents of C<$buffer>. The buffer can either be a scalar
1136 or a scalar reference. When finished, C<$buffer> will be
1137 completely processed (assuming there were no errors). If the deflation
1138 was successful it returns the deflated output, C<$out>, and a status
1139 value, C<$status>, of C<Z_OK>.
1141 On error, C<$out> will be I<undef> and C<$status> will contain the
1144 In a scalar context C<deflate> will return C<$out> only.
1146 As with the I<deflate> function in I<zlib>, it is not necessarily the
1147 case that any output will be produced by this method. So don't rely on
1148 the fact that C<$out> is empty for an error test.
1151 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
1153 Typically used to finish the deflation. Any pending output will be
1154 returned via C<$out>.
1155 C<$status> will have a value C<Z_OK> if successful.
1157 In a scalar context C<flush> will return C<$out> only.
1159 Note that flushing can seriously degrade the compression ratio, so it
1160 should only be used to terminate a decompression (using C<Z_FINISH>) or
1161 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1163 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1164 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1165 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1166 C<flush_type> parameter if you fully understand the implications of
1167 what it does. See the C<zlib> documentation for details.
1169 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1171 Change settings for the deflate stream C<$d>.
1173 The list of the valid options is shown below. Options not specified
1174 will remain unchanged.
1180 Defines the compression level. Valid values are 0 through 9,
1181 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1182 C<Z_DEFAULT_COMPRESSION>.
1186 Defines the strategy used to tune the compression. The valid values are
1187 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1191 =head2 B<$d-E<gt>dict_adler()>
1193 Returns the adler32 value for the dictionary.
1195 =head2 B<$d-E<gt>msg()>
1197 Returns the last error message generated by zlib.
1199 =head2 B<$d-E<gt>total_in()>
1201 Returns the total number of bytes uncompressed bytes input to deflate.
1203 =head2 B<$d-E<gt>total_out()>
1205 Returns the total number of compressed bytes output from deflate.
1210 Here is a trivial example of using C<deflate>. It simply reads standard
1211 input, deflates it and writes it to standard output.
1216 use Compress::Zlib ;
1220 my $x = deflateInit()
1221 or die "Cannot create a deflation stream\n" ;
1223 my ($output, $status) ;
1226 ($output, $status) = $x->deflate($_) ;
1229 or die "deflation failed\n" ;
1234 ($output, $status) = $x->flush() ;
1237 or die "deflation failed\n" ;
1241 =head1 Inflate Interface
1243 This section defines the interface available that allows in-memory
1244 uncompression using the I<deflate> interface provided by zlib.
1246 Here is a definition of the interface:
1249 =head2 B<($i, $status) = inflateInit()>
1251 Initialises an inflation stream.
1253 In a list context it returns the inflation stream, C<$i>, and the
1254 I<zlib> status code in C<$status>. In a scalar context it returns the
1255 inflation stream only.
1257 If successful, C<$i> will hold the inflation stream and C<$status> will
1260 If not successful, C<$i> will be I<undef> and C<$status> will hold the
1263 The function optionally takes a number of named options specified as
1264 C<< -Name=>value >> pairs. This allows individual options to be
1265 tailored without having to specify them all in the parameter list.
1267 For backward compatibility, it is also possible to pass the parameters
1268 as a reference to a hash containing the name=>value pairs.
1270 The function takes one optional parameter, a reference to a hash. The
1271 contents of the hash allow the deflation interface to be tailored.
1273 Here is a list of the valid options:
1277 =item B<-WindowBits>
1279 To uncompress an RFC 1950 data stream, set C<WindowBits> to a positive number.
1281 To uncompress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1283 For a full definition of the meaning and valid values for C<WindowBits> refer
1284 to the I<zlib> documentation for I<inflateInit2>.
1286 Defaults to MAX_WBITS.
1290 Sets the initial size for the inflation buffer. If the buffer has to be
1291 reallocated to increase the size, it will grow in increments of
1296 =item B<-Dictionary>
1298 The default is no dictionary.
1302 Here is an example of using the C<inflateInit> optional parameter to
1303 override the default buffer size.
1305 inflateInit( -Bufsize => 300 ) ;
1307 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
1309 Inflates the complete contents of C<$buffer>. The buffer can either be
1310 a scalar or a scalar reference.
1312 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1313 compressed data has been successfully reached.
1314 If not successful, C<$out> will be I<undef> and C<$status> will hold
1315 the I<zlib> error code.
1317 The C<$buffer> parameter is modified by C<inflate>. On completion it
1318 will contain what remains of the input buffer after inflation. This
1319 means that C<$buffer> will be an empty string when the return status is
1320 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
1321 parameter will contains what (if anything) was stored in the input
1322 buffer after the deflated data stream.
1324 This feature is useful when processing a file format that encapsulates
1325 a compressed data stream (e.g. gzip, zip).
1327 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
1329 Scans C<$buffer> until it reaches either a I<full flush point> or the
1332 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
1333 will be have all data up to the flush point removed. This can then be
1334 passed to the C<deflate> method.
1336 Any other return code means that a flush point was not found. If more
1337 data is available, C<inflateSync> can be called repeatedly with more
1338 compressed data until the flush point is found.
1341 =head2 B<$i-E<gt>dict_adler()>
1343 Returns the adler32 value for the dictionary.
1345 =head2 B<$i-E<gt>msg()>
1347 Returns the last error message generated by zlib.
1349 =head2 B<$i-E<gt>total_in()>
1351 Returns the total number of bytes compressed bytes input to inflate.
1353 =head2 B<$i-E<gt>total_out()>
1355 Returns the total number of uncompressed bytes output from inflate.
1359 Here is an example of using C<inflate>.
1364 use Compress::Zlib ;
1366 my $x = inflateInit()
1367 or die "Cannot create a inflation stream\n" ;
1373 my ($output, $status) ;
1374 while (read(STDIN, $input, 4096))
1376 ($output, $status) = $x->inflate(\$input) ;
1379 if $status == Z_OK or $status == Z_STREAM_END ;
1381 last if $status != Z_OK ;
1384 die "inflation failed\n"
1385 unless $status == Z_STREAM_END ;
1387 =head1 CHECKSUM FUNCTIONS
1389 Two functions are provided by I<zlib> to calculate checksums. For the
1390 Perl interface, the order of the two parameters in both functions has
1391 been reversed. This allows both running checksums and one off
1392 calculations to be done.
1394 $crc = adler32($buffer [,$crc]) ;
1395 $crc = crc32($buffer [,$crc]) ;
1397 The buffer parameters can either be a scalar or a scalar reference.
1399 If the $crc parameters is C<undef>, the crc value will be reset.
1401 If you have built this module with zlib 1.2.3 or better, two more
1402 CRC-related functions are available.
1404 $crc = adler32_combine($crc1, $crc2, $len2)l
1405 $crc = crc32_combine($adler1, $adler2, $len2)
1407 These functions allow checksums to be merged.
1411 All the I<zlib> constants are automatically imported when you make use
1412 of I<Compress::Zlib>.
1417 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>
1419 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1421 L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1422 L<Archive::Tar|Archive::Tar>,
1423 L<IO::Zlib|IO::Zlib>
1426 For RFC 1950, 1951 and 1952 see
1427 F<http://www.faqs.org/rfcs/rfc1950.html>,
1428 F<http://www.faqs.org/rfcs/rfc1951.html> and
1429 F<http://www.faqs.org/rfcs/rfc1952.html>
1431 The I<zlib> compression library was written by Jean-loup Gailly
1432 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1434 The primary site for the I<zlib> compression library is
1435 F<http://www.zlib.org>.
1437 The primary site for gzip is F<http://www.gzip.org>.
1444 This module was written by Paul Marquess, F<pmqs@cpan.org>.
1448 =head1 MODIFICATION HISTORY
1450 See the Changes file.
1452 =head1 COPYRIGHT AND LICENSE
1454 Copyright (c) 1995-2007 Paul Marquess. All rights reserved.
1456 This program is free software; you can redistribute it and/or
1457 modify it under the same terms as Perl itself.