Compress::Zlib becomes zlib agnostic
[p5sagit/p5-mst-13.2.git] / ext / Compress / Zlib / Zlib.pm
1
2 package Compress::Zlib;
3
4 require 5.004 ;
5 require Exporter;
6 use AutoLoader;
7 use Carp ;
8 use IO::Handle ;
9 use Scalar::Util qw(dualvar);
10
11 use Compress::Zlib::Common ;
12 use Compress::Zlib::ParseParameters;
13
14 use strict ;
15 use warnings ;
16 use bytes ;
17 our ($VERSION, $XS_VERSION, @ISA, @EXPORT, $AUTOLOAD);
18
19 $VERSION = '2.000_07';
20 $XS_VERSION = $VERSION; 
21 $VERSION = eval $VERSION;
22
23 @ISA = qw(Exporter);
24 # Items to export into callers namespace by default. Note: do not export
25 # names by default without a very good reason. Use EXPORT_OK instead.
26 # Do not simply export all your public functions/methods/constants.
27 @EXPORT = qw(
28         deflateInit inflateInit
29
30         compress uncompress
31
32         gzopen $gzerrno
33
34         adler32 crc32
35
36         ZLIB_VERSION
37         ZLIB_VERNUM
38
39         DEF_WBITS
40         OS_CODE
41
42         MAX_MEM_LEVEL
43         MAX_WBITS
44
45         Z_ASCII
46         Z_BEST_COMPRESSION
47         Z_BEST_SPEED
48         Z_BINARY
49         Z_BLOCK
50         Z_BUF_ERROR
51         Z_DATA_ERROR
52         Z_DEFAULT_COMPRESSION
53         Z_DEFAULT_STRATEGY
54         Z_DEFLATED
55         Z_ERRNO
56         Z_FILTERED
57         Z_FIXED
58         Z_FINISH
59         Z_FULL_FLUSH
60         Z_HUFFMAN_ONLY
61         Z_MEM_ERROR
62         Z_NEED_DICT
63         Z_NO_COMPRESSION
64         Z_NO_FLUSH
65         Z_NULL
66         Z_OK
67         Z_PARTIAL_FLUSH
68         Z_RLE
69         Z_STREAM_END
70         Z_STREAM_ERROR
71         Z_SYNC_FLUSH
72         Z_UNKNOWN
73         Z_VERSION_ERROR
74 );
75
76
77 sub AUTOLOAD {
78     my($constname);
79     ($constname = $AUTOLOAD) =~ s/.*:://;
80     my ($error, $val) = constant($constname);
81     Carp::croak $error if $error;
82     no strict 'refs';
83     *{$AUTOLOAD} = sub { $val };
84     goto &{$AUTOLOAD};
85 }
86
87 use constant FLAG_APPEND             => 1 ;
88 use constant FLAG_CRC                => 2 ;
89 use constant FLAG_ADLER              => 4 ;
90 use constant FLAG_CONSUME_INPUT      => 8 ;
91
92 eval {
93     require XSLoader;
94     XSLoader::load('Compress::Zlib', $XS_VERSION);
95     1;
96
97 or do {
98     require DynaLoader;
99     local @ISA = qw(DynaLoader);
100     bootstrap Compress::Zlib $XS_VERSION ; 
101 };
102  
103 # Preloaded methods go here.
104
105 require IO::Compress::Gzip;
106 require IO::Uncompress::Gunzip;
107
108 our (@my_z_errmsg);
109
110 @my_z_errmsg = (
111     "need dictionary",     # Z_NEED_DICT     2
112     "stream end",          # Z_STREAM_END    1
113     "",                    # Z_OK            0
114     "file error",          # Z_ERRNO        (-1)
115     "stream error",        # Z_STREAM_ERROR (-2)
116     "data error",          # Z_DATA_ERROR   (-3)
117     "insufficient memory", # Z_MEM_ERROR    (-4)
118     "buffer error",        # Z_BUF_ERROR    (-5)
119     "incompatible version",# Z_VERSION_ERROR(-6)
120     );
121
122
123 sub _set_gzerr
124 {
125     my $value = shift ;
126
127     if ($value == 0) {
128         $Compress::Zlib::gzerrno = 0 ;
129     }
130     elsif ($value == Z_ERRNO() || $value > 2) {
131         $Compress::Zlib::gzerrno = $! ;
132     }
133     else {
134         $Compress::Zlib::gzerrno = dualvar($value+0, $my_z_errmsg[2 - $value]);
135     }
136
137     return $value ;
138 }
139
140 sub _save_gzerr
141 {
142     my $gz = shift ;
143     my $test_eof = shift ;
144
145     my $value = $gz->errorNo() || 0 ;
146
147     if ($test_eof) {
148         #my $gz = $self->[0] ;
149         # gzread uses Z_STREAM_END to denote a successful end
150         $value = Z_STREAM_END() if $gz->eof() && $value == 0 ;
151     }
152
153     _set_gzerr($value) ;
154 }
155
156 sub gzopen($$)
157 {
158     my ($file, $mode) = @_ ;
159
160     my $gz ;
161     my %defOpts = (Level    => Z_DEFAULT_COMPRESSION(),
162                    Strategy => Z_DEFAULT_STRATEGY(),
163                   );
164
165     my $writing ;
166     $writing = ! ($mode =~ /r/i) ;
167     $writing = ($mode =~ /[wa]/i) ;
168
169     $defOpts{Level}    = $1               if $mode =~ /(\d)/;
170     $defOpts{Strategy} = Z_FILTERED()     if $mode =~ /f/i;
171     $defOpts{Strategy} = Z_HUFFMAN_ONLY() if $mode =~ /h/i;
172
173     my $infDef = $writing ? 'deflate' : 'inflate';
174     my @params = () ;
175
176     croak "gzopen: file parameter is not a filehandle or filename"
177         unless isaFilehandle $file || isaFilename $file ;
178
179     return undef unless $mode =~ /[rwa]/i ;
180
181     _set_gzerr(0) ;
182
183     if ($writing) {
184         $gz = new IO::Compress::Gzip($file, Minimal => 1, AutoClose => 1, 
185                                      %defOpts) 
186             or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError;
187     }
188     else {
189         $gz = new IO::Uncompress::Gunzip($file, 
190                                          Transparent => 1,
191                                          Append => 0, 
192                                          AutoClose => 1, 
193                                          Strict => 0) 
194             or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
195     }
196
197     return undef
198         if ! defined $gz ;
199
200     bless [$gz, $infDef], 'Compress::Zlib::gzFile';
201 }
202
203 sub Compress::Zlib::gzFile::gzread
204 {
205     my $self = shift ;
206
207     return _set_gzerr(Z_STREAM_ERROR())
208         if $self->[1] ne 'inflate';
209
210     return 0 if $self->gzeof();
211
212     my $gz = $self->[0] ;
213     my $status = $gz->read($_[0], defined $_[1] ? $_[1] : 4096) ; 
214     $_[0] = "" if ! defined $_[0] ;
215     _save_gzerr($gz, 1);
216     return $status ;
217 }
218
219 sub Compress::Zlib::gzFile::gzreadline
220 {
221     my $self = shift ;
222
223     my $gz = $self->[0] ;
224     $_[0] = $gz->getline() ; 
225     _save_gzerr($gz, 1);
226     return defined $_[0] ? length $_[0] : 0 ;
227 }
228
229 sub Compress::Zlib::gzFile::gzwrite
230 {
231     my $self = shift ;
232     my $gz = $self->[0] ;
233
234     return _set_gzerr(Z_STREAM_ERROR())
235         if $self->[1] ne 'deflate';
236
237     my $status = $gz->write($_[0]) ;
238     _save_gzerr($gz);
239     return $status ;
240 }
241
242 sub Compress::Zlib::gzFile::gztell
243 {
244     my $self = shift ;
245     my $gz = $self->[0] ;
246     my $status = $gz->tell() ;
247     _save_gzerr($gz);
248     return $status ;
249 }
250
251 sub Compress::Zlib::gzFile::gzseek
252 {
253     my $self   = shift ;
254     my $offset = shift ;
255     my $whence = shift ;
256
257     my $gz = $self->[0] ;
258     my $status ;
259     eval { $status = $gz->seek($offset, $whence) ; };
260     if ($@)
261     {
262         my $error = $@;
263         $error =~ s/^.*: /gzseek: /;
264         $error =~ s/ at .* line \d+\s*$//;
265         croak $error;
266     }
267     _save_gzerr($gz);
268     return $status ;
269 }
270
271 sub Compress::Zlib::gzFile::gzflush
272 {
273     my $self = shift ;
274     my $f    = shift ;
275
276     my $gz = $self->[0] ;
277     my $status = $gz->flush($f) ;
278     _save_gzerr($gz);
279     return $status ;
280 }
281
282 sub Compress::Zlib::gzFile::gzclose
283 {
284     my $self = shift ;
285     my $gz = $self->[0] ;
286
287     my $status = $gz->close() ;
288     _save_gzerr($gz);
289     return ! $status ;
290 }
291
292 sub Compress::Zlib::gzFile::gzeof
293 {
294     my $self = shift ;
295     my $gz = $self->[0] ;
296
297     return 0
298         if $self->[1] ne 'inflate';
299
300     my $status = $gz->eof() ;
301     _save_gzerr($gz);
302     return $status ;
303 }
304
305 sub Compress::Zlib::gzFile::gzsetparams
306 {
307     my $self = shift ;
308     croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
309         unless @_ eq 2 ;
310
311     my $gz = $self->[0] ;
312     my $level = shift ;
313     my $strategy = shift;
314
315     return _set_gzerr(Z_STREAM_ERROR())
316         if $self->[1] ne 'deflate';
317  
318     my $status = *$gz->{Compress}->deflateParams(-Level   => $level, 
319                                                 -Strategy => $strategy);
320     _save_gzerr($gz);
321     return $status ;
322 }
323
324 sub Compress::Zlib::gzFile::gzerror
325 {
326     my $self = shift ;
327     my $gz = $self->[0] ;
328     
329     return $Compress::Zlib::gzerrno ;
330 }
331
332 sub Compress::Zlib::Deflate::new
333 {
334     my $pkg = shift ;
335     my ($got) = ParseParameters(0,
336             {
337                 'AppendOutput'  => [1, 1, Parse_boolean,  0],
338                 'CRC32'         => [1, 1, Parse_boolean,  0],
339                 'ADLER32'       => [1, 1, Parse_boolean,  0],
340                 'Bufsize'       => [1, 1, Parse_unsigned, 4096],
341  
342                 'Level'         => [1, 1, Parse_signed,   Z_DEFAULT_COMPRESSION()],
343                 'Method'        => [1, 1, Parse_unsigned, Z_DEFLATED()],
344                 'WindowBits'    => [1, 1, Parse_signed,   MAX_WBITS()],
345                 'MemLevel'      => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
346                 'Strategy'      => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
347                 'Dictionary'    => [1, 1, Parse_any,      ""],
348             }, @_) ;
349
350
351     croak "Compress::Zlib::Deflate::new: Bufsize must be >= 1, you specified " . 
352             $got->value('Bufsize')
353         unless $got->value('Bufsize') >= 1;
354
355     my $flags = 0 ;
356     $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
357     $flags |= FLAG_CRC    if $got->value('CRC32') ;
358     $flags |= FLAG_ADLER  if $got->value('ADLER32') ;
359
360     _deflateInit($flags,
361                 $got->value('Level'), 
362                 $got->value('Method'), 
363                 $got->value('WindowBits'), 
364                 $got->value('MemLevel'), 
365                 $got->value('Strategy'), 
366                 $got->value('Bufsize'),
367                 $got->value('Dictionary')) ;
368
369 }
370
371 sub Compress::Zlib::Inflate::new
372 {
373     my $pkg = shift ;
374     my ($got) = ParseParameters(0,
375                     {
376                         'AppendOutput'  => [1, 1, Parse_boolean,  0],
377                         'CRC32'         => [1, 1, Parse_boolean,  0],
378                         'ADLER32'       => [1, 1, Parse_boolean,  0],
379                         'ConsumeInput'  => [1, 1, Parse_boolean,  1],
380                         'Bufsize'       => [1, 1, Parse_unsigned, 4096],
381                  
382                         'WindowBits'    => [1, 1, Parse_signed,   MAX_WBITS()],
383                         'Dictionary'    => [1, 1, Parse_any,      ""],
384             }, @_) ;
385
386
387     croak "Compress::Zlib::Inflate::new: Bufsize must be >= 1, you specified " . 
388             $got->value('Bufsize')
389         unless $got->value('Bufsize') >= 1;
390
391     my $flags = 0 ;
392     $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
393     $flags |= FLAG_CRC    if $got->value('CRC32') ;
394     $flags |= FLAG_ADLER  if $got->value('ADLER32') ;
395     $flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
396
397     _inflateInit($flags, $got->value('WindowBits'), $got->value('Bufsize'), 
398                  $got->value('Dictionary')) ;
399 }
400
401 sub Compress::Zlib::InflateScan::new
402 {
403     my $pkg = shift ;
404     my ($got) = ParseParameters(0,
405                     {
406                         'CRC32'         => [1, 1, Parse_boolean,  0],
407                         'ADLER32'       => [1, 1, Parse_boolean,  0],
408                         'Bufsize'       => [1, 1, Parse_unsigned, 4096],
409                  
410                         'WindowBits'    => [1, 1, Parse_signed,   -MAX_WBITS()],
411                         'Dictionary'    => [1, 1, Parse_any,      ""],
412             }, @_) ;
413
414
415     croak "Compress::Zlib::InflateScan::new: Bufsize must be >= 1, you specified " . 
416             $got->value('Bufsize')
417         unless $got->value('Bufsize') >= 1;
418
419     my $flags = 0 ;
420     #$flags |= FLAG_APPEND if $got->value('AppendOutput') ;
421     $flags |= FLAG_CRC    if $got->value('CRC32') ;
422     $flags |= FLAG_ADLER  if $got->value('ADLER32') ;
423     #$flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
424
425     _inflateScanInit($flags, $got->value('WindowBits'), $got->value('Bufsize'), 
426                  '') ;
427 }
428
429 sub Compress::Zlib::inflateScanStream::createDeflateStream
430 {
431     my $pkg = shift ;
432     my ($got) = ParseParameters(0,
433             {
434                 'AppendOutput'  => [1, 1, Parse_boolean,  0],
435                 'CRC32'         => [1, 1, Parse_boolean,  0],
436                 'ADLER32'       => [1, 1, Parse_boolean,  0],
437                 'Bufsize'       => [1, 1, Parse_unsigned, 4096],
438  
439                 'Level'         => [1, 1, Parse_signed,   Z_DEFAULT_COMPRESSION()],
440                 'Method'        => [1, 1, Parse_unsigned, Z_DEFLATED()],
441                 'WindowBits'    => [1, 1, Parse_signed,   - MAX_WBITS()],
442                 'MemLevel'      => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
443                 'Strategy'      => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
444             }, @_) ;
445
446     croak "Compress::Zlib::InflateScan::createDeflateStream: Bufsize must be >= 1, you specified " . 
447             $got->value('Bufsize')
448         unless $got->value('Bufsize') >= 1;
449
450     my $flags = 0 ;
451     $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
452     $flags |= FLAG_CRC    if $got->value('CRC32') ;
453     $flags |= FLAG_ADLER  if $got->value('ADLER32') ;
454
455     $pkg->_createDeflateStream($flags,
456                 $got->value('Level'), 
457                 $got->value('Method'), 
458                 $got->value('WindowBits'), 
459                 $got->value('MemLevel'), 
460                 $got->value('Strategy'), 
461                 $got->value('Bufsize'),
462                 ) ;
463
464 }
465
466 sub Compress::Zlib::inflateScanStream::inflate
467 {
468     my $self = shift ;
469     my $buffer = $_[1];
470     my $eof = $_[2];
471
472     my $status = $self->scan(@_);
473
474     if ($status == Z_OK() && $_[2]) {
475         my $byte = ' ';
476         
477         $status = $self->scan(\$byte, $_[1]) ;
478     }
479     
480     return $status ;
481 }
482
483 sub Compress::Zlib::deflateStream::deflateParams
484 {
485     my $self = shift ;
486     my ($got) = ParseParameters(0, {
487                 'Level'      => [1, 1, Parse_signed,   undef],
488                 'Strategy'   => [1, 1, Parse_unsigned, undef],
489                 'Bufsize'    => [1, 1, Parse_unsigned, undef],
490                 }, 
491                 @_) ;
492
493     croak "Compress::Zlib::deflateParams needs Level and/or Strategy"
494         unless $got->parsed('Level') + $got->parsed('Strategy') +
495             $got->parsed('Bufsize');
496
497     croak "Compress::Zlib::Inflate::deflateParams: Bufsize must be >= 1, you specified " . 
498             $got->value('Bufsize')
499         if $got->parsed('Bufsize') && $got->value('Bufsize') <= 1;
500
501     my $flags = 0;
502     $flags |= 1 if $got->parsed('Level') ;
503     $flags |= 2 if $got->parsed('Strategy') ;
504     $flags |= 4 if $got->parsed('Bufsize') ;
505
506     $self->_deflateParams($flags, $got->value('Level'), 
507                           $got->value('Strategy'), $got->value('Bufsize'));
508
509 }
510
511 sub compress($;$)
512 {
513     my ($x, $output, $err, $in) =('', '', '', '') ;
514
515     if (ref $_[0] ) {
516         $in = $_[0] ;
517         croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
518     }
519     else {
520         $in = \$_[0] ;
521     }
522
523     my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
524
525     $x = new Compress::Zlib::Deflate -AppendOutput => 1, -Level => $level
526             or return undef ;
527
528     $err = $x->deflate($in, $output) ;
529     return undef unless $err == Z_OK() ;
530
531     $err = $x->flush($output) ;
532     return undef unless $err == Z_OK() ;
533     
534     return $output ;
535
536 }
537
538 sub uncompress($)
539 {
540     my ($x, $output, $err, $in) =('', '', '', '') ;
541
542     if (ref $_[0] ) {
543         $in = $_[0] ;
544         croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
545     }
546     else {
547         $in = \$_[0] ;
548     }
549
550     $x = new Compress::Zlib::Inflate -ConsumeInput => 0 or return undef ;
551  
552     $err = $x->inflate($in, $output) ;
553     return undef unless $err == Z_STREAM_END() ;
554  
555     return $output ;
556 }
557
558
559 ### This stuff is for backward compat. with Compress::Zlib 1.x
560
561  
562 sub deflateInit(@)
563 {
564     my ($got) = ParseParameters(0,
565                 {
566                 'Bufsize'       => [1, 1, Parse_unsigned, 4096],
567                 'Level'         => [1, 1, Parse_signed,   Z_DEFAULT_COMPRESSION()],
568                 'Method'        => [1, 1, Parse_unsigned, Z_DEFLATED()],
569                 'WindowBits'    => [1, 1, Parse_signed,   MAX_WBITS()],
570                 'MemLevel'      => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
571                 'Strategy'      => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
572                 'Dictionary'    => [1, 1, Parse_any,      ""],
573                 }, @_ ) ;
574
575     croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " . 
576             $got->value('Bufsize')
577         unless $got->value('Bufsize') >= 1;
578
579     my $obj ;
580  
581     my $status = 0 ;
582     ($obj, $status) = 
583       _deflateInit(0,
584                 $got->value('Level'), 
585                 $got->value('Method'), 
586                 $got->value('WindowBits'), 
587                 $got->value('MemLevel'), 
588                 $got->value('Strategy'), 
589                 $got->value('Bufsize'),
590                 $got->value('Dictionary')) ;
591
592     my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldDeflate"  : undef) ;
593     return wantarray ? ($x, $status) : $x ;
594 }
595  
596 sub inflateInit(@)
597 {
598     my ($got) = ParseParameters(0,
599                 {
600                 'Bufsize'       => [1, 1, Parse_unsigned, 4096],
601                 'WindowBits'    => [1, 1, Parse_signed,   MAX_WBITS()],
602                 'Dictionary'    => [1, 1, Parse_any,      ""],
603                 }, @_) ;
604
605
606     croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " . 
607             $got->value('Bufsize')
608         unless $got->value('Bufsize') >= 1;
609
610     my $status = 0 ;
611     my $obj ;
612     ($obj, $status) = _inflateInit(FLAG_CONSUME_INPUT,
613                                 $got->value('WindowBits'), 
614                                 $got->value('Bufsize'), 
615                                 $got->value('Dictionary')) ;
616
617     my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldInflate"  : undef) ;
618
619     wantarray ? ($x, $status) : $x ;
620 }
621
622 package Zlib::OldDeflate ;
623
624 our (@ISA);
625 @ISA = qw(Compress::Zlib::deflateStream);
626
627
628 sub deflate
629 {
630     my $self = shift ;
631     my $output ;
632
633     my $status = $self->SUPER::deflate($_[0], $output) ;
634     wantarray ? ($output, $status) : $output ;
635 }
636
637 sub flush
638 {
639     my $self = shift ;
640     my $output ;
641     my $flag = shift || Compress::Zlib::Z_FINISH();
642     my $status = $self->SUPER::flush($output, $flag) ;
643     
644     wantarray ? ($output, $status) : $output ;
645 }
646
647 package Zlib::OldInflate ;
648
649 our (@ISA);
650 @ISA = qw(Compress::Zlib::inflateStream);
651
652 sub inflate
653 {
654     my $self = shift ;
655     my $output ;
656     my $status = $self->SUPER::inflate($_[0], $output) ;
657     wantarray ? ($output, $status) : $output ;
658 }
659
660 package Compress::Zlib ;
661
662 use Compress::Gzip::Constants;
663
664 sub memGzip($)
665 {
666   my $x = new Compress::Zlib::Deflate(
667                       -AppendOutput  => 1,
668                       -CRC32         => 1,
669                       -ADLER32       => 0,
670                       -Level         => Z_BEST_COMPRESSION(),
671                       -WindowBits    => - MAX_WBITS(),
672                      )
673       or return undef ;
674  
675   # write a minimal gzip header
676   my $output = GZIP_MINIMUM_HEADER ;
677  
678   # if the deflation buffer isn't a reference, make it one
679   my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
680
681   my $status = $x->deflate($string, \$output) ;
682   $status == Z_OK()
683       or return undef ;
684  
685   $status = $x->flush(\$output) ;
686   $status == Z_OK()
687       or return undef ;
688  
689   return $output . pack("V V", $x->crc32(), $x->total_in()) ;
690  
691 }
692
693
694 sub _removeGzipHeader($)
695 {
696     my $string = shift ;
697
698     return Z_DATA_ERROR() 
699         if length($$string) < GZIP_MIN_HEADER_SIZE ;
700
701     my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) = 
702         unpack ('CCCCVCC', $$string);
703
704     return Z_DATA_ERROR()
705         unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
706            $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
707     substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
708
709     # skip extra field
710     if ($flags & GZIP_FLG_FEXTRA)
711     {
712         return Z_DATA_ERROR()
713             if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
714
715         my ($extra_len) = unpack ('v', $$string);
716         $extra_len += GZIP_FEXTRA_HEADER_SIZE;
717         return Z_DATA_ERROR()
718             if length($$string) < $extra_len ;
719
720         substr($$string, 0, $extra_len) = '';
721     }
722
723     # skip orig name
724     if ($flags & GZIP_FLG_FNAME)
725     {
726         my $name_end = index ($$string, GZIP_NULL_BYTE);
727         return Z_DATA_ERROR()
728            if $name_end == -1 ;
729         substr($$string, 0, $name_end + 1) =  '';
730     }
731
732     # skip comment
733     if ($flags & GZIP_FLG_FCOMMENT)
734     {
735         my $comment_end = index ($$string, GZIP_NULL_BYTE);
736         return Z_DATA_ERROR()
737             if $comment_end == -1 ;
738         substr($$string, 0, $comment_end + 1) = '';
739     }
740
741     # skip header crc
742     if ($flags & GZIP_FLG_FHCRC)
743     {
744         return Z_DATA_ERROR()
745             if length ($$string) < GZIP_FHCRC_SIZE ;
746         substr($$string, 0, GZIP_FHCRC_SIZE) = '';
747     }
748     
749     return Z_OK();
750 }
751
752
753 sub memGunzip($)
754 {
755     # if the buffer isn't a reference, make it one
756     my $string = (ref $_[0] ? $_[0] : \$_[0]);
757  
758     _removeGzipHeader($string) == Z_OK() 
759         or return undef;
760      
761     my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
762     my $x = new Compress::Zlib::Inflate({-WindowBits => - MAX_WBITS(),
763                          -Bufsize => $bufsize}) 
764
765               or return undef;
766
767     my $output = "" ;
768     my $status = $x->inflate($string, $output);
769     return undef 
770         unless $status == Z_STREAM_END();
771
772     if (length $$string >= 8)
773     {
774         my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
775         substr($$string, 0, 8) = '';
776         return undef 
777             unless $len == length($output) and
778                    $crc == crc32($output);
779     }
780     else
781     {
782         $$string = '';
783     }
784     return $output;   
785 }
786
787 # Autoload methods go after __END__, and are processed by the autosplit program.
788
789 1;
790 __END__
791
792
793 =head1 NAME
794
795 Compress::Zlib - Interface to zlib compression library
796
797 =head1 SYNOPSIS
798
799     use Compress::Zlib 2 ;
800
801     ($d, $status) = new Compress::Zlib::Deflate( [OPT] ) ;
802     $status = $d->deflate($input, $output) ;
803     $status = $d->flush($output [, $flush_type]) ;
804     $d->deflateParams(OPTS) ;
805     $d->deflateTune(OPTS) ;
806     $d->dict_adler() ;
807     $d->crc32() ;
808     $d->adler32() ;
809     $d->total_in() ;
810     $d->total_out() ;
811     $d->msg() ;
812     $d->get_Strategy();
813     $d->get_Level();
814     $d->get_BufSize();
815
816     ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) ;
817     $status = $i->inflate($input, $output [, $eof]) ;
818     $status = $i->inflateSync($input) ;
819     $i->dict_adler() ;
820     $d->crc32() ;
821     $d->adler32() ;
822     $i->total_in() ;
823     $i->total_out() ;
824     $i->msg() ;
825     $d->get_BufSize();
826
827     $dest = compress($source) ;
828     $dest = uncompress($source) ;
829
830     $gz = gzopen($filename or filehandle, $mode) ;
831     $bytesread = $gz->gzread($buffer [,$size]) ;
832     $bytesread = $gz->gzreadline($line) ;
833     $byteswritten = $gz->gzwrite($buffer) ;
834     $status = $gz->gzflush($flush) ;
835     $offset = $gz->gztell() ;
836     $status = $gz->gzseek($offset, $whence) ;
837     $status = $gz->gzclose() ;
838     $status = $gz->gzeof() ;
839     $status = $gz->gzsetparams($level, $strategy) ;
840     $errstring = $gz->gzerror() ; 
841     $gzerrno
842
843     $dest = Compress::Zlib::memGzip($buffer) ;
844     $dest = Compress::Zlib::memGunzip($buffer) ;
845
846     $crc = adler32($buffer [,$crc]) ;
847     $crc = crc32($buffer [,$crc]) ;
848
849     $crc = adler32_combine($crc1, $crc2, $len2)l
850     $crc = crc32_combine($adler1, $adler2, $len2)
851
852     ZLIB_VERSION
853     ZLIB_VERNUM
854
855     # Compress::Zlib 1.x legacy interface
856
857     ($d, $status) = deflateInit( [OPT] ) ;
858     ($out, $status) = $d->deflate($buffer) ;
859     $status = $d->deflateParams([OPT]) ;
860     ($out, $status) = $d->flush() ;
861     $d->dict_adler() ;
862     $d->total_in() ;
863     $d->total_out() ;
864     $d->msg() ;
865
866     ($i, $status) = inflateInit( [OPT] ) ;
867     ($out, $status) = $i->inflate($buffer) ;
868     $status = $i->inflateSync($buffer) ;
869     $i->dict_adler() ;
870     $i->total_in() ;
871     $i->total_out() ;
872     $i->msg() ;
873
874
875 =head1 DESCRIPTION
876
877 The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
878 compression library (see L</AUTHOR> for details about where to get
879 I<zlib>). 
880 The I<zlib> library allows reading and writing of
881 compressed data streams that conform to RFC1950, RFC1951 and RFC1952
882 (aka gzip).
883 Most of the I<zlib> functionality is available in I<Compress::Zlib>. 
884
885 Unless you are working with legacy code, or you need to work directly
886 with the low-level zlib interface, it is recommended that applications
887 use one of the newer C<IO::*> interfaces provided with this module.
888
889 The C<Compress::Zlib> module can be split into two general areas of
890 functionality, namely a low-level in-memory compression/decompression
891 interface and a simple read/write interface to I<gzip> files.
892
893 Each of these areas will be discussed separately below.
894
895
896 =head1 GZIP INTERFACE
897
898 A number of functions are supplied in I<zlib> for reading and writing
899 I<gzip> files that conform to RFC1952. This module provides an interface
900 to most of them. 
901
902 If you are upgrading from C<Compress::Zlib> 1.x, the following enhancements
903 have been made to the C<gzopen> interface:
904
905 =over 5
906
907 =item 1
908
909 If you want to to open either STDIN or STDOUT with C<gzopen>, you can now
910 optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
911 C<\*STDOUT>.
912
913 =item 2 
914
915 In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open the
916 underlying file. This made things especially tricky when a Perl filehandle was
917 passed to C<gzopen>. Behind the scenes the numeric C file descriptor had to be
918 extracted from the Perl filehandle and this passed to the zlib library.
919
920 Apart from being non-portable to some operating systems, this made it difficult
921 to use C<gzopen> in situations where you wanted to extract/create a gzip data
922 stream that is embedded in a larger file, without having to resort to opening
923 and closing the file multiple times. 
924
925 In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been completely
926 rewritten to use the L<IO::Gzip|IO::Gzip> for writing gzip files and
927 L<IO::Gunzip|IO::Gunzip> for reading gzip files.
928
929 =item 3
930
931 Addition of C<gzseek> to provide a restricted C<seek> interface.
932
933 =item 4.
934
935 Added C<gztell>.
936
937 =back
938
939 A more complete and flexible interface for reading/writing gzip
940 files/buffers is included with this module.  See L<IO::Gzip|IO::Gzip> and
941 L<IO::Gunzip|IO::Gunzip> for more details.
942
943 =over 5
944
945 =item B<$gz = gzopen($filename, $mode)>
946
947 =item B<$gz = gzopen($filehandle, $mode)>
948
949 This function opens either the I<gzip> file C<$filename> for reading or
950 writing or attaches to the opened filehandle, C<$filehandle>. 
951 It returns an object on success and C<undef> on failure.
952
953 When writing a gzip file this interface will always create the smallest
954 possible gzip header (exactly 10 bytes). If you want greater control over
955 the information stored in the gzip header (like the original filename or a
956 comment) use L<IO::Gzip|IO::Gzip> instead.
957
958 The second parameter, C<$mode>, is used to specify whether the file is
959 opened for reading or writing and to optionally specify a compression
960 level and compression strategy when writing. The format of the C<$mode>
961 parameter is similar to the mode parameter to the 'C' function C<fopen>,
962 so "rb" is used to open for reading and "wb" for writing.
963
964 To specify a compression level when writing, append a digit between 0
965 and 9 to the mode string -- 0 means no compression and 9 means maximum
966 compression.
967 If no compression level is specified Z_DEFAULT_COMPRESSION is used.
968
969 To specify the compression strategy when writing, append 'f' for filtered
970 data, 'h' for Huffman only compression, or 'R' for run-length encoding.
971 If no strategy is specified Z_DEFAULT_STRATEGY is used.
972
973 So, for example, "wb9" means open for writing with the maximum compression
974 using the default strategy and "wb4R" means open for writing with compression
975 level 4 and run-length encoding.
976
977 Refer to the I<zlib> documentation for the exact format of the C<$mode>
978 parameter.
979
980
981 =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
982
983 Reads C<$size> bytes from the compressed file into C<$buffer>. If
984 C<$size> is not specified, it will default to 4096. If the scalar
985 C<$buffer> is not large enough, it will be extended automatically.
986
987 Returns the number of bytes actually read. On EOF it returns 0 and in
988 the case of an error, -1.
989
990 =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
991
992 Reads the next line from the compressed file into C<$line>. 
993
994 Returns the number of bytes actually read. On EOF it returns 0 and in
995 the case of an error, -1.
996
997 It is legal to intermix calls to C<gzread> and C<gzreadline>.
998
999 In addition, C<gzreadline> fully supports the use of of the variable C<$/>
1000 (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use) to
1001 determine what constitutes an end of line. Both paragraph mode and file
1002 slurp mode are supported. 
1003
1004
1005 =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
1006
1007 Writes the contents of C<$buffer> to the compressed file. Returns the
1008 number of bytes actually written, or 0 on error.
1009
1010 =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
1011
1012 Flushes all pending output into the compressed file.
1013
1014 This method takes an optional parameter, C<$flush_type>, that controls
1015 how the flushing will be carried out. By default the C<$flush_type>
1016 used is C<Z_FINISH>. Other valid values for C<$flush_type> are
1017 C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
1018 strongly recommended that you only set the C<flush_type> parameter if
1019 you fully understand the implications of what it does - overuse of C<flush>
1020 can seriously degrade the level of compression achieved. See the C<zlib>
1021 documentation for details.
1022
1023 Returns 1 on success, 0 on failure.
1024
1025
1026 =item B<$offset = $gz-E<gt>gztell() ;>
1027
1028 Returns the uncompressed file offset.
1029
1030 =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
1031
1032 Provides a sub-set of the C<seek> functionality, with the restriction
1033 that it is only legal to seek forward in the compressed file.
1034 It is a fatal error to attempt to seek backward.
1035
1036 When opened for writing, empty parts of the file will have NULL (0x00)
1037 bytes written to them.
1038
1039 The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
1040
1041 Returns 1 on success, 0 on failure.
1042
1043 =item B<$gz-E<gt>gzclose>
1044
1045 Closes the compressed file. Any pending data is flushed to the file
1046 before it is closed.
1047
1048 Returns 1 on success, 0 on failure.
1049
1050 =item B<$gz-E<gt>gzsetparams($level, $strategy>
1051
1052 Change settings for the deflate stream C<$gz>.
1053
1054 The list of the valid options is shown below. Options not specified
1055 will remain unchanged.
1056
1057 Note: This method is only available if you are running zlib 1.0.6 or better.
1058
1059 =over 5
1060
1061 =item B<$level>
1062
1063 Defines the compression level. Valid values are 0 through 9,
1064 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1065 C<Z_DEFAULT_COMPRESSION>.
1066
1067 =item B<$strategy>
1068
1069 Defines the strategy used to tune the compression. The valid values are
1070 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
1071
1072 =back
1073
1074 =item B<$gz-E<gt>gzerror>
1075
1076 Returns the I<zlib> error message or number for the last operation
1077 associated with C<$gz>. The return value will be the I<zlib> error
1078 number when used in a numeric context and the I<zlib> error message
1079 when used in a string context. The I<zlib> error number constants,
1080 shown below, are available for use.
1081
1082     Z_OK
1083     Z_STREAM_END
1084     Z_ERRNO
1085     Z_STREAM_ERROR
1086     Z_DATA_ERROR
1087     Z_MEM_ERROR
1088     Z_BUF_ERROR
1089
1090 =item B<$gzerrno>
1091
1092 The C<$gzerrno> scalar holds the error code associated with the most
1093 recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
1094 I<not> associated with a particular file.
1095
1096 As with C<gzerror()> it returns an error number in numeric context and
1097 an error message in string context. Unlike C<gzerror()> though, the
1098 error message will correspond to the I<zlib> message when the error is
1099 associated with I<zlib> itself, or the UNIX error message when it is
1100 not (i.e. I<zlib> returned C<Z_ERRORNO>).
1101
1102 As there is an overlap between the error numbers used by I<zlib> and
1103 UNIX, C<$gzerrno> should only be used to check for the presence of
1104 I<an> error in numeric context. Use C<gzerror()> to check for specific
1105 I<zlib> errors. The I<gzcat> example below shows how the variable can
1106 be used safely.
1107
1108 =back
1109
1110
1111 =head2 Examples
1112
1113 Here is an example script which uses the interface. It implements a
1114 I<gzcat> function.
1115
1116     use strict ;
1117     use warnings ;
1118     
1119     use Compress::Zlib ;
1120     
1121     # use stdin if no files supplied
1122     @ARGV = '-' unless @ARGV ;
1123     
1124     foreach my $file (@ARGV) {
1125         my $buffer ;
1126     
1127         my $gz = gzopen($file, "rb") 
1128              or die "Cannot open $file: $gzerrno\n" ;
1129     
1130         print $buffer while $gz->gzread($buffer) > 0 ;
1131     
1132         die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n" 
1133             if $gzerrno != Z_STREAM_END ;
1134         
1135         $gz->gzclose() ;
1136     }
1137
1138 Below is a script which makes use of C<gzreadline>. It implements a
1139 very simple I<grep> like script.
1140
1141     use strict ;
1142     use warnings ;
1143     
1144     use Compress::Zlib ;
1145     
1146     die "Usage: gzgrep pattern [file...]\n"
1147         unless @ARGV >= 1;
1148     
1149     my $pattern = shift ;
1150     
1151     # use stdin if no files supplied
1152     @ARGV = '-' unless @ARGV ;
1153     
1154     foreach my $file (@ARGV) {
1155         my $gz = gzopen($file, "rb") 
1156              or die "Cannot open $file: $gzerrno\n" ;
1157     
1158         while ($gz->gzreadline($_) > 0) {
1159             print if /$pattern/ ;
1160         }
1161     
1162         die "Error reading from $file: $gzerrno\n" 
1163             if $gzerrno != Z_STREAM_END ;
1164         
1165         $gz->gzclose() ;
1166     }
1167
1168 This script, I<gzstream>, does the opposite of the I<gzcat> script
1169 above. It reads from standard input and writes a gzip data stream to
1170 standard output.
1171
1172     use strict ;
1173     use warnings ;
1174     
1175     use Compress::Zlib ;
1176     
1177     binmode STDOUT;  # gzopen only sets it on the fd
1178     
1179     my $gz = gzopen(\*STDOUT, "wb")
1180           or die "Cannot open stdout: $gzerrno\n" ;
1181     
1182     while (<>) {
1183         $gz->gzwrite($_) 
1184           or die "error writing: $gzerrno\n" ;
1185     }
1186
1187     $gz->gzclose ;
1188
1189 =head2 Compress::Zlib::memGzip
1190
1191 This function is used to create an in-memory gzip file with the minimum
1192 possible gzip header (exactly 10 bytes).
1193
1194     $dest = Compress::Zlib::memGzip($buffer) ;
1195
1196 If successful, it returns the in-memory gzip file, otherwise it returns
1197 undef.
1198
1199 The C<$buffer> parameter can either be a scalar or a scalar reference.
1200
1201 See L<IO::Gzip|IO::Gzip> for an alternative way to carry out in-memory gzip
1202 compression.
1203
1204 =head2 Compress::Zlib::memGunzip
1205
1206 This function is used to uncompress an in-memory gzip file.
1207
1208     $dest = Compress::Zlib::memGunzip($buffer) ;
1209
1210 If successful, it returns the uncompressed gzip file, otherwise it
1211 returns undef.
1212
1213 The C<$buffer> parameter can either be a scalar or a scalar reference. The
1214 contents of the C<$buffer> parameter are destroyed after calling this function.
1215
1216 See L<IO::Gunzip|IO::Gunzip> for an alternative way to carry out in-memory gzip
1217 uncompression.
1218
1219 =head1 COMPRESS/UNCOMPRESS
1220
1221 Two functions are provided to perform in-memory compression/uncompression of
1222 RFC 1950 data streams. They are called C<compress> and C<uncompress>.
1223
1224 =over 5
1225
1226 =item B<$dest = compress($source [, $level] ) ;>
1227
1228 Compresses C<$source>. If successful it returns the compressed
1229 data. Otherwise it returns I<undef>.
1230
1231 The source buffer, C<$source>, can either be a scalar or a scalar
1232 reference.
1233
1234 The C<$level> parameter defines the compression level. Valid values are
1235 0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
1236 C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
1237 If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
1238
1239
1240 =item B<$dest = uncompress($source) ;>
1241
1242 Uncompresses C<$source>. If successful it returns the uncompressed
1243 data. Otherwise it returns I<undef>.
1244
1245 The source buffer can either be a scalar or a scalar reference.
1246
1247 =back
1248
1249 Please note: the two functions defined above are I<not> compatible with
1250 the Unix commands of the same name.
1251
1252 See L<IO::Deflate|IO::Deflate> and L<IO::Inflate|IO::Inflate> included with
1253 this distribution for an alternative interface for reading/writing RFC 1950
1254 files/buffers.
1255
1256 =head1 CHECKSUM FUNCTIONS
1257
1258 Two functions are provided by I<zlib> to calculate checksums. For the
1259 Perl interface, the order of the two parameters in both functions has
1260 been reversed. This allows both running checksums and one off
1261 calculations to be done.
1262
1263     $crc = adler32($buffer [,$crc]) ;
1264     $crc = crc32($buffer [,$crc]) ;
1265
1266 The buffer parameters can either be a scalar or a scalar reference.
1267
1268 If the $crc parameters is C<undef>, the crc value will be reset.
1269
1270 If you have built this module with zlib 1.2.3 or better, two more
1271 CRC-related functions are available.
1272
1273     $crc = adler32_combine($crc1, $crc2, $len2)l
1274     $crc = crc32_combine($adler1, $adler2, $len2)
1275
1276 These functions allow checksums to be merged.
1277
1278 =head1 Compress::Zlib::Deflate
1279
1280 This section defines an interface that allows in-memory compression using
1281 the I<deflate> interface provided by zlib.
1282
1283 Note: The interface defined in this section is different from version
1284 1.x of this module. The original deflate interface is still available
1285 for backward compatibility and is documented in the section
1286 L<Compress::Zlib 1.x Deflate Interface>.
1287
1288 Here is a definition of the interface available:
1289
1290
1291 =head2 B<($d, $status) = new Compress::Zlib::Deflate( [OPT] ) >
1292
1293 Initialises a deflation object. 
1294
1295 If you are familiar with the I<zlib> library, it combines the
1296 features of the I<zlib> functions C<deflateInit>, C<deflateInit2>
1297 and C<deflateSetDictionary>.
1298
1299 If successful, it will return the initialised deflation object, C<$d>
1300 and a C<$status> of C<Z_OK> in a list context. In scalar context it
1301 returns the deflation object, C<$d>, only.
1302
1303 If not successful, the returned deflation object, C<$d>, will be
1304 I<undef> and C<$status> will hold the a I<zlib> error code.
1305
1306 The function optionally takes a number of named options specified as
1307 C<-Name =E<gt> value> pairs. This allows individual options to be
1308 tailored without having to specify them all in the parameter list.
1309
1310 For backward compatibility, it is also possible to pass the parameters
1311 as a reference to a hash containing the name=>value pairs.
1312
1313 Below is a list of the valid options:
1314
1315 =over 5
1316
1317 =item B<-Level>
1318
1319 Defines the compression level. Valid values are 0 through 9,
1320 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1321 C<Z_DEFAULT_COMPRESSION>.
1322
1323 The default is C<-Level =E<gt> Z_DEFAULT_COMPRESSION>.
1324
1325 =item B<-Method>
1326
1327 Defines the compression method. The only valid value at present (and
1328 the default) is C<-Method =E<gt> Z_DEFLATED>.
1329
1330 =item B<-WindowBits>
1331
1332 For a definition of the meaning and valid values for C<WindowBits>
1333 refer to the I<zlib> documentation for I<deflateInit2>.
1334
1335 Defaults to C<-WindowBits =E<gt> MAX_WBITS>.
1336
1337 =item B<-MemLevel>
1338
1339 For a definition of the meaning and valid values for C<MemLevel>
1340 refer to the I<zlib> documentation for I<deflateInit2>.
1341
1342 Defaults to C<-MemLevel =E<gt> MAX_MEM_LEVEL>.
1343
1344 =item B<-Strategy>
1345
1346 Defines the strategy used to tune the compression. The valid values are
1347 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED>, C<Z_RLE>, C<Z_FIXED> and
1348 C<Z_HUFFMAN_ONLY>.
1349
1350 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1351
1352 =item B<-Dictionary>
1353
1354 When a dictionary is specified I<Compress::Zlib> will automatically
1355 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1356 Adler32 value for the dictionary can be obtained by calling the method 
1357 C<$d-E<gt>dict_adler()>.
1358
1359 The default is no dictionary.
1360
1361 =item B<-Bufsize>
1362
1363 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1364 and C<$d-E<gt>flush> methods. If the buffer has to be
1365 reallocated to increase the size, it will grow in increments of
1366 C<Bufsize>.
1367
1368 The default buffer size is 4096.
1369
1370 =item B<-AppendOutput>
1371
1372 This option controls how data is written to the output buffer by the
1373 C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1374
1375 If the C<AppendOutput> option is set to false, the output buffers in the
1376 C<$d-E<gt>deflate> and C<$d-E<gt>flush>  methods will be truncated before
1377 uncompressed data is written to them.
1378
1379 If the option is set to true, uncompressed data will be appended to the
1380 output buffer in the C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
1381
1382 This option defaults to false.
1383
1384 =item B<-CRC32>
1385
1386 If set to true, a crc32 checksum of the uncompressed data will be
1387 calculated. Use the C<$d-E<gt>crc32> method to retrieve this value.
1388
1389 This option defaults to false.
1390
1391
1392 =item B<-ADLER32>
1393
1394 If set to true, an adler32 checksum of the uncompressed data will be
1395 calculated. Use the C<$d-E<gt>adler32> method to retrieve this value.
1396
1397 This option defaults to false.
1398
1399
1400 =back
1401
1402 Here is an example of using the C<Compress::Zlib::Deflate> optional
1403 parameter list to override the default buffer size and compression
1404 level. All other options will take their default values.
1405
1406     my $d = new Compress::Zlib::Deflate ( -Bufsize => 300, 
1407                                           -Level   => Z_BEST_SPEED ) ;
1408
1409
1410 =head2 B<$status = $d-E<gt>deflate($input, $output)>
1411
1412 Deflates the contents of C<$input> and writes the compressed data to
1413 C<$output>.
1414
1415 The C<$input> and C<$output> parameters can be either scalars or scalar
1416 references.
1417
1418 When finished, C<$input> will be completely processed (assuming there
1419 were no errors). If the deflation was successful it writes the deflated
1420 data to C<$output> and returns a status value of C<Z_OK>.
1421
1422 On error, it returns a I<zlib> error code.
1423
1424 If the C<AppendOutput> option is set to true in the constructor for
1425 the C<$d> object, the compressed data will be appended to C<$output>. If
1426 it is false, C<$output> will be truncated before any compressed data is
1427 written to it.
1428
1429 B<Note>: This method will not necessarily write compressed data to
1430 C<$output> every time it is called. So do not assume that there has been
1431 an error if the contents of C<$output> is empty on returning from
1432 this method. As long as the return code from the method is C<Z_OK>,
1433 the deflate has succeeded.
1434
1435 =head2 B<$status = $d-E<gt>flush($output [, $flush_type]) >
1436
1437 Typically used to finish the deflation. Any pending output will be
1438 written to C<$output>.
1439
1440 Returns C<Z_OK> if successful.
1441
1442 Note that flushing can seriously degrade the compression ratio, so it
1443 should only be used to terminate a decompression (using C<Z_FINISH>) or
1444 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1445
1446 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1447 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1448 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1449 C<flush_type> parameter if you fully understand the implications of
1450 what it does. See the C<zlib> documentation for details.
1451
1452 If the C<AppendOutput> option is set to true in the constructor for
1453 the C<$d> object, the compressed data will be appended to C<$output>. If
1454 it is false, C<$output> will be truncated before any compressed data is
1455 written to it.
1456
1457 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1458
1459 Change settings for the deflate object C<$d>.
1460
1461 The list of the valid options is shown below. Options not specified
1462 will remain unchanged.
1463
1464
1465 =over 5
1466
1467 =item B<-Level>
1468
1469 Defines the compression level. Valid values are 0 through 9,
1470 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1471 C<Z_DEFAULT_COMPRESSION>.
1472
1473 =item B<-Strategy>
1474
1475 Defines the strategy used to tune the compression. The valid values are
1476 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
1477
1478 =item B<-BufSize>
1479
1480 Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
1481 and C<$d-E<gt>flush> methods. If the buffer has to be
1482 reallocated to increase the size, it will grow in increments of
1483 C<Bufsize>.
1484
1485
1486 =back
1487
1488 =head2 B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)>
1489
1490 Tune the internal settings for the deflate object C<$d>. This option is
1491 only available if you are running zlib 1.2.2.3 or better.
1492
1493 Refer to the documentation in zlib.h for instructions on how to fly
1494 C<deflateTune>.
1495
1496 =head2 B<$d-E<gt>dict_adler()>
1497
1498 Returns the adler32 value for the dictionary.
1499
1500 =head2 B<$d-E<gt>crc32()>
1501
1502 Returns the crc32 value for the uncompressed data to date. 
1503
1504 If the C<CRC32> option is not enabled in the constructor for this object,
1505 this method will always return 0;
1506
1507 =head2 B<$d-E<gt>adler32()>
1508
1509 Returns the adler32 value for the uncompressed data to date. 
1510
1511 =head2 B<$d-E<gt>msg()>
1512
1513 Returns the last error message generated by zlib.
1514
1515 =head2 B<$d-E<gt>total_in()>
1516
1517 Returns the total number of bytes uncompressed bytes input to deflate.
1518
1519 =head2 B<$d-E<gt>total_out()>
1520
1521 Returns the total number of compressed bytes output from deflate.
1522
1523 =head2 B<$d-E<gt>get_Strategy()>
1524
1525 Returns the deflation strategy currently used. Valid values are
1526 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
1527
1528
1529 =head2 B<$d-E<gt>get_Level()>
1530
1531 Returns the compression level being used. 
1532
1533 =head2 B<$d-E<gt>get_BufSize()>
1534
1535 Returns the buffer size used to carry out the compression.
1536
1537 =head2 Example
1538
1539
1540 Here is a trivial example of using C<deflate>. It simply reads standard
1541 input, deflates it and writes it to standard output.
1542
1543     use strict ;
1544     use warnings ;
1545
1546     use Compress::Zlib 2 ;
1547
1548     binmode STDIN;
1549     binmode STDOUT;
1550     my $x = new Compress::Zlib::Deflate
1551        or die "Cannot create a deflation stream\n" ;
1552
1553     my ($output, $status) ;
1554     while (<>)
1555     {
1556         $status = $x->deflate($_, $output) ;
1557     
1558         $status == Z_OK
1559             or die "deflation failed\n" ;
1560     
1561         print $output ;
1562     }
1563     
1564     $status = $x->flush($output) ;
1565     
1566     $status == Z_OK
1567         or die "deflation failed\n" ;
1568     
1569     print $output ;
1570
1571 =head1 Compress::Zlib::Inflate
1572
1573 This section defines an interface that allows in-memory uncompression using
1574 the I<inflate> interface provided by zlib.
1575
1576 Note: The interface defined in this section is different from version
1577 1.x of this module. The original inflate interface is still available
1578 for backward compatibility and is documented in the section
1579 L<Compress::Zlib 1.x Inflate Interface>.
1580
1581 Here is a definition of the interface:
1582
1583
1584 =head2 B< ($i, $status) = new Compress::Zlib::Inflate( [OPT] ) >
1585
1586 Initialises an inflation object. 
1587
1588 In a list context it returns the inflation object, C<$i>, and the
1589 I<zlib> status code (C<$status>). In a scalar context it returns the
1590 inflation object only.
1591
1592 If successful, C<$i> will hold the inflation object and C<$status> will
1593 be C<Z_OK>.
1594
1595 If not successful, C<$i> will be I<undef> and C<$status> will hold the
1596 I<zlib> error code.
1597
1598 The function optionally takes a number of named options specified as
1599 C<-Name =E<gt> value> pairs. This allows individual options to be
1600 tailored without having to specify them all in the parameter list.
1601
1602 For backward compatibility, it is also possible to pass the parameters
1603 as a reference to a hash containing the name=E<gt>value pairs.
1604
1605 Here is a list of the valid options:
1606
1607 =over 5
1608
1609 =item B<-WindowBits>
1610
1611 To uncompress an RFC1950 data stream, set C<WindowBits> to a positive number.
1612
1613 To uncompress an RFC1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1614
1615 For a full definition of the meaning and valid values for C<WindowBits> refer
1616 to the I<zlib> documentation for I<inflateInit2>.
1617
1618 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1619
1620 =item B<-Bufsize>
1621
1622 Sets the initial size for the output buffer used by the C<$i-E<gt>inflate>
1623 method. If the output buffer in this method has to be reallocated to
1624 increase the size, it will grow in increments of C<Bufsize>.
1625
1626 Default is 4096.
1627
1628 =item B<-Dictionary>
1629
1630 The default is no dictionary.
1631
1632 =item B<-AppendOutput>
1633
1634 This option controls how data is written to the output buffer by the
1635 C<$i-E<gt>inflate> method.
1636
1637 If the option is set to false, the output buffer in the C<$i-E<gt>inflate>
1638 method will be truncated before uncompressed data is written to it.
1639
1640 If the option is set to true, uncompressed data will be appended to the
1641 output buffer by the C<$i-E<gt>inflate> method.
1642
1643 This option defaults to false.
1644
1645
1646 =item B<-CRC32>
1647
1648 If set to true, a crc32 checksum of the uncompressed data will be
1649 calculated. Use the C<$i-E<gt>crc32> method to retrieve this value.
1650
1651 This option defaults to false.
1652
1653 =item B<-ADLER32>
1654
1655 If set to true, an adler32 checksum of the uncompressed data will be
1656 calculated. Use the C<$i-E<gt>adler32> method to retrieve this value.
1657
1658 This option defaults to false.
1659
1660 =item B<-ConsumeInput>
1661
1662 If set to true, this option will remove compressed data from the input
1663 buffer of the the C< $i-E<gt>inflate > method as the inflate progresses.
1664
1665 This option can be useful when you are processing compressed data that is
1666 embedded in another file/buffer. In this case the data that immediately
1667 follows the compressed stream will be left in the input buffer.
1668
1669 This option defaults to true.
1670
1671 =back
1672
1673 Here is an example of using an optional parameter to override the default
1674 buffer size.
1675
1676     my ($i, $status) = new Compress::Zlib::Inflate( -Bufsize => 300 ) ;
1677
1678 =head2 B< $status = $i-E<gt>inflate($input, $output [,$eof]) >
1679
1680 Inflates the complete contents of C<$input> and writes the uncompressed
1681 data to C<$output>. The C<$input> and C<$output> parameters can either be
1682 scalars or scalar references.
1683
1684 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1685 compressed data has been successfully reached. 
1686
1687 If not successful C<$status> will hold the I<zlib> error code.
1688
1689 If the C<ConsumeInput> option has been set to true when the
1690 C<Compress::Zlib::Inflate> object is created, the C<$input> parameter
1691 is modified by C<inflate>. On completion it will contain what remains
1692 of the input buffer after inflation. In practice, this means that when
1693 the return status is C<Z_OK> the C<$input> parameter will contain an
1694 empty string, and when the return status is C<Z_STREAM_END> the C<$input>
1695 parameter will contains what (if anything) was stored in the input buffer
1696 after the deflated data stream.
1697
1698 This feature is useful when processing a file format that encapsulates
1699 a compressed data stream (e.g. gzip, zip) and there is useful data
1700 immediately after the deflation stream.
1701
1702 If the C<AppendOutput> option is set to true in the constructor for
1703 this object, the uncompressed data will be appended to C<$output>. If
1704 it is false, C<$output> will be truncated before any uncompressed data
1705 is written to it.
1706
1707 The C<$eof> parameter needs a bit of explanation. 
1708
1709 Prior to version 1.2.0, zlib assumed that there was at least one trailing
1710 byte immediately after the compressed data stream when it was carrying out
1711 decompression. This normally isn't a problem because the majority of zlib
1712 applications guarantee that there will be data directly after the
1713 compressed data stream.  For example, both gzip (RFC1950) and zip both
1714 define trailing data that follows the compressed data stream.
1715
1716 The C<$eof> parameter only needs to be used if B<all> of the following
1717 conditions apply
1718
1719 =over 5
1720
1721 =item 1 
1722
1723 You are either using a copy of zlib that is older than version 1.2.0 or you
1724 want your application code to be able to run with as many different
1725 versions of zlib as possible.
1726
1727 =item 2
1728
1729 You have set the C<WindowBits> parameter to C<-MAX_WBITS> in the constructor
1730 for this object, i.e. you are uncompressing a raw deflated data stream
1731 (RFC1951).
1732
1733 =item 3
1734
1735 There is no data immediately after the compressed data stream.
1736
1737 =back
1738
1739 If B<all> of these are the case, then you need to set the C<$eof> parameter to
1740 true on the final call (and only the final call) to C<$i-E<gt>inflate>. 
1741
1742 If you have built this module with zlib >= 1.2.0, the C<$eof> parameter is
1743 ignored. You can still set it if you want, but it won't be used behind the
1744 scenes.
1745
1746 =head2 B<$status = $i-E<gt>inflateSync($input)>
1747
1748 This method can be used to attempt to recover good data from a compressed
1749 data stream that is partially corrupt.
1750 It scans C<$input> until it reaches either a I<full flush point> or the
1751 end of the buffer.
1752
1753 If a I<full flush point> is found, C<Z_OK> is returned and C<$input>
1754 will be have all data up to the flush point removed. This data can then be
1755 passed to the C<$i-E<gt>inflate> method to be uncompressed.
1756
1757 Any other return code means that a flush point was not found. If more
1758 data is available, C<inflateSync> can be called repeatedly with more
1759 compressed data until the flush point is found.
1760
1761 Note I<full flush points> are not present by default in compressed
1762 data streams. They must have been added explicitly when the data stream
1763 was created by calling C<Compress::Deflate::flush>  with C<Z_FULL_FLUSH>.
1764
1765
1766 =head2 B<$i-E<gt>dict_adler()>
1767
1768 Returns the adler32 value for the dictionary.
1769
1770 =head2 B<$i-E<gt>crc32()>
1771
1772 Returns the crc32 value for the uncompressed data to date.
1773
1774 If the C<CRC32> option is not enabled in the constructor for this object,
1775 this method will always return 0;
1776
1777 =head2 B<$i-E<gt>adler32()>
1778
1779 Returns the adler32 value for the uncompressed data to date.
1780
1781 If the C<ADLER32> option is not enabled in the constructor for this object,
1782 this method will always return 0;
1783
1784 =head2 B<$i-E<gt>msg()>
1785
1786 Returns the last error message generated by zlib.
1787
1788 =head2 B<$i-E<gt>total_in()>
1789
1790 Returns the total number of bytes compressed bytes input to inflate.
1791
1792 =head2 B<$i-E<gt>total_out()>
1793
1794 Returns the total number of uncompressed bytes output from inflate.
1795
1796 =head2 B<$d-E<gt>get_BufSize()>
1797
1798 Returns the buffer size used to carry out the decompression.
1799
1800 =head2 Example
1801
1802 Here is an example of using C<inflate>.
1803
1804     use strict ;
1805     use warnings ;
1806     
1807     use Compress::Zlib 2 ;
1808     
1809     my $x = new Compress::Zlib::Inflate()
1810        or die "Cannot create a inflation stream\n" ;
1811     
1812     my $input = '' ;
1813     binmode STDIN;
1814     binmode STDOUT;
1815     
1816     my ($output, $status) ;
1817     while (read(STDIN, $input, 4096))
1818     {
1819         $status = $x->inflate(\$input, $output) ;
1820     
1821         print $output 
1822             if $status == Z_OK or $status == Z_STREAM_END ;
1823     
1824         last if $status != Z_OK ;
1825     }
1826     
1827     die "inflation failed\n"
1828         unless $status == Z_STREAM_END ;
1829
1830 =head1 Compress::Zlib 1.x Deflate Interface
1831
1832 This section defines the interface available in C<Compress::Zlib> version
1833 1.x that allows in-memory compression using the I<deflate> interface
1834 provided by zlib.
1835
1836 Here is a definition of the interface available:
1837
1838
1839 =head2 B<($d, $status) = deflateInit( [OPT] )>
1840
1841 Initialises a deflation stream. 
1842
1843 It combines the features of the I<zlib> functions C<deflateInit>,
1844 C<deflateInit2> and C<deflateSetDictionary>.
1845
1846 If successful, it will return the initialised deflation stream, C<$d>
1847 and C<$status> of C<Z_OK> in a list context. In scalar context it
1848 returns the deflation stream, C<$d>, only.
1849
1850 If not successful, the returned deflation stream (C<$d>) will be
1851 I<undef> and C<$status> will hold the exact I<zlib> error code.
1852
1853 The function optionally takes a number of named options specified as
1854 C<-Name=E<gt>value> pairs. This allows individual options to be
1855 tailored without having to specify them all in the parameter list.
1856
1857 For backward compatibility, it is also possible to pass the parameters
1858 as a reference to a hash containing the name=>value pairs.
1859
1860 The function takes one optional parameter, a reference to a hash.  The
1861 contents of the hash allow the deflation interface to be tailored.
1862
1863 Here is a list of the valid options:
1864
1865 =over 5
1866
1867 =item B<-Level>
1868
1869 Defines the compression level. Valid values are 0 through 9,
1870 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1871 C<Z_DEFAULT_COMPRESSION>.
1872
1873 The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
1874
1875 =item B<-Method>
1876
1877 Defines the compression method. The only valid value at present (and
1878 the default) is C<-Method =E<gt>Z_DEFLATED>.
1879
1880 =item B<-WindowBits>
1881
1882 To create an RFC1950 data stream, set C<WindowBits> to a positive number.
1883
1884 To create an RFC1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1885
1886 For a full definition of the meaning and valid values for C<WindowBits> refer
1887 to the I<zlib> documentation for I<deflateInit2>.
1888
1889 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
1890
1891 =item B<-MemLevel>
1892
1893 For a definition of the meaning and valid values for C<MemLevel>
1894 refer to the I<zlib> documentation for I<deflateInit2>.
1895
1896 Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
1897
1898 =item B<-Strategy>
1899
1900 Defines the strategy used to tune the compression. The valid values are
1901 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
1902
1903 The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
1904
1905 =item B<-Dictionary>
1906
1907 When a dictionary is specified I<Compress::Zlib> will automatically
1908 call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1909 Adler32 value for the dictionary can be obtained by calling the method 
1910 C<$d->dict_adler()>.
1911
1912 The default is no dictionary.
1913
1914 =item B<-Bufsize>
1915
1916 Sets the initial size for the deflation buffer. If the buffer has to be
1917 reallocated to increase the size, it will grow in increments of
1918 C<Bufsize>.
1919
1920 The default is 4096.
1921
1922 =back
1923
1924 Here is an example of using the C<deflateInit> optional parameter list
1925 to override the default buffer size and compression level. All other
1926 options will take their default values.
1927
1928     deflateInit( -Bufsize => 300, 
1929                  -Level => Z_BEST_SPEED  ) ;
1930
1931
1932 =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1933
1934
1935 Deflates the contents of C<$buffer>. The buffer can either be a scalar
1936 or a scalar reference.  When finished, C<$buffer> will be
1937 completely processed (assuming there were no errors). If the deflation
1938 was successful it returns the deflated output, C<$out>, and a status
1939 value, C<$status>, of C<Z_OK>.
1940
1941 On error, C<$out> will be I<undef> and C<$status> will contain the
1942 I<zlib> error code.
1943
1944 In a scalar context C<deflate> will return C<$out> only.
1945
1946 As with the I<deflate> function in I<zlib>, it is not necessarily the
1947 case that any output will be produced by this method. So don't rely on
1948 the fact that C<$out> is empty for an error test.
1949
1950
1951 =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
1952
1953 Typically used to finish the deflation. Any pending output will be
1954 returned via C<$out>.
1955 C<$status> will have a value C<Z_OK> if successful.
1956
1957 In a scalar context C<flush> will return C<$out> only.
1958
1959 Note that flushing can seriously degrade the compression ratio, so it
1960 should only be used to terminate a decompression (using C<Z_FINISH>) or
1961 when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1962
1963 By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1964 for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1965 and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1966 C<flush_type> parameter if you fully understand the implications of
1967 what it does. See the C<zlib> documentation for details.
1968
1969 =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1970
1971 Change settings for the deflate stream C<$d>.
1972
1973 The list of the valid options is shown below. Options not specified
1974 will remain unchanged.
1975
1976 =over 5
1977
1978 =item B<-Level>
1979
1980 Defines the compression level. Valid values are 0 through 9,
1981 C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1982 C<Z_DEFAULT_COMPRESSION>.
1983
1984 =item B<-Strategy>
1985
1986 Defines the strategy used to tune the compression. The valid values are
1987 C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
1988
1989 =back
1990
1991 =head2 B<$d-E<gt>dict_adler()>
1992
1993 Returns the adler32 value for the dictionary.
1994
1995 =head2 B<$d-E<gt>msg()>
1996
1997 Returns the last error message generated by zlib.
1998
1999 =head2 B<$d-E<gt>total_in()>
2000
2001 Returns the total number of bytes uncompressed bytes input to deflate.
2002
2003 =head2 B<$d-E<gt>total_out()>
2004
2005 Returns the total number of compressed bytes output from deflate.
2006
2007 =head2 Example
2008
2009
2010 Here is a trivial example of using C<deflate>. It simply reads standard
2011 input, deflates it and writes it to standard output.
2012
2013     use strict ;
2014     use warnings ;
2015
2016     use Compress::Zlib ;
2017
2018     binmode STDIN;
2019     binmode STDOUT;
2020     my $x = deflateInit()
2021        or die "Cannot create a deflation stream\n" ;
2022
2023     my ($output, $status) ;
2024     while (<>)
2025     {
2026         ($output, $status) = $x->deflate($_) ;
2027     
2028         $status == Z_OK
2029             or die "deflation failed\n" ;
2030     
2031         print $output ;
2032     }
2033     
2034     ($output, $status) = $x->flush() ;
2035     
2036     $status == Z_OK
2037         or die "deflation failed\n" ;
2038     
2039     print $output ;
2040
2041 =head1 Compress::Zlib 1.x Inflate Interface
2042
2043 This section defines the interface available in C<Compress::Zlib> version
2044 1.x that allows in-memory uncompression using the I<deflate> interface
2045 provided by zlib.
2046
2047 Here is a definition of the interface:
2048
2049
2050 =head2 B<($i, $status) = inflateInit()>
2051
2052 Initializes an inflation stream. 
2053
2054 In a list context it returns the inflation stream, C<$i>, and the
2055 I<zlib> status code (C<$status>). In a scalar context it returns the
2056 inflation stream only.
2057
2058 If successful, C<$i> will hold the inflation stream and C<$status> will
2059 be C<Z_OK>.
2060
2061 If not successful, C<$i> will be I<undef> and C<$status> will hold the
2062 I<zlib> error code.
2063
2064 The function optionally takes a number of named options specified as
2065 C<-Name=E<gt>value> pairs. This allows individual options to be
2066 tailored without having to specify them all in the parameter list.
2067  
2068 For backward compatibility, it is also possible to pass the parameters
2069 as a reference to a hash containing the name=>value pairs.
2070  
2071 The function takes one optional parameter, a reference to a hash.  The
2072 contents of the hash allow the deflation interface to be tailored.
2073  
2074 Here is a list of the valid options:
2075
2076 =over 5
2077
2078 =item B<-WindowBits>
2079
2080 To uncompress an RFC1950 data stream, set C<WindowBits> to a positive number.
2081
2082 To uncompress an RFC1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
2083
2084 For a full definition of the meaning and valid values for C<WindowBits> refer
2085 to the I<zlib> documentation for I<inflateInit2>.
2086
2087 Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
2088
2089 =item B<-Bufsize>
2090
2091 Sets the initial size for the inflation buffer. If the buffer has to be
2092 reallocated to increase the size, it will grow in increments of
2093 C<Bufsize>. 
2094
2095 Default is 4096.
2096
2097 =item B<-Dictionary>
2098
2099 The default is no dictionary.
2100
2101 =back
2102
2103 Here is an example of using the C<inflateInit> optional parameter to
2104 override the default buffer size.
2105
2106     inflateInit( -Bufsize => 300 ) ;
2107
2108 =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
2109
2110 Inflates the complete contents of C<$buffer>. The buffer can either be
2111 a scalar or a scalar reference.
2112
2113 Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
2114 compressed data has been successfully reached. 
2115 If not successful, C<$out> will be I<undef> and C<$status> will hold
2116 the I<zlib> error code.
2117
2118 The C<$buffer> parameter is modified by C<inflate>. On completion it
2119 will contain what remains of the input buffer after inflation. This
2120 means that C<$buffer> will be an empty string when the return status is
2121 C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
2122 parameter will contains what (if anything) was stored in the input
2123 buffer after the deflated data stream.
2124
2125 This feature is useful when processing a file format that encapsulates
2126 a  compressed data stream (e.g. gzip, zip).
2127
2128 =head2 B<$status = $i-E<gt>inflateSync($buffer)>
2129
2130 Scans C<$buffer> until it reaches either a I<full flush point> or the
2131 end of the buffer.
2132
2133 If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
2134 will be have all data up to the flush point removed. This can then be
2135 passed to the C<deflate> method.
2136
2137 Any other return code means that a flush point was not found. If more
2138 data is available, C<inflateSync> can be called repeatedly with more
2139 compressed data until the flush point is found.
2140
2141
2142 =head2 B<$i-E<gt>dict_adler()>
2143
2144 Returns the adler32 value for the dictionary.
2145
2146 =head2 B<$i-E<gt>msg()>
2147
2148 Returns the last error message generated by zlib.
2149
2150 =head2 B<$i-E<gt>total_in()>
2151
2152 Returns the total number of bytes compressed bytes input to inflate.
2153
2154 =head2 B<$i-E<gt>total_out()>
2155
2156 Returns the total number of uncompressed bytes output from inflate.
2157
2158 =head2 Example
2159
2160 Here is an example of using C<inflate>.
2161
2162     use strict ;
2163     use warnings ;
2164     
2165     use Compress::Zlib ;
2166     
2167     my $x = inflateInit()
2168        or die "Cannot create a inflation stream\n" ;
2169     
2170     my $input = '' ;
2171     binmode STDIN;
2172     binmode STDOUT;
2173     
2174     my ($output, $status) ;
2175     while (read(STDIN, $input, 4096))
2176     {
2177         ($output, $status) = $x->inflate(\$input) ;
2178     
2179         print $output 
2180             if $status == Z_OK or $status == Z_STREAM_END ;
2181     
2182         last if $status != Z_OK ;
2183     }
2184     
2185     die "inflation failed\n"
2186         unless $status == Z_STREAM_END ;
2187
2188 =head1 ACCESSING ZIP FILES
2189
2190 Although it is possible (with some effort on your part) to use this
2191 module to access .zip files, there is a module on CPAN that will do all
2192 the hard work for you. Check out the C<Archive::Zip> module on CPAN at
2193
2194     http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz    
2195
2196
2197 =head1 CONSTANTS
2198
2199 All the I<zlib> constants are automatically imported when you make use
2200 of I<Compress::Zlib>.
2201
2202
2203 =head1 SEE ALSO
2204
2205 L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, L<IO::Compress::RawDeflate>, L<IO::Uncompress::RawInflate>, L<IO::Uncompress::AnyInflate>
2206
2207 L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
2208
2209 L<File::GlobMapper|File::GlobMapper>, L<Archive::Tar|Archive::Zip>,
2210 L<IO::Zlib|IO::Zlib>
2211
2212 For RFC 1950, 1951 and 1952 see 
2213 F<http://www.faqs.org/rfcs/rfc1950.html>,
2214 F<http://www.faqs.org/rfcs/rfc1951.html> and
2215 F<http://www.faqs.org/rfcs/rfc1952.html>
2216
2217 The primary site for the gzip program is F<http://www.gzip.org>.
2218
2219 =head1 AUTHOR
2220
2221 The I<Compress::Zlib> module was written by Paul Marquess,
2222 F<pmqs@cpan.org>. The latest copy of the module can be
2223 found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
2224
2225 The I<zlib> compression library was written by Jean-loup Gailly
2226 F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
2227
2228 The primary site for the I<zlib> compression library is
2229 F<http://www.zlib.org>.
2230
2231 =head1 MODIFICATION HISTORY
2232
2233 See the Changes file.
2234
2235 =head1 COPYRIGHT AND LICENSE
2236  
2237
2238 Copyright (c) 1995-2006 Paul Marquess. All rights reserved.
2239 This program is free software; you can redistribute it and/or
2240 modify it under the same terms as Perl itself.
2241
2242
2243
2244
2245