File Coverage

blib/lib/Compress/Zlib.pm
Criterion Covered Total %
statement 254 257 98.8
branch 125 146 85.6
condition 39 50 78.0
subroutine 40 41 97.5
pod 7 7 100.0
total 465 501 92.8


line stmt bran cond sub pod time code
1              
2             package Compress::Zlib;
3              
4             require 5.006 ;
5             require Exporter;
6 15     15   77134 use Carp ;
  15         29  
  15         1384  
7 15     15   13314 use IO::Handle ;
  15         88456  
  15         902  
8 15     15   109 use Scalar::Util qw(dualvar);
  15         31  
  15         1552  
9              
10 15     15   6146 use IO::Compress::Base::Common 2.219 ;
  15         423  
  15         2697  
11 15     15   7270 use Compress::Raw::Zlib 2.218 ;
  15         64252  
  15         4368  
12 15     15   10963 use IO::Compress::Gzip 2.219 ;
  15         372  
  15         1047  
13 15     15   6970 use IO::Uncompress::Gunzip 2.219 ;
  15         362  
  15         941  
14              
15 15     15   96 use strict ;
  15         64  
  15         400  
16 15     15   67 use warnings ;
  15         52  
  15         735  
17 15     15   81 use bytes ;
  15         31  
  15         94  
