RE: 05gzsetp.t and initial 'ver' in test output
[p5sagit/p5-mst-13.2.git] / ext / Compress / Zlib / Zlib.pm
CommitLineData
f4c6fd49 1# File : Zlib.pm
2# Author : Paul Marquess
3# Created : 30 January 2005
4# Version : 1.34
5#
6# Copyright (c) 1995-2005 Paul Marquess. All rights reserved.
7# This program is free software; you can redistribute it and/or
8# modify it under the same terms as Perl itself.
9#
10
11package Compress::Zlib;
12
13require 5.004 ;
14require Exporter;
15require DynaLoader;
16use AutoLoader;
17use Carp ;
18use IO::Handle ;
19
20use strict ;
8aa25532 21use warnings ;
22our ($VERSION, @ISA, @EXPORT, $AUTOLOAD);
23our ($deflateDefault, $deflateParamsDefault, $inflateDefault);
f4c6fd49 24
213b85e9 25$VERSION = "1.34_01" ;
f4c6fd49 26
27@ISA = qw(Exporter DynaLoader);
28# Items to export into callers namespace by default. Note: do not export
29# names by default without a very good reason. Use EXPORT_OK instead.
30# Do not simply export all your public functions/methods/constants.
31@EXPORT = qw(
32 deflateInit
33 inflateInit
34
35 compress
36 uncompress
37
38 gzip gunzip
39
40 gzopen
41 $gzerrno
42
43 adler32
44 crc32
45
46 ZLIB_VERSION
47
48 DEF_WBITS
49 OS_CODE
50
51 MAX_MEM_LEVEL
52 MAX_WBITS
53
54 Z_ASCII
55 Z_BEST_COMPRESSION
56 Z_BEST_SPEED
57 Z_BINARY
58 Z_BUF_ERROR
59 Z_DATA_ERROR
60 Z_DEFAULT_COMPRESSION
61 Z_DEFAULT_STRATEGY
62 Z_DEFLATED
63 Z_ERRNO
64 Z_FILTERED
65 Z_FINISH
66 Z_FULL_FLUSH
67 Z_HUFFMAN_ONLY
68 Z_MEM_ERROR
69 Z_NEED_DICT
70 Z_NO_COMPRESSION
71 Z_NO_FLUSH
72 Z_NULL
73 Z_OK
74 Z_PARTIAL_FLUSH
75 Z_STREAM_END
76 Z_STREAM_ERROR
77 Z_SYNC_FLUSH
78 Z_UNKNOWN
79 Z_VERSION_ERROR
80);
81
82
83
84sub AUTOLOAD {
85 my($constname);
86 ($constname = $AUTOLOAD) =~ s/.*:://;
87 my ($error, $val) = constant($constname);
88 Carp::croak $error if $error;
89 no strict 'refs';
90 *{$AUTOLOAD} = sub { $val };
91 goto &{$AUTOLOAD};
92}
93
94bootstrap Compress::Zlib $VERSION ;
95
96# Preloaded methods go here.
97
98sub isaFilehandle($)
99{
100 my $fh = shift ;
101
102 return ((UNIVERSAL::isa($fh,'GLOB') or UNIVERSAL::isa(\$fh,'GLOB'))
103 and defined fileno($fh) )
104
105}
106
107sub isaFilename($)
108{
109 my $name = shift ;
110
111 return (! ref $name and UNIVERSAL::isa(\$name, 'SCALAR')) ;
112}
113
114sub gzopen($$)
115{
116 my ($file, $mode) = @_ ;
117
118 if (isaFilehandle $file) {
119 IO::Handle::flush($file) ;
120 my $offset = tell($file) ;
121 gzdopen_(fileno($file), $mode, $offset) ;
122 }
123 elsif (isaFilename $file) {
124 gzopen_($file, $mode)
125 }
126 else {
127 croak "gzopen: file parameter is not a filehandle or filename"
128 }
129}
130
131sub ParseParameters($@)
132{
133 my ($default, @rest) = @_ ;
134 my (%got) = %$default ;
135 my (@Bad) ;
136 my ($key, $value) ;
137 my $sub = (caller(1))[3] ;
138 my %options = () ;
139
140 # allow the options to be passed as a hash reference or
141 # as the complete hash.
142 if (@rest == 1) {
143
144 croak "$sub: parameter is not a reference to a hash"
145 if ref $rest[0] ne "HASH" ;
146
147 %options = %{ $rest[0] } ;
148 }
149 elsif (@rest >= 2) {
150 my $count = @rest;
151 croak "$sub: Expected even number of parameters, got $count"
152 if @rest % 2 != 0 ;
153 %options = @rest ;
154 }
155
156 while (($key, $value) = each %options)
157 {
158 $key =~ s/^-// ;
159
160 if (exists $default->{$key})
161 { $got{$key} = $value }
162 else
163 { push (@Bad, $key) }
164 }
165
166 if (@Bad) {
167 my ($bad) = join(", ", @Bad) ;
168 croak "unknown key value(s) @Bad" ;
169 }
170
171 return \%got ;
172}
173
174$deflateDefault = {
175 'Level' => Z_DEFAULT_COMPRESSION(),
176 'Method' => Z_DEFLATED(),
177 'WindowBits' => MAX_WBITS(),
178 'MemLevel' => MAX_MEM_LEVEL(),
179 'Strategy' => Z_DEFAULT_STRATEGY(),
180 'Bufsize' => 4096,
181 'Dictionary' => "",
182 } ;
183
184$deflateParamsDefault = {
185 'Level' => undef,
186 'Strategy' => undef,
187 'Bufsize' => undef,
188 } ;
189
190$inflateDefault = {
191 'WindowBits' => MAX_WBITS(),
192 'Bufsize' => 4096,
193 'Dictionary' => "",
194 } ;
195
196
197sub deflateInit(@)
198{
199 my ($got) = ParseParameters($deflateDefault, @_) ;
8aa25532 200 no warnings;
f4c6fd49 201 croak "deflateInit: Bufsize must be >= 1, you specified $got->{Bufsize}"
202 unless $got->{Bufsize} >= 1;
203 _deflateInit($got->{Level}, $got->{Method}, $got->{WindowBits},
204 $got->{MemLevel}, $got->{Strategy}, $got->{Bufsize},
205 $got->{Dictionary}) ;
206
207}
208
209sub inflateInit(@)
210{
211 my ($got) = ParseParameters($inflateDefault, @_) ;
8aa25532 212 no warnings;
f4c6fd49 213 croak "inflateInit: Bufsize must be >= 1, you specified $got->{Bufsize}"
214 unless $got->{Bufsize} >= 1;
215 _inflateInit($got->{WindowBits}, $got->{Bufsize}, $got->{Dictionary});
216
217}
218
219sub Compress::Zlib::deflateStream::deflateParams
220{
221 my $self = shift ;
222 my ($got) = ParseParameters($deflateParamsDefault, @_) ;
223 croak "deflateParams needs Level and/or Strategy"
224 unless defined $got->{Level} || defined $got->{Strategy};
8aa25532 225 no warnings;
f4c6fd49 226 croak "deflateParams: Bufsize must be >= 1, you specified $got->{Bufsize}"
227 unless !defined $got->{Bufsize} || $got->{Bufsize} >= 1;
228
229 my $flags = 0;
230 if (defined $got->{Level})
231 { $flags |= 1 }
232 else
233 { $got->{Level} = 0 }
234
235 if (defined $got->{Strategy})
236 { $flags |= 2 }
237 else
238 { $got->{Strategy} = 0 }
239
240 $got->{Bufsize} = 0
241 if !defined $got->{Bufsize};
242
243 $self->_deflateParams($flags, $got->{Level}, $got->{Strategy},
244 $got->{Bufsize});
245
246}
247
248sub compress($;$)
249{
250 my ($x, $output, $out, $err, $in) ;
251
252 if (ref $_[0] ) {
253 $in = $_[0] ;
254 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
255 }
256 else {
257 $in = \$_[0] ;
258 }
259
260 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
261
262
263 if ( (($x, $err) = deflateInit(Level => $level))[1] == Z_OK()) {
264
265 ($output, $err) = $x->deflate($in) ;
266 return undef unless $err == Z_OK() ;
267
268 ($out, $err) = $x->flush() ;
269 return undef unless $err == Z_OK() ;
270
271 return ($output . $out) ;
272
273 }
274
275 return undef ;
276}
277
278
279sub uncompress($)
280{
281 my ($x, $output, $err, $in) ;
282
283 if (ref $_[0] ) {
284 $in = $_[0] ;
285 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
286 }
287 else {
288 $in = \$_[0] ;
289 }
290
291 if ( (($x, $err) = inflateInit())[1] == Z_OK()) {
292
293 ($output, $err) = $x->__unc_inflate($in) ;
294 return undef unless $err == Z_STREAM_END() ;
295
296 return $output ;
297 }
298
299 return undef ;
300}
301
302
303# Constants
304use constant MAGIC1 => 0x1f ;
305use constant MAGIC2 => 0x8b ;
306use constant OSCODE => 3 ;
307
308use constant FTEXT => 1 ;
309use constant FHCRC => 2 ;
310use constant FEXTRA => 4 ;
311use constant FNAME => 8 ;
312use constant FCOMMENT => 16 ;
313use constant NULL => pack("C", 0) ;
314use constant RESERVED => 0xE0 ;
315
316use constant MIN_HDR_SIZE => 10 ; # minimum gzip header size
317
318sub memGzip($)
319{
320 my $x = deflateInit(
321 -Level => Z_BEST_COMPRESSION(),
322 -WindowBits => - MAX_WBITS(),
323 )
324 or return undef ;
325
326 # write a minimal gzip header
327 my(@m);
328 push @m, pack("C" . MIN_HDR_SIZE,
329 MAGIC1, MAGIC2, Z_DEFLATED(), 0,0,0,0,0,0, OSCODE) ;
330
331 # if the deflation buffer isn't a reference, make it one
332 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
333
334 my ($output, $status) = $x->deflate($string) ;
335 push @m, $output ;
336 $status == Z_OK()
337 or return undef ;
338
339 ($output, $status) = $x->flush() ;
340 push @m, $output ;
341 $status == Z_OK()
342 or return undef ;
343
344 push @m, pack("V V", crc32($string), $x->total_in());
345
346 return join "", @m;
347}
348
349sub _removeGzipHeader($)
350{
351 my $string = shift ;
352
353 return Z_DATA_ERROR()
354 if length($$string) < MIN_HDR_SIZE ;
355
356 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
357 unpack ('CCCCVCC', $$string);
358
359 return Z_DATA_ERROR()
360 unless $magic1 == MAGIC1 and $magic2 == MAGIC2 and
361 $method == Z_DEFLATED() and !($flags & RESERVED()) ;
362 substr($$string, 0, MIN_HDR_SIZE) = '' ;
363
364 # skip extra field
365 if ($flags & FEXTRA)
366 {
367 return Z_DATA_ERROR()
368 if length($$string) < 2 ;
369
370 my ($extra_len) = unpack ('v', $$string);
371 $extra_len += 2;
372 return Z_DATA_ERROR()
373 if length($$string) < $extra_len ;
374
375 substr($$string, 0, $extra_len) = '';
376 }
377
378 # skip orig name
379 if ($flags & FNAME)
380 {
381 my $name_end = index ($$string, NULL);
382 return Z_DATA_ERROR()
383 if $name_end == -1 ;
384 substr($$string, 0, $name_end + 1) = '';
385 }
386
387 # skip comment
388 if ($flags & FCOMMENT)
389 {
390 my $comment_end = index ($$string, NULL);
391 return Z_DATA_ERROR()
392 if $comment_end == -1 ;
393 substr($$string, 0, $comment_end + 1) = '';
394 }
395
396 # skip header crc
397 if ($flags & FHCRC)
398 {
399 return Z_DATA_ERROR()
400 if length ($$string) < 2 ;
401 substr($$string, 0, 2) = '';
402 }
403
404 return Z_OK();
405}
406
407
408sub memGunzip($)
409{
410 # if the buffer isn't a reference, make it one
411 my $string = (ref $_[0] ? $_[0] : \$_[0]);
412
413 _removeGzipHeader($string) == Z_OK()
414 or return undef;
415
416 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
417 my $x = inflateInit( -WindowBits => - MAX_WBITS(),
418 -Bufsize => $bufsize)
419 or return undef;
420 my ($output, $status) = $x->inflate($string);
421 return undef
422 unless $status == Z_STREAM_END();
423
424 if (length $$string >= 8)
425 {
426 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
427 substr($$string, 0, 8) = '';
428 return undef
429 unless $len == length($output) and
430 $crc == crc32($output);
431 }
432 else
433 {
434 $$string = '';
435 }
436
437 return $output;
438}
439
440# Autoload methods go after __END__, and are processed by the autosplit program.
441
4421;
443__END__
444
445=cut
446
447=head1 NAME
448
449Compress::Zlib - Interface to zlib compression library
450
451=head1 SYNOPSIS
452
453 use Compress::Zlib ;
454
455 ($d, $status) = deflateInit( [OPT] ) ;
456 ($out, $status) = $d->deflate($buffer) ;
457 $status = $d->deflateParams([OPT]) ;
458 ($out, $status) = $d->flush() ;
459 $d->dict_adler() ;
460 $d->total_in() ;
461 $d->total_out() ;
462 $d->msg() ;
463
464 ($i, $status) = inflateInit( [OPT] ) ;
465 ($out, $status) = $i->inflate($buffer) ;
466 $status = $i->inflateSync($buffer) ;
467 $i->dict_adler() ;
468 $i->total_in() ;
469 $i->total_out() ;
470 $i->msg() ;
471
472 $dest = compress($source, [$level]) ;
473 $dest = uncompress($source) ;
474
475 $gz = gzopen($filename or filehandle, $mode) ;
476 $bytesread = $gz->gzread($buffer [,$size]) ;
477 $bytesread = $gz->gzreadline($line) ;
478 $byteswritten = $gz->gzwrite($buffer) ;
479 $status = $gz->gzflush($flush) ;
480 $status = $gz->gzclose() ;
481 $status = $gz->gzeof() ;
482 $status = $gz->gzsetparams($level, $strategy) ;
483 $errstring = $gz->gzerror() ;
484 $gzerrno
485
486 $dest = Compress::Zlib::memGzip($buffer) ;
487 $dest = Compress::Zlib::memGunzip($buffer) ;
488
489 $crc = adler32($buffer [,$crc]) ;
490 $crc = crc32($buffer [,$crc]) ;
491
492 ZLIB_VERSION
493
494=head1 DESCRIPTION
495
496The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
497compression library (see L</AUTHOR> for details about where to get
498I<zlib>). Most of the functionality provided by I<zlib> is available
499in I<Compress::Zlib>.
500
501The module can be split into two general areas of functionality, namely
502in-memory compression/decompression and read/write access to I<gzip>
503files. Each of these areas will be discussed separately below.
504
505=head1 DEFLATE
506
507The interface I<Compress::Zlib> provides to the in-memory I<deflate>
508(and I<inflate>) functions has been modified to fit into a Perl model.
509
510The main difference is that for both inflation and deflation, the Perl
511interface will I<always> consume the complete input buffer before
512returning. Also the output buffer returned will be automatically grown
513to fit the amount of output available.
514
515Here is a definition of the interface available:
516
517
518=head2 B<($d, $status) = deflateInit( [OPT] )>
519
520Initialises a deflation stream.
521
522It combines the features of the I<zlib> functions B<deflateInit>,
523B<deflateInit2> and B<deflateSetDictionary>.
524
525If successful, it will return the initialised deflation stream, B<$d>
526and B<$status> of C<Z_OK> in a list context. In scalar context it
527returns the deflation stream, B<$d>, only.
528
529If not successful, the returned deflation stream (B<$d>) will be
530I<undef> and B<$status> will hold the exact I<zlib> error code.
531
532The function optionally takes a number of named options specified as
533C<-Name=E<gt>value> pairs. This allows individual options to be
534tailored without having to specify them all in the parameter list.
535
536For backward compatibility, it is also possible to pass the parameters
537as a reference to a hash containing the name=>value pairs.
538
539The function takes one optional parameter, a reference to a hash. The
540contents of the hash allow the deflation interface to be tailored.
541
542Here is a list of the valid options:
543
544=over 5
545
546=item B<-Level>
547
548Defines the compression level. Valid values are 0 through 9,
549C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
550C<Z_DEFAULT_COMPRESSION>.
551
552The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
553
554=item B<-Method>
555
556Defines the compression method. The only valid value at present (and
557the default) is C<-Method =E<gt>Z_DEFLATED>.
558
559=item B<-WindowBits>
560
561For a definition of the meaning and valid values for B<WindowBits>
562refer to the I<zlib> documentation for I<deflateInit2>.
563
564Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
565
566=item B<-MemLevel>
567
568For a definition of the meaning and valid values for B<MemLevel>
569refer to the I<zlib> documentation for I<deflateInit2>.
570
571Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
572
573=item B<-Strategy>
574
575Defines the strategy used to tune the compression. The valid values are
576C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
577
578The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
579
580=item B<-Dictionary>
581
582When a dictionary is specified I<Compress::Zlib> will automatically
583call B<deflateSetDictionary> directly after calling B<deflateInit>. The
584Adler32 value for the dictionary can be obtained by calling the method
585C<$d->dict_adler()>.
586
587The default is no dictionary.
588
589=item B<-Bufsize>
590
591Sets the initial size for the deflation buffer. If the buffer has to be
592reallocated to increase the size, it will grow in increments of
593B<Bufsize>.
594
595The default is 4096.
596
597=back
598
599Here is an example of using the B<deflateInit> optional parameter list
600to override the default buffer size and compression level. All other
601options will take their default values.
602
603 deflateInit( -Bufsize => 300,
604 -Level => Z_BEST_SPEED ) ;
605
606
607=head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
608
609
610Deflates the contents of B<$buffer>. The buffer can either be a scalar
611or a scalar reference. When finished, B<$buffer> will be
612completely processed (assuming there were no errors). If the deflation
613was successful it returns the deflated output, B<$out>, and a status
614value, B<$status>, of C<Z_OK>.
615
616On error, B<$out> will be I<undef> and B<$status> will contain the
617I<zlib> error code.
618
619In a scalar context B<deflate> will return B<$out> only.
620
621As with the I<deflate> function in I<zlib>, it is not necessarily the
622case that any output will be produced by this method. So don't rely on
623the fact that B<$out> is empty for an error test.
624
625
626=head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
627
628Typically used to finish the deflation. Any pending output will be
629returned via B<$out>.
630B<$status> will have a value C<Z_OK> if successful.
631
632In a scalar context B<flush> will return B<$out> only.
633
634Note that flushing can seriously degrade the compression ratio, so it
635should only be used to terminate a decompression (using C<Z_FINISH>) or
636when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
637
638By default the C<flush_type> used is C<Z_FINISH>. Other valid values
639for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
640and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
641C<flush_type> parameter if you fully understand the implications of
642what it does. See the C<zlib> documentation for details.
643
644=head2 B<$status = $d-E<gt>deflateParams([OPT])>
645
646Change settings for the deflate stream C<$d>.
647
648The list of the valid options is shown below. Options not specified
649will remain unchanged.
650
651=over 5
652
653=item B<-Level>
654
655Defines the compression level. Valid values are 0 through 9,
656C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
657C<Z_DEFAULT_COMPRESSION>.
658
659=item B<-Strategy>
660
661Defines the strategy used to tune the compression. The valid values are
662C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
663
664=back
665
666=head2 B<$d-E<gt>dict_adler()>
667
668Returns the adler32 value for the dictionary.
669
670=head2 B<$d-E<gt>msg()>
671
672Returns the last error message generated by zlib.
673
674=head2 B<$d-E<gt>total_in()>
675
676Returns the total number of bytes uncompressed bytes input to deflate.
677
678=head2 B<$d-E<gt>total_out()>
679
680Returns the total number of compressed bytes output from deflate.
681
682=head2 Example
683
684
685Here is a trivial example of using B<deflate>. It simply reads standard
686input, deflates it and writes it to standard output.
687
688 use strict ;
689 use warnings ;
690
691 use Compress::Zlib ;
692
693 binmode STDIN;
694 binmode STDOUT;
695 my $x = deflateInit()
696 or die "Cannot create a deflation stream\n" ;
697
698 my ($output, $status) ;
699 while (<>)
700 {
701 ($output, $status) = $x->deflate($_) ;
702
703 $status == Z_OK
704 or die "deflation failed\n" ;
705
706 print $output ;
707 }
708
709 ($output, $status) = $x->flush() ;
710
711 $status == Z_OK
712 or die "deflation failed\n" ;
713
714 print $output ;
715
716=head1 INFLATE
717
718Here is a definition of the interface:
719
720
721=head2 B<($i, $status) = inflateInit()>
722
723Initialises an inflation stream.
724
725In a list context it returns the inflation stream, B<$i>, and the
726I<zlib> status code (B<$status>). In a scalar context it returns the
727inflation stream only.
728
729If successful, B<$i> will hold the inflation stream and B<$status> will
730be C<Z_OK>.
731
732If not successful, B<$i> will be I<undef> and B<$status> will hold the
733I<zlib> error code.
734
735The function optionally takes a number of named options specified as
736C<-Name=E<gt>value> pairs. This allows individual options to be
737tailored without having to specify them all in the parameter list.
738
739For backward compatibility, it is also possible to pass the parameters
740as a reference to a hash containing the name=>value pairs.
741
742The function takes one optional parameter, a reference to a hash. The
743contents of the hash allow the deflation interface to be tailored.
744
745Here is a list of the valid options:
746
747=over 5
748
749=item B<-WindowBits>
750
751For a definition of the meaning and valid values for B<WindowBits>
752refer to the I<zlib> documentation for I<inflateInit2>.
753
754Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
755
756=item B<-Bufsize>
757
758Sets the initial size for the inflation buffer. If the buffer has to be
759reallocated to increase the size, it will grow in increments of
760B<Bufsize>.
761
762Default is 4096.
763
764=item B<-Dictionary>
765
766The default is no dictionary.
767
768=back
769
770Here is an example of using the B<inflateInit> optional parameter to
771override the default buffer size.
772
773 inflateInit( -Bufsize => 300 ) ;
774
775=head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
776
777Inflates the complete contents of B<$buffer>. The buffer can either be
778a scalar or a scalar reference.
779
780Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
781compressed data has been successfully reached.
782If not successful, B<$out> will be I<undef> and B<$status> will hold
783the I<zlib> error code.
784
785The C<$buffer> parameter is modified by C<inflate>. On completion it
786will contain what remains of the input buffer after inflation. This
787means that C<$buffer> will be an empty string when the return status is
788C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
789parameter will contains what (if anything) was stored in the input
790buffer after the deflated data stream.
791
792This feature is useful when processing a file format that encapsulates
793a compressed data stream (e.g. gzip, zip).
794
795=head2 B<$status = $i-E<gt>inflateSync($buffer)>
796
797Scans C<$buffer> until it reaches either a I<full flush point> or the
798end of the buffer.
799
800If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
801will be have all data up to the flush point removed. This can then be
802passed to the C<deflate> method.
803
804Any other return code means that a flush point was not found. If more
805data is available, C<inflateSync> can be called repeatedly with more
806compressed data until the flush point is found.
807
808
809=head2 B<$i-E<gt>dict_adler()>
810
811Returns the adler32 value for the dictionary.
812
813=head2 B<$i-E<gt>msg()>
814
815Returns the last error message generated by zlib.
816
817=head2 B<$i-E<gt>total_in()>
818
819Returns the total number of bytes compressed bytes input to inflate.
820
821=head2 B<$i-E<gt>total_out()>
822
823Returns the total number of uncompressed bytes output from inflate.
824
825=head2 Example
826
827Here is an example of using B<inflate>.
828
829 use strict ;
830 use warnings ;
831
832 use Compress::Zlib ;
833
834 my $x = inflateInit()
835 or die "Cannot create a inflation stream\n" ;
836
837 my $input = '' ;
838 binmode STDIN;
839 binmode STDOUT;
840
841 my ($output, $status) ;
842 while (read(STDIN, $input, 4096))
843 {
844 ($output, $status) = $x->inflate(\$input) ;
845
846 print $output
847 if $status == Z_OK or $status == Z_STREAM_END ;
848
849 last if $status != Z_OK ;
850 }
851
852 die "inflation failed\n"
853 unless $status == Z_STREAM_END ;
854
855=head1 COMPRESS/UNCOMPRESS
856
857Two high-level functions are provided by I<zlib> to perform in-memory
bdd93743 858compression/uncompression of RFC1950 data streams. They are called
859B<compress> and B<uncompress>.
860
861The two Perl subs defined below provide the equivalent
862functionality.
f4c6fd49 863
864=over 5
865
866=item B<$dest = compress($source [, $level] ) ;>
867
868Compresses B<$source>. If successful it returns the
869compressed data. Otherwise it returns I<undef>.
870
871The source buffer can either be a scalar or a scalar reference.
872
873The B<$level> paramter defines the compression level. Valid values are
8740 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
875C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
876If B<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
877
878
879=item B<$dest = uncompress($source) ;>
880
881Uncompresses B<$source>. If successful it returns the uncompressed
882data. Otherwise it returns I<undef>.
883
884The source buffer can either be a scalar or a scalar reference.
885
886=back
887
bdd93743 888Please note: the two functions defined above are I<not> compatible with
889the Unix commands of the same name.
890
f4c6fd49 891=head1 GZIP INTERFACE
892
893A number of functions are supplied in I<zlib> for reading and writing
894I<gzip> files. This module provides an interface to most of them. In
895general the interface provided by this module operates identically to
896the functions provided by I<zlib>. Any differences are explained
897below.
898
899=over 5
900
901=item B<$gz = gzopen(filename or filehandle, mode)>
902
903This function operates identically to the I<zlib> equivalent except
904that it returns an object which is used to access the other I<gzip>
905methods.
906
907As with the I<zlib> equivalent, the B<mode> parameter is used to
908specify both whether the file is opened for reading or writing and to
909optionally specify a a compression level. Refer to the I<zlib>
910documentation for the exact format of the B<mode> parameter.
911
912If a reference to an open filehandle is passed in place of the
913filename, gzdopen will be called behind the scenes. The third example
914at the end of this section, I<gzstream>, uses this feature.
915
916=item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
917
918Reads B<$size> bytes from the compressed file into B<$buffer>. If
919B<$size> is not specified, it will default to 4096. If the scalar
920B<$buffer> is not large enough, it will be extended automatically.
921
922Returns the number of bytes actually read. On EOF it returns 0 and in
923the case of an error, -1.
924
925=item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
926
927Reads the next line from the compressed file into B<$line>.
928
929Returns the number of bytes actually read. On EOF it returns 0 and in
930the case of an error, -1.
931
932It is legal to intermix calls to B<gzread> and B<gzreadline>.
933
934At this time B<gzreadline> ignores the variable C<$/>
935(C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use). The
936end of a line is denoted by the C character C<'\n'>.
937
938=item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
939
940Writes the contents of B<$buffer> to the compressed file. Returns the
941number of bytes actually written, or 0 on error.
942
943=item B<$status = $gz-E<gt>gzflush($flush) ;>
944
945Flushes all pending output to the compressed file.
946Works identically to the I<zlib> function it interfaces to. Note that
947the use of B<gzflush> can degrade compression.
948
949Returns C<Z_OK> if B<$flush> is C<Z_FINISH> and all output could be
950flushed. Otherwise the zlib error code is returned.
951
952Refer to the I<zlib> documentation for the valid values of B<$flush>.
953
954=item B<$status = $gz-E<gt>gzeof() ;>
955
956Returns 1 if the end of file has been detected while reading the input
957file, otherwise returns 0.
958
959=item B<$gz-E<gt>gzclose>
960
961Closes the compressed file. Any pending data is flushed to the file
962before it is closed.
963
964=item B<$gz-E<gt>gzsetparams($level, $strategy>
965
966Change settings for the deflate stream C<$gz>.
967
968The list of the valid options is shown below. Options not specified
969will remain unchanged.
970
971Note: This method is only available if you are running zlib 1.0.6 or better.
972
973=over 5
974
975=item B<$level>
976
977Defines the compression level. Valid values are 0 through 9,
978C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
979C<Z_DEFAULT_COMPRESSION>.
980
981=item B<$strategy>
982
983Defines the strategy used to tune the compression. The valid values are
984C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
985
986=back
987
988=item B<$gz-E<gt>gzerror>
989
990Returns the I<zlib> error message or number for the last operation
991associated with B<$gz>. The return value will be the I<zlib> error
992number when used in a numeric context and the I<zlib> error message
993when used in a string context. The I<zlib> error number constants,
994shown below, are available for use.
995
996 Z_OK
997 Z_STREAM_END
998 Z_ERRNO
999 Z_STREAM_ERROR
1000 Z_DATA_ERROR
1001 Z_MEM_ERROR
1002 Z_BUF_ERROR
1003
1004=item B<$gzerrno>
1005
1006The B<$gzerrno> scalar holds the error code associated with the most
1007recent I<gzip> routine. Note that unlike B<gzerror()>, the error is
1008I<not> associated with a particular file.
1009
1010As with B<gzerror()> it returns an error number in numeric context and
1011an error message in string context. Unlike B<gzerror()> though, the
1012error message will correspond to the I<zlib> message when the error is
1013associated with I<zlib> itself, or the UNIX error message when it is
1014not (i.e. I<zlib> returned C<Z_ERRORNO>).
1015
1016As there is an overlap between the error numbers used by I<zlib> and
1017UNIX, B<$gzerrno> should only be used to check for the presence of
1018I<an> error in numeric context. Use B<gzerror()> to check for specific
1019I<zlib> errors. The I<gzcat> example below shows how the variable can
1020be used safely.
1021
1022=back
1023
1024
1025=head2 Examples
1026
1027Here is an example script which uses the interface. It implements a
1028I<gzcat> function.
1029
1030 use strict ;
1031 use warnings ;
1032
1033 use Compress::Zlib ;
1034
1035 die "Usage: gzcat file...\n"
1036 unless @ARGV ;
1037
1038 my $file ;
1039
1040 foreach $file (@ARGV) {
1041 my $buffer ;
1042
1043 my $gz = gzopen($file, "rb")
1044 or die "Cannot open $file: $gzerrno\n" ;
1045
1046 print $buffer while $gz->gzread($buffer) > 0 ;
1047
1048 die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
1049 if $gzerrno != Z_STREAM_END ;
1050
1051 $gz->gzclose() ;
1052 }
1053
1054Below is a script which makes use of B<gzreadline>. It implements a
1055very simple I<grep> like script.
1056
1057 use strict ;
1058 use warnings ;
1059
1060 use Compress::Zlib ;
1061
1062 die "Usage: gzgrep pattern file...\n"
1063 unless @ARGV >= 2;
1064
1065 my $pattern = shift ;
1066
1067 my $file ;
1068
1069 foreach $file (@ARGV) {
1070 my $gz = gzopen($file, "rb")
1071 or die "Cannot open $file: $gzerrno\n" ;
1072
1073 while ($gz->gzreadline($_) > 0) {
1074 print if /$pattern/ ;
1075 }
1076
1077 die "Error reading from $file: $gzerrno\n"
1078 if $gzerrno != Z_STREAM_END ;
1079
1080 $gz->gzclose() ;
1081 }
1082
1083This script, I<gzstream>, does the opposite of the I<gzcat> script
1084above. It reads from standard input and writes a gzip file to standard
1085output.
1086
1087 use strict ;
1088 use warnings ;
1089
1090 use Compress::Zlib ;
1091
1092 binmode STDOUT; # gzopen only sets it on the fd
1093
1094 my $gz = gzopen(\*STDOUT, "wb")
1095 or die "Cannot open stdout: $gzerrno\n" ;
1096
1097 while (<>) {
1098 $gz->gzwrite($_)
1099 or die "error writing: $gzerrno\n" ;
1100 }
1101
1102 $gz->gzclose ;
1103
1104=head2 Compress::Zlib::memGzip
1105
1106This function is used to create an in-memory gzip file.
1107It creates a minimal gzip header.
1108
1109 $dest = Compress::Zlib::memGzip($buffer) ;
1110
1111If successful, it returns the in-memory gzip file, otherwise it returns
1112undef.
1113
1114The buffer parameter can either be a scalar or a scalar reference.
1115
1116=head2 Compress::Zlib::memGunzip
1117
1118This function is used to uncompress an in-memory gzip file.
1119
1120 $dest = Compress::Zlib::memGunzip($buffer) ;
1121
1122If successful, it returns the uncompressed gzip file, otherwise it
1123returns undef.
1124
1125The buffer parameter can either be a scalar or a scalar reference. The
1126contents of the buffer parameter are destroyed after calling this
1127function.
1128
1129=head1 CHECKSUM FUNCTIONS
1130
1131Two functions are provided by I<zlib> to calculate a checksum. For the
1132Perl interface, the order of the two parameters in both functions has
1133been reversed. This allows both running checksums and one off
1134calculations to be done.
1135
1136 $crc = adler32($buffer [,$crc]) ;
1137 $crc = crc32($buffer [,$crc]) ;
1138
1139The buffer parameters can either be a scalar or a scalar reference.
1140
1141If the $crc parameters is C<undef>, the crc value will be reset.
1142
1143=head1 ACCESSING ZIP FILES
1144
1145Although it is possible to use this module to access .zip files, there
1146is a module on CPAN that will do all the hard work for you. Check out
1147
1148 http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz
1149
1150Assuming you don't want to use this module to access zip files there
1151are a number of undocumented features in the zlib library you need to
1152be aware of.
1153
1154=over 5
1155
1156=item 1.
1157
1158When calling B<inflateInit> or B<deflateInit> the B<WindowBits> parameter
1159must be set to C<-MAX_WBITS>. This disables the creation of the zlib
1160header.
1161
1162=item 2.
1163
1164The zlib function B<inflate>, and so the B<inflate> method supplied in
1165this module, assume that there is at least one trailing byte after the
1166compressed data stream. Normally this isn't a problem because both
1167the gzip and zip file formats will guarantee that there is data directly
1168after the compressed data stream.
1169
1170=back
1171
1172=head1 CONSTANTS
1173
1174All the I<zlib> constants are automatically imported when you make use
1175of I<Compress::Zlib>.
1176
1177=head1 AUTHOR
1178
1179The I<Compress::Zlib> module was written by Paul Marquess,
1180F<pmqs@cpan.org>. The latest copy of the module can be
1181found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
1182
1183The primary site for the I<zlib> compression library is
1184F<http://www.zlib.org>.
1185
1186=head1 MODIFICATION HISTORY
1187
1188See the Changes file.