18             our ($VERSION, $XS_VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
19              
20             $VERSION = '2.219';
21             $XS_VERSION = $VERSION;
22             $VERSION = eval $VERSION;
23              
24             @ISA = qw(Exporter);
25             # Items to export into callers namespace by default. Note: do not export
26             # names by default without a very good reason. Use EXPORT_OK instead.
27             # Do not simply export all your public functions/methods/constants.
28             @EXPORT = qw(
29             deflateInit inflateInit
30              
31             compress uncompress
32              
33             gzopen $gzerrno
34             );
35              
36             push @EXPORT, @Compress::Raw::Zlib::EXPORT ;
37              
38             @EXPORT_OK = qw(memGunzip memGzip zlib_version);
39             %EXPORT_TAGS = (
40             ALL => \@EXPORT
41             );
42              
43             BEGIN
44             {
45 15     15   3355 *zlib_version = \&Compress::Raw::Zlib::zlib_version;
46             }
47              
48 15     15   109 use constant FLAG_APPEND => 1 ;
  15         30  
  15         1431  
49 15     15   99 use constant FLAG_CRC => 2 ;
  15         31  
  15         955  
50 15     15   91 use constant FLAG_ADLER => 4 ;
  15         28  
  15         878  
51 15     15   91 use constant FLAG_CONSUME_INPUT => 8 ;
  15         29  
  15         47114  
52              
53             our (@my_z_errmsg);
54              
55             @my_z_errmsg = (
56             "need dictionary", # Z_NEED_DICT 2
57             "stream end", # Z_STREAM_END 1
58             "", # Z_OK 0
59             "file error", # Z_ERRNO (-1)
60             "stream error", # Z_STREAM_ERROR (-2)
61             "data error", # Z_DATA_ERROR (-3)
62             "insufficient memory", # Z_MEM_ERROR (-4)
63             "buffer error", # Z_BUF_ERROR (-5)
64             "incompatible version",# Z_VERSION_ERROR(-6)
65             );
66              
67              
68             sub _set_gzerr
69             {
70 455     455   1006 my $value = shift ;
71              
72 455 100 33     1298 if ($value == 0) {
    50          
73 368         699 $Compress::Zlib::gzerrno = 0 ;
74             }
75             elsif ($value == Z_ERRNO() || $value > 2) {
76 0         0 $Compress::Zlib::gzerrno = $! ;
77             }
78             else {
79 87         1084 $Compress::Zlib::gzerrno = dualvar($value+0, $my_z_errmsg[2 - $value]);
80             }
81              
82 455         915 return $value ;
83             }
84              
85             sub _set_gzerr_undef
86             {
87 30     30   189 _set_gzerr(@_);
88 30         163 return undef;
89             }
90              
91             sub _save_gzerr
92             {
93 285     285   615 my $gz = shift ;
94 285         480 my $test_eof = shift ;
95              
96 285   100     1014 my $value = $gz->errorNo() || 0 ;
97 285         927 my $eof = $gz->eof() ;
98              
99 285 100       744 if ($test_eof) {
100             # gzread uses Z_STREAM_END to denote a successful end
101 78 100 100     257 $value = Z_STREAM_END() if $gz->eof() && $value == 0 ;
102             }
103              
104 285         18490 _set_gzerr($value) ;
105             }
106              
107             sub gzopen($$)
108             {
109 78     78 1 763772 my ($file, $mode) = @_ ;
110              
111 78         158 my $gz ;
112 78         408 my %defOpts = (Level => Z_DEFAULT_COMPRESSION(),
113             Strategy => Z_DEFAULT_STRATEGY(),
114             );
115              
116 78         1619 my $writing ;
117 78         355 $writing = ! ($mode =~ /r/i) ;
118 78         376 $writing = ($mode =~ /[wa]/i) ;
119              
120 78 100       427 $defOpts{Level} = $1 if $mode =~ /(\d)/;
121 78 100       584 $defOpts{Strategy} = Z_FILTERED() if $mode =~ /f/i;
122 78 100       455 $defOpts{Strategy} = Z_HUFFMAN_ONLY() if $mode =~ /h/i;
123 78 100       284 $defOpts{Append} = 1 if $mode =~ /a/i;
124              
125 78 100       241 my $infDef = $writing ? 'deflate' : 'inflate';
126 78         205 my @params = () ;
127              
128 78 50 100     431 croak "gzopen: file parameter is not a filehandle or filename"
      33        
      66        
129             unless isaFilehandle $file || isaFilename $file ||
130             (ref $file && ref $file eq 'SCALAR');
131              
132 77 100       402 return undef unless $mode =~ /[rwa]/i ;
133              
134 76         253 _set_gzerr(0) ;
135              
136 76 100       207 if ($writing) {
137 34 50       408 $gz = IO::Compress::Gzip->new($file, Minimal => 1, AutoClose => 1,
138             %defOpts)
139             or $Compress::Zlib::gzerrno = $IO::Compress::Gzip::GzipError;
140             }
141             else {
142 42 50       453 $gz = IO::Uncompress::Gunzip->new($file,
143             Transparent => 1,
144             Append => 0,
145             AutoClose => 1,
146             MultiStream => 1,
147             Strict => 0)
148             or $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
149             }
150              
151             return undef
152 76 50       263 if ! defined $gz ;
153              
154 76         1090 bless [$gz, $infDef], 'Compress::Zlib::gzFile';
155             }
156              
157             sub Compress::Zlib::gzFile::gzread
158             {
159 42     42   2211 my $self = shift ;
160              
161 42 100       186 return _set_gzerr(Z_STREAM_ERROR())
162             if $self->[1] ne 'inflate';
163              
164 41 100       152 my $len = defined $_[1] ? $_[1] : 4096 ;
165              
166 41         71 my $gz = $self->[0] ;
167 41 100 100     128 if ($self->gzeof() || $len == 0) {
168             # Zap the output buffer to match ver 1 behaviour.
169 13         54 $_[0] = "" ;
170 13         71 _save_gzerr($gz, 1);
171 13         64 return 0 ;
172             }
173              
174 28         131 my $status = $gz->read($_[0], $len) ;
175 28         101 _save_gzerr($gz, 1);
176 28         215 return $status ;
177             }
178              
179             sub Compress::Zlib::gzFile::gzreadline
180             {
181 37     37   760 my $self = shift ;
182              
183 37         74 my $gz = $self->[0] ;
184             {
185             # Maintain backward compatibility with 1.x behaviour
186             # It didn't support $/, so this can't either.
187 37         59 local $/ = "\n" ;
  37         161  
188 37         154 $_[0] = $gz->getline() ;
189             }
190 37         146 _save_gzerr($gz, 1);
191 37 100       203 return defined $_[0] ? length $_[0] : 0 ;
192             }
193              
194             sub Compress::Zlib::gzFile::gzwrite
195             {
196 38     38   1837 my $self = shift ;
197 38         137 my $gz = $self->[0] ;
198              
199 38 100       160 return _set_gzerr(Z_STREAM_ERROR())
200             if $self->[1] ne 'deflate';
201              
202 37 50 66     423 $] >= 5.008 and (utf8::downgrade($_[0], 1)
203             or croak "Wide character in gzwrite");
204              
205 36         228 my $status = $gz->write($_[0]) ;
206 36         131 _save_gzerr($gz);
207 36         255 return $status ;
208             }
209              
210             sub Compress::Zlib::gzFile::gztell
211             {
212 16     16   41 my $self = shift ;
213 16         34 my $gz = $self->[0] ;
214 16         86 my $status = $gz->tell() ;
215 16         57 _save_gzerr($gz);
216 16         92 return $status ;
217             }
218              
219             sub Compress::Zlib::gzFile::gzseek
220             {
221 11     11   1445 my $self = shift ;
222 11         23 my $offset = shift ;
223 11         19 my $whence = shift ;
224              
225 11         26 my $gz = $self->[0] ;
226 11         17 my $status ;
227 11         21 eval { local $SIG{__DIE__}; $status = $gz->seek($offset, $whence) ; };
  11         54  
  11         83  
228 11 100       45 if ($@)
229             {
230 5         13 my $error = $@;
231 5         37 $error =~ s/^.*: /gzseek: /;
232 5         36 $error =~ s/ at .* line \d+\s*$//;
233 5         762 croak $error;
234             }
235 6         20 _save_gzerr($gz);
236 6         35 return $status ;
237             }
238              
239             sub Compress::Zlib::gzFile::gzflush
240             {
241 7     7   1488 my $self = shift ;
242 7         18 my $f = shift ;
243              
244 7         17 my $gz = $self->[0] ;
245 7         58 my $status = $gz->flush($f) ;
246 7         23 my $err = _save_gzerr($gz);
247 7 100       52 return $status ? 0 : $err;
248             }
249              
250             sub Compress::Zlib::gzFile::gzclose
251             {
252 66     66   955 my $self = shift ;
253 66         154 my $gz = $self->[0] ;
254              
255 66         468 my $status = $gz->close() ;
256 66         217 my $err = _save_gzerr($gz);
257 66 50       480 return $status ? 0 : $err;
258             }
259              
260             sub Compress::Zlib::gzFile::gzeof
261             {
262 76     76   2960 my $self = shift ;
263 76         153 my $gz = $self->[0] ;
264              
265 76 100       270 return 0
266             if $self->[1] ne 'inflate';
267              
268 75         348 my $status = $gz->eof() ;
269 75         275 _save_gzerr($gz);
270 75         1071 return $status ;
271             }
272              
273             sub Compress::Zlib::gzFile::gzsetparams
274             {
275 3     3   404 my $self = shift ;
276 3 100       258 croak "Usage: Compress::Zlib::gzFile::gzsetparams(file, level, strategy)"
277             unless @_ eq 2 ;
278              
279 2         5 my $gz = $self->[0] ;
280 2         6 my $level = shift ;
281 2         4 my $strategy = shift;
282              
283 2 100       13 return _set_gzerr(Z_STREAM_ERROR())
284             if $self->[1] ne 'deflate';
285              
286 1         9 my $status = *$gz->{Compress}->deflateParams(-Level => $level,
287             -Strategy => $strategy);
288 1         6 _save_gzerr($gz);
289 1         4 return $status ;
290             }
291              
292             sub Compress::Zlib::gzFile::gzerror
293             {
294 4     4   18 my $self = shift ;
295 4         8 my $gz = $self->[0] ;
296              
297 4         21 return $Compress::Zlib::gzerrno ;
298             }
299              
300              
301             sub compress($;$)
302             {
303 10     10 1 273715 my ($x, $output, $err, $in) =('', '', '', '') ;
304              
305 10 100       36 if (ref $_[0] ) {
306 3         7 $in = $_[0] ;
307 3 100       242 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
308             }
309             else {
310 7         40 $in = \$_[0] ;
311             }
312              
313 9 50 66     205 $] >= 5.008 and (utf8::downgrade($$in, 1)
314             or croak "Wide character in compress");
315              
316 8 100       40 my $level = (@_ == 2 ? $_[1] : Z_DEFAULT_COMPRESSION() );
317              
318 8 100       36 $x = Compress::Raw::Zlib::_deflateInit(FLAG_APPEND,
319             $level,
320             Z_DEFLATED,
321             MAX_WBITS,
322             MAX_MEM_LEVEL,
323             Z_DEFAULT_STRATEGY,
324             4096,
325             '')
326             or return undef ;
327              
328 7         1308 $err = $x->deflate($in, $output) ;
329 7 50       52 return undef unless $err == Z_OK() ;
330              
331 7         343 $err = $x->flush($output) ;
332 7 50       27 return undef unless $err == Z_OK() ;
333              
334 7         529 return $output ;
335             }
336              
337             sub uncompress($)
338             {
339 10     10 1 3916 my ($output, $in) =('', '') ;
340              
341 10 100       40 if (ref $_[0] ) {
342 4         8 $in = $_[0] ;
343 4 100       144 croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
344             }
345             else {
346 6         17 $in = \$_[0] ;
347             }
348              
349 9 50 66     240 $] >= 5.008 and (utf8::downgrade($$in, 1)
350             or croak "Wide character in uncompress");
351              
352 8         108 my ($obj, $status) = Compress::Raw::Zlib::_inflateInit(0,
353             MAX_WBITS, 4096, "") ;
354              
355 8 50       185 $status == Z_OK
356             or return undef;
357              
358 8 100       139 $obj->inflate($in, $output) == Z_STREAM_END
359             or return undef;
360              
361 7         153 return $output;
362             }
363              
364             sub deflateInit(@)
365             {
366 19     19 1 14120 my ($got) = ParseParameters(0,
367             {
368             'bufsize' => [IO::Compress::Base::Common::Parse_unsigned, 4096],
369             'level' => [IO::Compress::Base::Common::Parse_signed, Z_DEFAULT_COMPRESSION()],
370             'method' => [IO::Compress::Base::Common::Parse_unsigned, Z_DEFLATED()],
371             'windowbits' => [IO::Compress::Base::Common::Parse_signed, MAX_WBITS()],
372             'memlevel' => [IO::Compress::Base::Common::Parse_unsigned, MAX_MEM_LEVEL()],
373             'strategy' => [IO::Compress::Base::Common::Parse_unsigned, Z_DEFAULT_STRATEGY()],
374             'dictionary' => [IO::Compress::Base::Common::Parse_any, ""],
375             }, @_ ) ;
376              
377 15 100       150 croak "Compress::Zlib::deflateInit: Bufsize must be >= 1, you specified " .
378             $got->getValue('bufsize')
379             unless $got->getValue('bufsize') >= 1;
380              
381 14         25 my $obj ;
382              
383 14         28 my $status = 0 ;
384 14         43 ($obj, $status) =
385             Compress::Raw::Zlib::_deflateInit(0,
386             $got->getValue('level'),
387             $got->getValue('method'),
388             $got->getValue('windowbits'),
389             $got->getValue('memlevel'),
390             $got->getValue('strategy'),
391             $got->getValue('bufsize'),
392             $got->getValue('dictionary')) ;
393              
394 14 50       126 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldDeflate" : undef) ;
395 14 100       404 return wantarray ? ($x, $status) : $x ;
396             }
397              
398             sub inflateInit(@)
399             {
400 17     17 1 23914 my ($got) = ParseParameters(0,
401             {
402             'bufsize' => [IO::Compress::Base::Common::Parse_unsigned, 4096],
403             'windowbits' => [IO::Compress::Base::Common::Parse_signed, MAX_WBITS()],
404             'dictionary' => [IO::Compress::Base::Common::Parse_any, ""],
405             }, @_) ;
406              
407              
408 13 100       83 croak "Compress::Zlib::inflateInit: Bufsize must be >= 1, you specified " .
409             $got->getValue('bufsize')
410             unless $got->getValue('bufsize') >= 1;
411              
412 12         25 my $status = 0 ;
413 12         21 my $obj ;
414 12         56 ($obj, $status) = Compress::Raw::Zlib::_inflateInit(FLAG_CONSUME_INPUT,
415             $got->getValue('windowbits'),
416             $got->getValue('bufsize'),
417             $got->getValue('dictionary')) ;
418              
419 12 50       74 my $x = ($status == Z_OK() ? bless $obj, "Zlib::OldInflate" : undef) ;
420              
421 12 100       297 wantarray ? ($x, $status) : $x ;
422             }
423              
424             package Zlib::OldDeflate ;
425              
426             our (@ISA);
427             @ISA = qw(Compress::Raw::Zlib::deflateStream);
428              
429              
430             sub deflate
431             {
432 91     91   9142 my $self = shift ;
433 91         131 my $output ;
434              
435 91         3487 my $status = $self->SUPER::deflate($_[0], $output) ;
436 91 100       354 wantarray ? ($output, $status) : $output ;
437             }
438              
439             sub flush
440             {
441 17     17   3692 my $self = shift ;
442 17         34 my $output ;
443 17   66     100 my $flag = shift || Compress::Zlib::Z_FINISH();
444 17         1086 my $status = $self->SUPER::flush($output, $flag) ;
445              
446 17 100       146 wantarray ? ($output, $status) : $output ;
447             }
448              
449             package Zlib::OldInflate ;
450              
451             our (@ISA);
452             @ISA = qw(Compress::Raw::Zlib::inflateStream);
453              
454             sub inflate
455             {
456 151     151   5812 my $self = shift ;
457 151         230 my $output ;
458 151         1805 my $status = $self->SUPER::inflate($_[0], $output) ;
459 151 100       772 wantarray ? ($output, $status) : $output ;
460             }
461              
462             package Compress::Zlib ;
463              
464 15     15   144 use IO::Compress::Gzip::Constants 2.219 ;
  15         367  
  15         20756  
465              
466             sub memGzip($)
467             {
468 6     6 1 220967 _set_gzerr(0);
469 6 50       37 my $x = Compress::Raw::Zlib::_deflateInit(FLAG_APPEND|FLAG_CRC,
470             Z_BEST_COMPRESSION,
471             Z_DEFLATED,
472             -MAX_WBITS(),
473             MAX_MEM_LEVEL,
474             Z_DEFAULT_STRATEGY,
475             4096,
476             '')
477             or return undef ;
478              
479             # if the deflation buffer isn't a reference, make it one
480 6 100       951 my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
481              
482 6 50 66     388 $] >= 5.008 and (utf8::downgrade($$string, 1)
483             or croak "Wide character in memGzip");
484              
485 5         16 my $out;
486             my $status ;
487              
488 5 50       962 $x->deflate($string, $out) == Z_OK
489             or return undef ;
490              
491 5 50       413 $x->flush($out) == Z_OK
492             or return undef ;
493              
494 5         312 return IO::Compress::Gzip::Constants::GZIP_MINIMUM_HEADER .
495             $out .
496             pack("V V", $x->crc32(), $x->total_in());
497             }
498              
499              
500             sub _removeGzipHeader($)
501             {
502 54     54   113 my $string = shift ;
503              
504 54 100       163 return Z_DATA_ERROR()
505             if length($$string) < GZIP_MIN_HEADER_SIZE ;
506              
507 53         277 my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) =
508             unpack ('CCCCVCC', $$string);
509              
510 53 100 100     429 return Z_DATA_ERROR()
      100        
      100        
511             unless $magic1 == GZIP_ID1 and $magic2 == GZIP_ID2 and
512             $method == Z_DEFLATED() and !($flags & GZIP_FLG_RESERVED) ;
513 44         368 substr($$string, 0, GZIP_MIN_HEADER_SIZE) = '' ;
514              
515             # skip extra field
516 44 100       121 if ($flags & GZIP_FLG_FEXTRA)
517             {
518 4 100       17 return Z_DATA_ERROR()
519             if length($$string) < GZIP_FEXTRA_HEADER_SIZE ;
520              
521 3         9 my ($extra_len) = unpack ('v', $$string);
522 3         6 $extra_len += GZIP_FEXTRA_HEADER_SIZE;
523 3 100       15 return Z_DATA_ERROR()
524             if length($$string) < $extra_len ;
525              
526 1         4 substr($$string, 0, $extra_len) = '';
527             }
528              
529             # skip orig name
530 41 100       92 if ($flags & GZIP_FLG_FNAME)
531             {
532 5         15 my $name_end = index ($$string, GZIP_NULL_BYTE);
533 5 100       22 return Z_DATA_ERROR()
534             if $name_end == -1 ;
535 1         3 substr($$string, 0, $name_end + 1) = '';
536             }
537              
538             # skip comment
539 37 100       79 if ($flags & GZIP_FLG_FCOMMENT)
540             {
541 8         20 my $comment_end = index ($$string, GZIP_NULL_BYTE);
542 8 100       32 return Z_DATA_ERROR()
543             if $comment_end == -1 ;
544 1         4 substr($$string, 0, $comment_end + 1) = '';
545             }
546              
547             # skip header crc
548 30 100       69 if ($flags & GZIP_FLG_FHCRC)
549             {
550 3 100       17 return Z_DATA_ERROR()
551             if length ($$string) < GZIP_FHCRC_SIZE ;
552 1         3 substr($$string, 0, GZIP_FHCRC_SIZE) = '';
553             }
554              
555 28         94 return Z_OK();
556             }
557              
558             sub _ret_gun_error
559             {
560 0     0   0 $Compress::Zlib::gzerrno = $IO::Uncompress::Gunzip::GunzipError;
561 0         0 return undef;
562             }
563              
564              
565             sub memGunzip($)
566             {
567             # if the buffer isn't a reference, make it one
568 55 100   55 1 13776 my $string = (ref $_[0] ? $_[0] : \$_[0]);
569              
570 55 50 66     491 $] >= 5.008 and (utf8::downgrade($$string, 1)
571             or croak "Wide character in memGunzip");
572              
573 54         178 _set_gzerr(0);
574              
575 54         139 my $status = _removeGzipHeader($string) ;
576 54 100       366 $status == Z_OK()
577             or return _set_gzerr_undef($status);
578              
579 28 100       150 my $bufsize = length $$string > 4096 ? length $$string : 4096 ;
580 28 50       69 my $x = Compress::Raw::Zlib::_inflateInit(FLAG_CRC | FLAG_CONSUME_INPUT,
581             -MAX_WBITS(), $bufsize, '')
582             or return _ret_gun_error();
583              
584 28         529 my $output = '' ;
585 28         383 $status = $x->inflate($string, $output);
586              
587 28 100       87 if ( $status == Z_OK() )
588             {
589 1         12 _set_gzerr(Z_DATA_ERROR());
590 1         9 return undef;
591             }
592              
593 27 50       170 return _ret_gun_error()
594             if ($status != Z_STREAM_END());
595              
596 27 100       231 if (length $$string >= 8)
597             {
598 11         50 my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
599 11         28 substr($$string, 0, 8) = '';
600 11 100 100     180 return _set_gzerr_undef(Z_DATA_ERROR())
601             unless $len == length($output) and
602             $crc == Compress::Raw::Zlib::crc32($output);
603             }
604             else
605             {
606 16         38 $$string = '';
607             }
608              
609 23         201 return $output;
610             }
611              
612             # Autoload methods go after __END__, and are processed by the autosplit program.
613              
614             1;
615             __END__
616              
617              
618             =head1 NAME
619              
620             Compress::Zlib - Interface to zlib compression library
621              
622             =head1 SYNOPSIS
623              
624             use Compress::Zlib ;
625              
626             ($d, $status) = deflateInit( [OPT] ) ;
627             $status = $d->deflate($input, $output) ;
628             $status = $d->flush([$flush_type]) ;
629             $d->deflateParams(OPTS) ;
630             $d->deflateTune(OPTS) ;
631             $d->dict_adler() ;
632             $d->crc32() ;
633             $d->adler32() ;
634             $d->total_in() ;
635             $d->total_out() ;
636             $d->msg() ;
637             $d->get_Strategy();
638             $d->get_Level();
639             $d->get_BufSize();
640              
641             ($i, $status) = inflateInit( [OPT] ) ;
642             $status = $i->inflate($input, $output [, $eof]) ;
643             $status = $i->inflateSync($input) ;
644             $i->dict_adler() ;
645             $d->crc32() ;
646             $d->adler32() ;
647             $i->total_in() ;
648             $i->total_out() ;
649             $i->msg() ;
650             $d->get_BufSize();
651              
652             $dest = compress($source) ;
653             $dest = uncompress($source) ;
654              
655             $gz = gzopen($filename or filehandle, $mode) ;
656             $bytesread = $gz->gzread($buffer [,$size]) ;
657             $bytesread = $gz->gzreadline($line) ;
658             $byteswritten = $gz->gzwrite($buffer) ;
659             $status = $gz->gzflush($flush) ;
660             $offset = $gz->gztell() ;
661             $status = $gz->gzseek($offset, $whence) ;
662             $status = $gz->gzclose() ;
663             $status = $gz->gzeof() ;
664             $status = $gz->gzsetparams($level, $strategy) ;
665             $errstring = $gz->gzerror() ;
666             $gzerrno
667              
668             $dest = Compress::Zlib::memGzip($buffer) ;
669             $dest = Compress::Zlib::memGunzip($buffer) ;
670              
671             $crc = adler32($buffer [,$crc]) ;
672             $crc = crc32($buffer [,$crc]) ;
673              
674             $crc = crc32_combine($crc1, $crc2, $len2);
675             $adler = adler32_combine($adler1, $adler2, $len2);
676              
677             my $version = Compress::Raw::Zlib::zlib_version();
678              
679             =head1 DESCRIPTION
680              
681             The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
682             compression library (see L</AUTHOR> for details about where to get
683             I<zlib>).
684              
685             The C<Compress::Zlib> module can be split into two general areas of
686             functionality, namely a simple read/write interface to I<gzip> files
687             and a low-level in-memory compression/decompression interface.
688              
689             Each of these areas will be discussed in the following sections.
690              
691             =head2 Notes for users of Compress::Zlib version 1
692              
693             The main change in C<Compress::Zlib> version 2.x is that it does not now
694             interface directly to the zlib library. Instead it uses the
695             C<IO::Compress::Gzip> and C<IO::Uncompress::Gunzip> modules for
696             reading/writing gzip files, and the C<Compress::Raw::Zlib> module for some
697             low-level zlib access.
698              
699             The interface provided by version 2 of this module should be 100% backward
700             compatible with version 1. If you find a difference in the expected
701             behaviour please contact the author (See L</AUTHOR>). See L<GZIP INTERFACE>
702              
703             With the creation of the C<IO::Compress> and C<IO::Uncompress> modules no
704             new features are planned for C<Compress::Zlib> - the new modules do
705             everything that C<Compress::Zlib> does and then some. Development on
706             C<Compress::Zlib> will be limited to bug fixes only.
707              
708             If you are writing new code, your first port of call should be one of the
709             new C<IO::Compress> or C<IO::Uncompress> modules.
710              
711             =head1 GZIP INTERFACE
712              
713             A number of functions are supplied in I<zlib> for reading and writing
714             I<gzip> files that conform to RFC 1952. This module provides an interface
715             to most of them.
716              
717             If you have previously used C<Compress::Zlib> 1.x, the following
718             enhancements/changes have been made to the C<gzopen> interface:
719              
720             =over 5
721              
722             =item 1
723              
724             If you want to open either STDIN or STDOUT with C<gzopen>, you can now
725             optionally use the special filename "C<->" as a synonym for C<\*STDIN> and
726             C<\*STDOUT>.
727              
728             =item 2
729              
730             In C<Compress::Zlib> version 1.x, C<gzopen> used the zlib library to open
731             the underlying file. This made things especially tricky when a Perl
732             filehandle was passed to C<gzopen>. Behind the scenes the numeric C file
733             descriptor had to be extracted from the Perl filehandle and this passed to
734             the zlib library.
735              
736             Apart from being non-portable to some operating systems, this made it
737             difficult to use C<gzopen> in situations where you wanted to extract/create
738             a gzip data stream that is embedded in a larger file, without having to
739             resort to opening and closing the file multiple times.
740              
741             It also made it impossible to pass a perl filehandle that wasn't associated
742             with a real filesystem file, like, say, an C<IO::String>.
743              
744             In C<Compress::Zlib> version 2.x, the C<gzopen> interface has been
745             completely rewritten to use the L<IO::Compress::Gzip|IO::Compress::Gzip>
746             for writing gzip files and L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>
747             for reading gzip files. None of the limitations mentioned above apply.
748              
749             =item 3
750              
751             Addition of C<gzseek> to provide a restricted C<seek> interface.
752              
753             =item 4.
754              
755             Added C<gztell>.
756              
757             =back
758              
759             A more complete and flexible interface for reading/writing gzip
760             files/buffers is included with the module C<IO-Compress-Zlib>. See
761             L<IO::Compress::Gzip|IO::Compress::Gzip> and
762             L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for more details.
763              
764             =over 5
765              
766             =item B<$gz = gzopen($filename, $mode)>
767              
768             =item B<$gz = gzopen($filehandle, $mode)>
769              
770             This function opens either the I<gzip> file C<$filename> for reading or
771             writing or attaches to the opened filehandle, C<$filehandle>.
772             It returns an object on success and C<undef> on failure.
773              
774             When writing a gzip file this interface will I<always> create the smallest
775             possible gzip header (exactly 10 bytes). If you want greater control over
776             what gets stored in the gzip header (like the original filename or a
777             comment) use L<IO::Compress::Gzip|IO::Compress::Gzip> instead. Similarly if
778             you want to read the contents of the gzip header use
779             L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>.
780              
781             The second parameter, C<$mode>, is used to specify whether the file is
782             opened for reading or writing and to optionally specify a compression
783             level and compression strategy when writing. The format of the C<$mode>
784             parameter is similar to the mode parameter to the 'C' function C<fopen>,
785             so "rb" is used to open for reading, "wb" for writing and "ab" for
786             appending (writing at the end of the file).
787              
788             To specify a compression level when writing, append a digit between 0
789             and 9 to the mode string -- 0 means no compression and 9 means maximum
790             compression.
791             If no compression level is specified Z_DEFAULT_COMPRESSION is used.
792              
793             To specify the compression strategy when writing, append 'f' for filtered
794             data, 'h' for Huffman only compression, or 'R' for run-length encoding.
795             If no strategy is specified Z_DEFAULT_STRATEGY is used.
796              
797             So, for example, "wb9" means open for writing with the maximum compression
798             using the default strategy and "wb4R" means open for writing with compression
799             level 4 and run-length encoding.
800              
801             Refer to the I<zlib> documentation for the exact format of the C<$mode>
802             parameter.
803              
804             =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
805              
806             Reads C<$size> bytes from the compressed file into C<$buffer>. If
807             C<$size> is not specified, it will default to 4096. If the scalar
808             C<$buffer> is not large enough, it will be extended automatically.
809              
810             Returns the number of bytes actually read. On EOF it returns 0 and in
811             the case of an error, -1.
812              
813             =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
814              
815             Reads the next line from the compressed file into C<$line>.
816              
817             Returns the number of bytes actually read. On EOF it returns 0 and in
818             the case of an error, -1.
819              
820             It is legal to intermix calls to C<gzread> and C<gzreadline>.
821              
822             To maintain backward compatibility with version 1.x of this module
823             C<gzreadline> ignores the C<$/> variable - it I<always> uses the string
824             C<"\n"> as the line delimiter.
825              
826             If you want to read a gzip file a line at a time and have it respect the
827             C<$/> variable (or C<$INPUT_RECORD_SEPARATOR>, or C<$RS> when C<English> is
828             in use) see L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip>.
829              
830             =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
831              
832             Writes the contents of C<$buffer> to the compressed file. Returns the
833             number of bytes actually written, or 0 on error.
834              
835             =item B<$status = $gz-E<gt>gzflush($flush_type) ;>
836              
837             Flushes all pending output into the compressed file.
838              
839             This method takes an optional parameter, C<$flush_type>, that controls
840             how the flushing will be carried out. By default the C<$flush_type>
841             used is C<Z_FINISH>. Other valid values for C<$flush_type> are
842             C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is
843             strongly recommended that you only set the C<flush_type> parameter if
844             you fully understand the implications of what it does - overuse of C<flush>
845             can seriously degrade the level of compression achieved. See the C<zlib>
846             documentation for details.
847              
848             Returns 0 on success.
849              
850             =item B<$offset = $gz-E<gt>gztell() ;>
851              
852             Returns the uncompressed file offset.
853              
854             =item B<$status = $gz-E<gt>gzseek($offset, $whence) ;>
855              
856             Provides a sub-set of the C<seek> functionality, with the restriction
857             that it is only legal to seek forward in the compressed file.
858             It is a fatal error to attempt to seek backward.
859              
860             When opened for writing, empty parts of the file will have NULL (0x00)
861             bytes written to them.
862              
863             The C<$whence> parameter should be one of SEEK_SET, SEEK_CUR or SEEK_END.
864              
865             Returns 1 on success, 0 on failure.
866              
867             =item B<$gz-E<gt>gzclose>
868              
869             Closes the compressed file. Any pending data is flushed to the file
870             before it is closed.
871              
872             Returns 0 on success.
873              
874             =item B<$gz-E<gt>gzsetparams($level, $strategy>
875              
876             Change settings for the deflate stream C<$gz>.
877              
878             The list of the valid options is shown below. Options not specified
879             will remain unchanged.
880              
881             Note: This method is only available if you are running zlib 1.0.6 or better.
882              
883             =over 5
884              
885             =item B<$level>
886              
887             Defines the compression level. Valid values are 0 through 9,
888             C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
889             C<Z_DEFAULT_COMPRESSION>.
890              
891             =item B<$strategy>
892              
893             Defines the strategy used to tune the compression. The valid values are
894             C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
895              
896             =back
897              
898             =item B<$gz-E<gt>gzerror>
899              
900             Returns the I<zlib> error message or number for the last operation
901             associated with C<$gz>. The return value will be the I<zlib> error
902             number when used in a numeric context and the I<zlib> error message
903             when used in a string context. The I<zlib> error number constants,
904             shown below, are available for use.
905              
906             Z_OK
907             Z_STREAM_END
908             Z_ERRNO
909             Z_STREAM_ERROR
910             Z_DATA_ERROR
911             Z_MEM_ERROR
912             Z_BUF_ERROR
913              
914             =item B<$gzerrno>
915              
916             The C<$gzerrno> scalar holds the error code associated with the most
917             recent I<gzip> routine. Note that unlike C<gzerror()>, the error is
918             I<not> associated with a particular file.
919              
920             As with C<gzerror()> it returns an error number in numeric context and
921             an error message in string context. Unlike C<gzerror()> though, the
922             error message will correspond to the I<zlib> message when the error is
923             associated with I<zlib> itself, or the UNIX error message when it is
924             not (i.e. I<zlib> returned C<Z_ERRORNO>).
925              
926             As there is an overlap between the error numbers used by I<zlib> and
927             UNIX, C<$gzerrno> should only be used to check for the presence of
928             I<an> error in numeric context. Use C<gzerror()> to check for specific
929             I<zlib> errors. The I<gzcat> example below shows how the variable can
930             be used safely.
931              
932             =back
933              
934             =head2 Examples
935              
936             Here is an example script which uses the interface. It implements a
937             I<gzcat> function.
938              
939             use strict ;
940             use warnings ;
941              
942             use Compress::Zlib ;
943              
944             # use stdin if no files supplied
945             @ARGV = '-' unless @ARGV ;
946              
947             foreach my $file (@ARGV) {
948             my $buffer ;
949              
950             my $gz = gzopen($file, "rb")
951             or die "Cannot open $file: $gzerrno\n" ;
952              
953             print $buffer while $gz->gzread($buffer) > 0 ;
954              
955             die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n"
956             if $gzerrno != Z_STREAM_END ;
957              
958             $gz->gzclose() ;
959             }
960              
961             Below is a script which makes use of C<gzreadline>. It implements a
962             very simple I<grep> like script.
963              
964             use strict ;
965             use warnings ;
966              
967             use Compress::Zlib ;
968              
969             die "Usage: gzgrep pattern [file...]\n"
970             unless @ARGV >= 1;
971              
972             my $pattern = shift ;
973              
974             # use stdin if no files supplied
975             @ARGV = '-' unless @ARGV ;
976              
977             foreach my $file (@ARGV) {
978             my $gz = gzopen($file, "rb")
979             or die "Cannot open $file: $gzerrno\n" ;
980              
981             while ($gz->gzreadline($_) > 0) {
982             print if /$pattern/ ;
983             }
984              
985             die "Error reading from $file: $gzerrno\n"
986             if $gzerrno != Z_STREAM_END ;
987              
988             $gz->gzclose() ;
989             }
990              
991             This script, I<gzstream>, does the opposite of the I<gzcat> script
992             above. It reads from standard input and writes a gzip data stream to
993             standard output.
994              
995             use strict ;
996             use warnings ;
997              
998             use Compress::Zlib ;
999              
1000             binmode STDOUT; # gzopen only sets it on the fd
1001              
1002             my $gz = gzopen(\*STDOUT, "wb")
1003             or die "Cannot open stdout: $gzerrno\n" ;
1004              
1005             while (<>) {
1006             $gz->gzwrite($_)
1007             or die "error writing: $gzerrno\n" ;
1008             }
1009              
1010             $gz->gzclose ;
1011              
1012             =head2 Compress::Zlib::memGzip
1013              
1014             This function is used to create an in-memory gzip file with the minimum
1015             possible gzip header (exactly 10 bytes).
1016              
1017             $dest = Compress::Zlib::memGzip($buffer)
1018             or die "Cannot compress: $gzerrno\n";
1019              
1020             If successful, it returns the in-memory gzip file. Otherwise it returns
1021             C<undef> and the C<$gzerrno> variable will store the zlib error code.
1022              
1023             The C<$buffer> parameter can either be a scalar or a scalar reference.
1024              
1025             See L<IO::Compress::Gzip|IO::Compress::Gzip> for an alternative way to
1026             carry out in-memory gzip compression.
1027              
1028             =head2 Compress::Zlib::memGunzip
1029              
1030             This function is used to uncompress an in-memory gzip file.
1031              
1032             $dest = Compress::Zlib::memGunzip($buffer)
1033             or die "Cannot uncompress: $gzerrno\n";
1034              
1035             If successful, it returns the uncompressed gzip file. Otherwise it
1036             returns C<undef> and the C<$gzerrno> variable will store the zlib error
1037             code.
1038              
1039             The C<$buffer> parameter can either be a scalar or a scalar reference. The
1040             contents of the C<$buffer> parameter are destroyed after calling this function.
1041              
1042             If C<$buffer> consists of multiple concatenated gzip data streams only the
1043             first will be uncompressed. Use C<gunzip> with the C<MultiStream> option in
1044             the C<IO::Uncompress::Gunzip> module if you need to deal with concatenated
1045             data streams.
1046              
1047             See L<IO::Uncompress::Gunzip|IO::Uncompress::Gunzip> for an alternative way
1048             to carry out in-memory gzip uncompression.
1049              
1050             =head1 COMPRESS/UNCOMPRESS
1051              
1052             Two functions are provided to perform in-memory compression/uncompression of
1053             RFC 1950 data streams. They are called C<compress> and C<uncompress>.
1054              
1055             =over 5
1056              
1057             =item B<$dest = compress($source [, $level] ) ;>
1058              
1059             Compresses C<$source>. If successful it returns the compressed
1060             data. Otherwise it returns I<undef>.
1061              
1062             The source buffer, C<$source>, can either be a scalar or a scalar
1063             reference.
1064              
1065             The C<$level> parameter defines the compression level. Valid values are
1066             0 through 9, C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>,
1067             C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
1068             If C<$level> is not specified C<Z_DEFAULT_COMPRESSION> will be used.
1069              
1070             =item B<$dest = uncompress($source) ;>
1071              
1072             Uncompresses C<$source>. If successful it returns the uncompressed
1073             data. Otherwise it returns I<undef>.
1074              
1075             The source buffer can either be a scalar or a scalar reference.
1076              
1077             =back
1078              
1079             Please note: the two functions defined above are I<not> compatible with
1080             the Unix commands of the same name.
1081              
1082             See L<IO::Deflate|IO::Deflate> and L<IO::Inflate|IO::Inflate> included with
1083             this distribution for an alternative interface for reading/writing RFC 1950
1084             files/buffers.
1085              
1086             =head1 Deflate Interface
1087              
1088             This section defines an interface that allows in-memory compression using
1089             the I<deflate> interface provided by zlib.
1090              
1091             Here is a definition of the interface available:
1092              
1093             =head2 B<($d, $status) = deflateInit( [OPT] )>
1094              
1095             Initialises a deflation stream.
1096              
1097             It combines the features of the I<zlib> functions C<deflateInit>,
1098             C<deflateInit2> and C<deflateSetDictionary>.
1099              
1100             If successful, it will return the initialised deflation stream, C<$d>
1101             and C<$status> of C<Z_OK> in a list context. In scalar context it
1102             returns the deflation stream, C<$d>, only.
1103              
1104             If not successful, the returned deflation stream (C<$d>) will be
1105             I<undef> and C<$status> will hold the exact I<zlib> error code.
1106              
1107             The function optionally takes a number of named options specified as
1108             C<< -Name=>value >> pairs. This allows individual options to be
1109             tailored without having to specify them all in the parameter list.
1110              
1111             For backward compatibility, it is also possible to pass the parameters
1112             as a reference to a hash containing the name=>value pairs.
1113              
1114             The function takes one optional parameter, a reference to a hash. The
1115             contents of the hash allow the deflation interface to be tailored.
1116              
1117             Here is a list of the valid options:
1118              
1119             =over 5
1120              
1121             =item B<-Level>
1122              
1123             Defines the compression level. Valid values are 0 through 9,
1124             C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1125             C<Z_DEFAULT_COMPRESSION>.
1126              
1127             The default is Z_DEFAULT_COMPRESSION.
1128              
1129             =item B<-Method>
1130              
1131             Defines the compression method. The only valid value at present (and
1132             the default) is Z_DEFLATED.
1133              
1134             =item B<-WindowBits>
1135              
1136             To create an RFC 1950 data stream, set C<WindowBits> to a positive number.
1137              
1138             To create an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1139              
1140             For a full definition of the meaning and valid values for C<WindowBits> refer
1141             to the I<zlib> documentation for I<deflateInit2>.
1142              
1143             Defaults to MAX_WBITS.
1144              
1145             =item B<-MemLevel>
1146              
1147             For a definition of the meaning and valid values for C<MemLevel>
1148             refer to the I<zlib> documentation for I<deflateInit2>.
1149              
1150             Defaults to MAX_MEM_LEVEL.
1151              
1152             =item B<-Strategy>
1153              
1154             Defines the strategy used to tune the compression. The valid values are
1155             C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1156              
1157             The default is Z_DEFAULT_STRATEGY.
1158              
1159             =item B<-Dictionary>
1160              
1161             When a dictionary is specified I<Compress::Zlib> will automatically
1162             call C<deflateSetDictionary> directly after calling C<deflateInit>. The
1163             Adler32 value for the dictionary can be obtained by calling the method
1164             C<< $d->dict_adler() >>.
1165              
1166             The default is no dictionary.
1167              
1168             =item B<-Bufsize>
1169              
1170             Sets the initial size for the deflation buffer. If the buffer has to be
1171             reallocated to increase the size, it will grow in increments of
1172             C<Bufsize>.
1173              
1174             The default is 4096.
1175              
1176             =back
1177              
1178             Here is an example of using the C<deflateInit> optional parameter list
1179             to override the default buffer size and compression level. All other
1180             options will take their default values.
1181              
1182             deflateInit( -Bufsize => 300,
1183             -Level => Z_BEST_SPEED ) ;
1184              
1185             =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
1186              
1187             Deflates the contents of C<$buffer>. The buffer can either be a scalar
1188             or a scalar reference. When finished, C<$buffer> will be
1189             completely processed (assuming there were no errors). If the deflation
1190             was successful it returns the deflated output, C<$out>, and a status
1191             value, C<$status>, of C<Z_OK>.
1192              
1193             On error, C<$out> will be I<undef> and C<$status> will contain the
1194             I<zlib> error code.
1195              
1196             In a scalar context C<deflate> will return C<$out> only.
1197              
1198             As with the I<deflate> function in I<zlib>, it is not necessarily the
1199             case that any output will be produced by this method. So don't rely on
1200             the fact that C<$out> is empty for an error test.
1201              
1202             =head2 B<($out, $status) = $d-E<gt>flush()>
1203             =head2 B<($out, $status) = $d-E<gt>flush($flush_type)>
1204              
1205             Typically used to finish the deflation. Any pending output will be
1206             returned via C<$out>.
1207             C<$status> will have a value C<Z_OK> if successful.
1208              
1209             In a scalar context C<flush> will return C<$out> only.
1210              
1211             Note that flushing can seriously degrade the compression ratio, so it
1212             should only be used to terminate a decompression (using C<Z_FINISH>) or
1213             when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
1214              
1215             By default the C<flush_type> used is C<Z_FINISH>. Other valid values
1216             for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
1217             and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
1218             C<flush_type> parameter if you fully understand the implications of
1219             what it does. See the C<zlib> documentation for details.
1220              
1221             =head2 B<$status = $d-E<gt>deflateParams([OPT])>
1222              
1223             Change settings for the deflate stream C<$d>.
1224              
1225             The list of the valid options is shown below. Options not specified
1226             will remain unchanged.
1227              
1228             =over 5
1229              
1230             =item B<-Level>
1231              
1232             Defines the compression level. Valid values are 0 through 9,
1233             C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
1234             C<Z_DEFAULT_COMPRESSION>.
1235              
1236             =item B<-Strategy>
1237              
1238             Defines the strategy used to tune the compression. The valid values are
1239             C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
1240              
1241             =back
1242              
1243             =head2 B<$d-E<gt>dict_adler()>
1244              
1245             Returns the adler32 value for the dictionary.
1246              
1247             =head2 B<$d-E<gt>msg()>
1248              
1249             Returns the last error message generated by zlib.
1250              
1251             =head2 B<$d-E<gt>total_in()>
1252              
1253             Returns the total number of bytes uncompressed bytes input to deflate.
1254              
1255             =head2 B<$d-E<gt>total_out()>
1256              
1257             Returns the total number of compressed bytes output from deflate.
1258              
1259             =head2 Example
1260              
1261             Here is a trivial example of using C<deflate>. It simply reads standard
1262             input, deflates it and writes it to standard output.
1263              
1264             use strict ;
1265             use warnings ;
1266              
1267             use Compress::Zlib ;
1268              
1269             binmode STDIN;
1270             binmode STDOUT;
1271             my $x = deflateInit()
1272             or die "Cannot create a deflation stream\n" ;
1273              
1274             my ($output, $status) ;
1275             while (<>)
1276             {
1277             ($output, $status) = $x->deflate($_) ;
1278              
1279             $status == Z_OK
1280             or die "deflation failed\n" ;
1281              
1282             print $output ;
1283             }
1284              
1285             ($output, $status) = $x->flush() ;
1286              
1287             $status == Z_OK
1288             or die "deflation failed\n" ;
1289              
1290             print $output ;
1291              
1292             =head1 Inflate Interface
1293              
1294             This section defines the interface available that allows in-memory
1295             uncompression using the I<deflate> interface provided by zlib.
1296              
1297             Here is a definition of the interface:
1298              
1299             =head2 B<($i, $status) = inflateInit()>
1300              
1301             Initialises an inflation stream.
1302              
1303             In a list context it returns the inflation stream, C<$i>, and the
1304             I<zlib> status code in C<$status>. In a scalar context it returns the
1305             inflation stream only.
1306              
1307             If successful, C<$i> will hold the inflation stream and C<$status> will
1308             be C<Z_OK>.
1309              
1310             If not successful, C<$i> will be I<undef> and C<$status> will hold the
1311             I<zlib> error code.
1312              
1313             The function optionally takes a number of named options specified as
1314             C<< -Name=>value >> pairs. This allows individual options to be
1315             tailored without having to specify them all in the parameter list.
1316              
1317             For backward compatibility, it is also possible to pass the parameters
1318             as a reference to a hash containing the name=>value pairs.
1319              
1320             The function takes one optional parameter, a reference to a hash. The
1321             contents of the hash allow the deflation interface to be tailored.
1322              
1323             Here is a list of the valid options:
1324              
1325             =over 5
1326              
1327             =item B<-WindowBits>
1328              
1329             To uncompress an RFC 1950 data stream, set C<WindowBits> to a positive number.
1330              
1331             To uncompress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
1332              
1333             For a full definition of the meaning and valid values for C<WindowBits> refer
1334             to the I<zlib> documentation for I<inflateInit2>.
1335              
1336             Defaults to MAX_WBITS.
1337              
1338             =item B<-Bufsize>
1339              
1340             Sets the initial size for the inflation buffer. If the buffer has to be
1341             reallocated to increase the size, it will grow in increments of
1342             C<Bufsize>.
1343              
1344             Default is 4096.
1345              
1346             =item B<-Dictionary>
1347              
1348             The default is no dictionary.
1349              
1350             =back
1351              
1352             Here is an example of using the C<inflateInit> optional parameter to
1353             override the default buffer size.
1354              
1355             inflateInit( -Bufsize => 300 ) ;
1356              
1357             =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
1358              
1359             Inflates the complete contents of C<$buffer>. The buffer can either be
1360             a scalar or a scalar reference.
1361              
1362             Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1363             compressed data has been successfully reached.
1364             If not successful, C<$out> will be I<undef> and C<$status> will hold
1365             the I<zlib> error code.
1366              
1367             The C<$buffer> parameter is modified by C<inflate>. On completion it
1368             will contain what remains of the input buffer after inflation. This
1369             means that C<$buffer> will be an empty string when the return status is
1370             C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
1371             parameter will contains what (if anything) was stored in the input
1372             buffer after the deflated data stream.
1373              
1374             This feature is useful when processing a file format that encapsulates
1375             a compressed data stream (e.g. gzip, zip).
1376              
1377             =head2 B<$status = $i-E<gt>inflateSync($buffer)>
1378              
1379             Scans C<$buffer> until it reaches either a I<full flush point> or the
1380             end of the buffer.
1381              
1382             If a I<full flush point> is found, C<Z_OK> is returned and C<$buffer>
1383             will be have all data up to the flush point removed. This can then be
1384             passed to the C<deflate> method.
1385              
1386             Any other return code means that a flush point was not found. If more
1387             data is available, C<inflateSync> can be called repeatedly with more
1388             compressed data until the flush point is found.
1389              
1390             =head2 B<$i-E<gt>dict_adler()>
1391              
1392             Returns the adler32 value for the dictionary.
1393              
1394             =head2 B<$i-E<gt>msg()>
1395              
1396             Returns the last error message generated by zlib.
1397              
1398             =head2 B<$i-E<gt>total_in()>
1399              
1400             Returns the total number of bytes compressed bytes input to inflate.
1401              
1402             =head2 B<$i-E<gt>total_out()>
1403              
1404             Returns the total number of uncompressed bytes output from inflate.
1405              
1406             =head2 Example
1407              
1408             Here is an example of using C<inflate>.
1409              
1410             use strict ;
1411             use warnings ;
1412              
1413             use Compress::Zlib ;
1414              
1415             my $x = inflateInit()
1416             or die "Cannot create a inflation stream\n" ;
1417              
1418             my $input = '' ;
1419             binmode STDIN;
1420             binmode STDOUT;
1421              
1422             my ($output, $status) ;
1423             while (read(STDIN, $input, 4096))
1424             {
1425             ($output, $status) = $x->inflate(\$input) ;
1426              
1427             print $output
1428             if $status == Z_OK or $status == Z_STREAM_END ;
1429              
1430             last if $status != Z_OK ;
1431             }
1432              
1433             die "inflation failed\n"
1434             unless $status == Z_STREAM_END ;
1435              
1436             =head1 CHECKSUM FUNCTIONS
1437              
1438             Two functions are provided by I<zlib> to calculate checksums. For the
1439             Perl interface, the order of the two parameters in both functions has
1440             been reversed. This allows both running checksums and one off
1441             calculations to be done.
1442              
1443             $crc = adler32($buffer [,$crc]) ;
1444             $crc = crc32($buffer [,$crc]) ;
1445              
1446             The buffer parameters can either be a scalar or a scalar reference.
1447              
1448             If the $crc parameters is C<undef>, the crc value will be reset.
1449              
1450             If you have built this module with zlib 1.2.3 or better, two more
1451             CRC-related functions are available.
1452              
1453             $crc = crc32_combine($crc1, $crc2, $len2);
1454             $adler = adler32_combine($adler1, $adler2, $len2);
1455              
1456             These functions allow checksums to be merged.
1457             Refer to the I<zlib> documentation for more details.
1458              
1459             =head1 Misc
1460              
1461             =head2 my $version = Compress::Zlib::zlib_version();
1462              
1463             Returns the version of the zlib library.
1464              
1465             =head1 CONSTANTS
1466              
1467             All the I<zlib> constants are automatically imported when you make use
1468             of I<Compress::Zlib>.
1469              
1470             =head1 SUPPORT
1471              
1472             General feedback/questions/bug reports should be sent to
1473             L<https://github.com/pmqs/IO-Compress/issues> (preferred) or
1474             L<https://rt.cpan.org/Public/Dist/Display.html?Name=IO-Compress>.
1475              
1476             =head1 SEE ALSO
1477              
1478             L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, L<IO::Compress::RawDeflate>, L<IO::Uncompress::RawInflate>, L<IO::Compress::Bzip2>, L<IO::Uncompress::Bunzip2>, L<IO::Compress::Lzma>, L<IO::Uncompress::UnLzma>, L<IO::Compress::Xz>, L<IO::Uncompress::UnXz>, L<IO::Compress::Lzip>, L<IO::Uncompress::UnLzip>, L<IO::Compress::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Compress::Zstd>, L<IO::Uncompress::UnZstd>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
1479              
1480             L<IO::Compress::FAQ|IO::Compress::FAQ>
1481              
1482             L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1483             L<Archive::Tar|Archive::Tar>,
1484             L<IO::Zlib|IO::Zlib>
1485              
1486             For RFC 1950, 1951 and 1952 see
1487             L<https://datatracker.ietf.org/doc/html/rfc1950>,
1488             L<https://datatracker.ietf.org/doc/html/rfc1951> and
1489             L<https://datatracker.ietf.org/doc/html/rfc1952>
1490              
1491             The I<zlib> compression library was written by Jean-loup Gailly
1492             C<gzip@prep.ai.mit.edu> and Mark Adler C<madler@alumni.caltech.edu>.
1493              
1494             The primary site for the I<zlib> compression library is
1495             L<http://www.zlib.org>.
1496              
1497             The primary site for the I<zlib-ng> compression library is
1498             L<https://github.com/zlib-ng/zlib-ng>.
1499              
1500             The primary site for gzip is L<http://www.gzip.org>.
1501              
1502             =head1 AUTHOR
1503              
1504             This module was written by Paul Marquess, C<pmqs@cpan.org>.
1505              
1506             =head1 MODIFICATION HISTORY
1507              
1508             See the Changes file.
1509              
1510             =head1 COPYRIGHT AND LICENSE
1511              
1512             Copyright (c) 1995-2026 Paul Marquess. All rights reserved.
1513              
1514             This program is free software; you can redistribute it and/or
1515             modify it under the same terms as Perl itself.