This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update Compress-Raw-Zlib to CPAN version 2.066
[perl5.git] / cpan / Compress-Raw-Zlib / lib / Compress / Raw / Zlib.pm
CommitLineData
25f0751f
PM
1
2package Compress::Raw::Zlib;
3
589c1691 4require 5.006 ;
25f0751f 5require Exporter;
25f0751f
PM
6use Carp ;
7
25f0751f
PM
8use strict ;
9use warnings ;
10use bytes ;
f3d3633e 11our ($VERSION, $XS_VERSION, @ISA, @EXPORT, %EXPORT_TAGS, @EXPORT_OK, $AUTOLOAD, %DEFLATE_CONSTANTS, @DEFLATE_CONSTANTS);
25f0751f 12
1590a345 13$VERSION = '2.066';
25f0751f
PM
14$XS_VERSION = $VERSION;
15$VERSION = eval $VERSION;
16
17@ISA = qw(Exporter);
589c1691
CBW
18%EXPORT_TAGS = ( flush => [qw{
19 Z_NO_FLUSH
20 Z_PARTIAL_FLUSH
21 Z_SYNC_FLUSH
22 Z_FULL_FLUSH
23 Z_FINISH
24 Z_BLOCK
25 }],
26 level => [qw{
27 Z_NO_COMPRESSION
28 Z_BEST_SPEED
29 Z_BEST_COMPRESSION
30 Z_DEFAULT_COMPRESSION
31 }],
32 strategy => [qw{
33 Z_FILTERED
34 Z_HUFFMAN_ONLY
35 Z_RLE
36 Z_FIXED
37 Z_DEFAULT_STRATEGY
38 }],
39 status => [qw{
40 Z_OK
41 Z_STREAM_END
42 Z_NEED_DICT
43 Z_ERRNO
44 Z_STREAM_ERROR
45 Z_DATA_ERROR
46 Z_MEM_ERROR
47 Z_BUF_ERROR
48 Z_VERSION_ERROR
49 }],
50 );
51
52%DEFLATE_CONSTANTS = %EXPORT_TAGS;
53
25f0751f
PM
54# Items to export into callers namespace by default. Note: do not export
55# names by default without a very good reason. Use EXPORT_OK instead.
56# Do not simply export all your public functions/methods/constants.
589c1691 57@DEFLATE_CONSTANTS =
25f0751f 58@EXPORT = qw(
25f0751f
PM
59 ZLIB_VERSION
60 ZLIB_VERNUM
61
589c1691 62
25f0751f
PM
63 OS_CODE
64
65 MAX_MEM_LEVEL
66 MAX_WBITS
67
68 Z_ASCII
69 Z_BEST_COMPRESSION
70 Z_BEST_SPEED
71 Z_BINARY
72 Z_BLOCK
73 Z_BUF_ERROR
74 Z_DATA_ERROR
75 Z_DEFAULT_COMPRESSION
76 Z_DEFAULT_STRATEGY
77 Z_DEFLATED
78 Z_ERRNO
79 Z_FILTERED
80 Z_FIXED
81 Z_FINISH
82 Z_FULL_FLUSH
83 Z_HUFFMAN_ONLY
84 Z_MEM_ERROR
85 Z_NEED_DICT
86 Z_NO_COMPRESSION
87 Z_NO_FLUSH
88 Z_NULL
89 Z_OK
90 Z_PARTIAL_FLUSH
91 Z_RLE
92 Z_STREAM_END
93 Z_STREAM_ERROR
94 Z_SYNC_FLUSH
f02c02ec 95 Z_TREES
25f0751f
PM
96 Z_UNKNOWN
97 Z_VERSION_ERROR
e11a3f9e
PM
98
99 WANT_GZIP
100 WANT_GZIP_OR_ZLIB
25f0751f
PM
101);
102
589c1691
CBW
103push @EXPORT, qw(crc32 adler32 DEF_WBITS);
104
e11a3f9e
PM
105use constant WANT_GZIP => 16;
106use constant WANT_GZIP_OR_ZLIB => 32;
25f0751f
PM
107
108sub AUTOLOAD {
109 my($constname);
110 ($constname = $AUTOLOAD) =~ s/.*:://;
111 my ($error, $val) = constant($constname);
112 Carp::croak $error if $error;
113 no strict 'refs';
114 *{$AUTOLOAD} = sub { $val };
115 goto &{$AUTOLOAD};
116}
117
118use constant FLAG_APPEND => 1 ;
119use constant FLAG_CRC => 2 ;
120use constant FLAG_ADLER => 4 ;
121use constant FLAG_CONSUME_INPUT => 8 ;
9253672d 122use constant FLAG_LIMIT_OUTPUT => 16 ;
25f0751f
PM
123
124eval {
125 require XSLoader;
126 XSLoader::load('Compress::Raw::Zlib', $XS_VERSION);
127 1;
128}
129or do {
130 require DynaLoader;
131 local @ISA = qw(DynaLoader);
132 bootstrap Compress::Raw::Zlib $XS_VERSION ;
133};
134
135
136use constant Parse_any => 0x01;
137use constant Parse_unsigned => 0x02;
138use constant Parse_signed => 0x04;
139use constant Parse_boolean => 0x08;
c788e059
CBW
140#use constant Parse_string => 0x10;
141#use constant Parse_custom => 0x12;
25f0751f 142
c788e059 143#use constant Parse_store_ref => 0x100 ;
25f0751f
PM
144
145use constant OFF_PARSED => 0 ;
146use constant OFF_TYPE => 1 ;
147use constant OFF_DEFAULT => 2 ;
148use constant OFF_FIXED => 3 ;
149use constant OFF_FIRST_ONLY => 4 ;
150use constant OFF_STICKY => 5 ;
151
152
153
154sub ParseParameters
155{
156 my $level = shift || 0 ;
157
158 my $sub = (caller($level + 1))[3] ;
159 #local $Carp::CarpLevel = 1 ;
160 my $p = new Compress::Raw::Zlib::Parameters() ;
161 $p->parse(@_)
162 or croak "$sub: $p->{Error}" ;
163
164 return $p;
165}
166
167
168sub Compress::Raw::Zlib::Parameters::new
169{
170 my $class = shift ;
171
172 my $obj = { Error => '',
173 Got => {},
174 } ;
175
176 #return bless $obj, ref($class) || $class || __PACKAGE__ ;
177 return bless $obj, 'Compress::Raw::Zlib::Parameters' ;
178}
179
180sub Compress::Raw::Zlib::Parameters::setError
181{
182 my $self = shift ;
183 my $error = shift ;
184 my $retval = @_ ? shift : undef ;
185
186 $self->{Error} = $error ;
187 return $retval;
188}
189
190#sub getError
191#{
192# my $self = shift ;
193# return $self->{Error} ;
194#}
195
196sub Compress::Raw::Zlib::Parameters::parse
197{
198 my $self = shift ;
199
200 my $default = shift ;
201
202 my $got = $self->{Got} ;
203 my $firstTime = keys %{ $got } == 0 ;
204
205 my (@Bad) ;
206 my @entered = () ;
207
208 # Allow the options to be passed as a hash reference or
209 # as the complete hash.
210 if (@_ == 0) {
211 @entered = () ;
212 }
213 elsif (@_ == 1) {
214 my $href = $_[0] ;
215 return $self->setError("Expected even number of parameters, got 1")
216 if ! defined $href or ! ref $href or ref $href ne "HASH" ;
217
218 foreach my $key (keys %$href) {
219 push @entered, $key ;
220 push @entered, \$href->{$key} ;
221 }
222 }
223 else {
224 my $count = @_;
225 return $self->setError("Expected even number of parameters, got $count")
226 if $count % 2 != 0 ;
227
228 for my $i (0.. $count / 2 - 1) {
229 push @entered, $_[2* $i] ;
230 push @entered, \$_[2* $i+1] ;
231 }
232 }
233
234
235 while (my ($key, $v) = each %$default)
236 {
237 croak "need 4 params [@$v]"
238 if @$v != 4 ;
239
240 my ($first_only, $sticky, $type, $value) = @$v ;
241 my $x ;
242 $self->_checkType($key, \$value, $type, 0, \$x)
243 or return undef ;
244
245 $key = lc $key;
246
247 if ($firstTime || ! $sticky) {
248 $got->{$key} = [0, $type, $value, $x, $first_only, $sticky] ;
249 }
250
251 $got->{$key}[OFF_PARSED] = 0 ;
252 }
253
254 for my $i (0.. @entered / 2 - 1) {
255 my $key = $entered[2* $i] ;
256 my $value = $entered[2* $i+1] ;
257
258 #print "Key [$key] Value [$value]" ;
259 #print defined $$value ? "[$$value]\n" : "[undef]\n";
260
261 $key =~ s/^-// ;
262 my $canonkey = lc $key;
263
264 if ($got->{$canonkey} && ($firstTime ||
265 ! $got->{$canonkey}[OFF_FIRST_ONLY] ))
266 {
267 my $type = $got->{$canonkey}[OFF_TYPE] ;
268 my $s ;
269 $self->_checkType($key, $value, $type, 1, \$s)
270 or return undef ;
271 #$value = $$value unless $type & Parse_store_ref ;
272 $value = $$value ;
273 $got->{$canonkey} = [1, $type, $value, $s] ;
274 }
275 else
276 { push (@Bad, $key) }
277 }
278
279 if (@Bad) {
280 my ($bad) = join(", ", @Bad) ;
281 return $self->setError("unknown key value(s) @Bad") ;
282 }
283
284 return 1;
285}
286
287sub Compress::Raw::Zlib::Parameters::_checkType
288{
289 my $self = shift ;
290
291 my $key = shift ;
292 my $value = shift ;
293 my $type = shift ;
294 my $validate = shift ;
295 my $output = shift;
296
297 #local $Carp::CarpLevel = $level ;
298 #print "PARSE $type $key $value $validate $sub\n" ;
c788e059
CBW
299# if ( $type & Parse_store_ref)
300# {
301# #$value = $$value
302# # if ref ${ $value } ;
303#
304# $$output = $value ;
305# return 1;
306# }
25f0751f
PM
307
308 $value = $$value ;
309
310 if ($type & Parse_any)
311 {
312 $$output = $value ;
313 return 1;
314 }
315 elsif ($type & Parse_unsigned)
316 {
317 return $self->setError("Parameter '$key' must be an unsigned int, got 'undef'")
318 if $validate && ! defined $value ;
319 return $self->setError("Parameter '$key' must be an unsigned int, got '$value'")
320 if $validate && $value !~ /^\d+$/;
321
322 $$output = defined $value ? $value : 0 ;
323 return 1;
324 }
325 elsif ($type & Parse_signed)
326 {
327 return $self->setError("Parameter '$key' must be a signed int, got 'undef'")
328 if $validate && ! defined $value ;
329 return $self->setError("Parameter '$key' must be a signed int, got '$value'")
330 if $validate && $value !~ /^-?\d+$/;
331
332 $$output = defined $value ? $value : 0 ;
333 return 1 ;
334 }
335 elsif ($type & Parse_boolean)
336 {
337 return $self->setError("Parameter '$key' must be an int, got '$value'")
338 if $validate && defined $value && $value !~ /^\d*$/;
339 $$output = defined $value ? $value != 0 : 0 ;
340 return 1;
341 }
c788e059
CBW
342# elsif ($type & Parse_string)
343# {
344# $$output = defined $value ? $value : "" ;
345# return 1;
346# }
25f0751f
PM
347
348 $$output = $value ;
349 return 1;
350}
351
352
353
354sub Compress::Raw::Zlib::Parameters::parsed
355{
356 my $self = shift ;
357 my $name = shift ;
358
359 return $self->{Got}{lc $name}[OFF_PARSED] ;
360}
361
362sub Compress::Raw::Zlib::Parameters::value
363{
364 my $self = shift ;
365 my $name = shift ;
366
367 if (@_)
368 {
369 $self->{Got}{lc $name}[OFF_PARSED] = 1;
370 $self->{Got}{lc $name}[OFF_DEFAULT] = $_[0] ;
371 $self->{Got}{lc $name}[OFF_FIXED] = $_[0] ;
372 }
373
374 return $self->{Got}{lc $name}[OFF_FIXED] ;
375}
376
c788e059
CBW
377our $OPTIONS_deflate =
378 {
379 'AppendOutput' => [1, 1, Parse_boolean, 0],
380 'CRC32' => [1, 1, Parse_boolean, 0],
381 'ADLER32' => [1, 1, Parse_boolean, 0],
382 'Bufsize' => [1, 1, Parse_unsigned, 4096],
383
384 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
385 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
386 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
387 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
388 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
389 'Dictionary' => [1, 1, Parse_any, ""],
390 };
391
25f0751f
PM
392sub Compress::Raw::Zlib::Deflate::new
393{
394 my $pkg = shift ;
c788e059 395 my ($got) = ParseParameters(0, $OPTIONS_deflate, @_);
25f0751f
PM
396
397 croak "Compress::Raw::Zlib::Deflate::new: Bufsize must be >= 1, you specified " .
398 $got->value('Bufsize')
399 unless $got->value('Bufsize') >= 1;
400
401 my $flags = 0 ;
402 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
403 $flags |= FLAG_CRC if $got->value('CRC32') ;
404 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
405
e11a3f9e
PM
406 my $windowBits = $got->value('WindowBits');
407 $windowBits += MAX_WBITS()
408 if ($windowBits & MAX_WBITS()) == 0 ;
409
25f0751f
PM
410 _deflateInit($flags,
411 $got->value('Level'),
412 $got->value('Method'),
e11a3f9e 413 $windowBits,
25f0751f
PM
414 $got->value('MemLevel'),
415 $got->value('Strategy'),
416 $got->value('Bufsize'),
417 $got->value('Dictionary')) ;
418
419}
420
949ade47
CBW
421sub Compress::Raw::Zlib::deflateStream::STORABLE_freeze
422{
423 my $type = ref shift;
424 croak "Cannot freeze $type object\n";
425}
426
427sub Compress::Raw::Zlib::deflateStream::STORABLE_thaw
428{
429 my $type = ref shift;
430 croak "Cannot thaw $type object\n";
431}
432
433
c788e059
CBW
434our $OPTIONS_inflate =
435 {
436 'AppendOutput' => [1, 1, Parse_boolean, 0],
437 'LimitOutput' => [1, 1, Parse_boolean, 0],
438 'CRC32' => [1, 1, Parse_boolean, 0],
439 'ADLER32' => [1, 1, Parse_boolean, 0],
440 'ConsumeInput' => [1, 1, Parse_boolean, 1],
441 'Bufsize' => [1, 1, Parse_unsigned, 4096],
442
443 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
444 'Dictionary' => [1, 1, Parse_any, ""],
445 } ;
446
25f0751f
PM
447sub Compress::Raw::Zlib::Inflate::new
448{
449 my $pkg = shift ;
c788e059 450 my ($got) = ParseParameters(0, $OPTIONS_inflate, @_);
25f0751f
PM
451
452 croak "Compress::Raw::Zlib::Inflate::new: Bufsize must be >= 1, you specified " .
453 $got->value('Bufsize')
454 unless $got->value('Bufsize') >= 1;
455
456 my $flags = 0 ;
457 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
458 $flags |= FLAG_CRC if $got->value('CRC32') ;
459 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
460 $flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
9253672d
SH
461 $flags |= FLAG_LIMIT_OUTPUT if $got->value('LimitOutput') ;
462
25f0751f 463
e11a3f9e
PM
464 my $windowBits = $got->value('WindowBits');
465 $windowBits += MAX_WBITS()
466 if ($windowBits & MAX_WBITS()) == 0 ;
467
468 _inflateInit($flags, $windowBits, $got->value('Bufsize'),
25f0751f
PM
469 $got->value('Dictionary')) ;
470}
471
949ade47
CBW
472sub Compress::Raw::Zlib::inflateStream::STORABLE_freeze
473{
474 my $type = ref shift;
475 croak "Cannot freeze $type object\n";
476}
477
478sub Compress::Raw::Zlib::inflateStream::STORABLE_thaw
479{
480 my $type = ref shift;
481 croak "Cannot thaw $type object\n";
482}
483
25f0751f
PM
484sub Compress::Raw::Zlib::InflateScan::new
485{
486 my $pkg = shift ;
487 my ($got) = ParseParameters(0,
488 {
489 'CRC32' => [1, 1, Parse_boolean, 0],
490 'ADLER32' => [1, 1, Parse_boolean, 0],
491 'Bufsize' => [1, 1, Parse_unsigned, 4096],
492
493 'WindowBits' => [1, 1, Parse_signed, -MAX_WBITS()],
494 'Dictionary' => [1, 1, Parse_any, ""],
495 }, @_) ;
496
497
498 croak "Compress::Raw::Zlib::InflateScan::new: Bufsize must be >= 1, you specified " .
499 $got->value('Bufsize')
500 unless $got->value('Bufsize') >= 1;
501
502 my $flags = 0 ;
503 #$flags |= FLAG_APPEND if $got->value('AppendOutput') ;
504 $flags |= FLAG_CRC if $got->value('CRC32') ;
505 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
506 #$flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
507
508 _inflateScanInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
509 '') ;
510}
511
512sub Compress::Raw::Zlib::inflateScanStream::createDeflateStream
513{
514 my $pkg = shift ;
515 my ($got) = ParseParameters(0,
516 {
517 'AppendOutput' => [1, 1, Parse_boolean, 0],
518 'CRC32' => [1, 1, Parse_boolean, 0],
519 'ADLER32' => [1, 1, Parse_boolean, 0],
520 'Bufsize' => [1, 1, Parse_unsigned, 4096],
521
522 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
523 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
524 'WindowBits' => [1, 1, Parse_signed, - MAX_WBITS()],
525 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
526 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
527 }, @_) ;
528
529 croak "Compress::Raw::Zlib::InflateScan::createDeflateStream: Bufsize must be >= 1, you specified " .
530 $got->value('Bufsize')
531 unless $got->value('Bufsize') >= 1;
532
533 my $flags = 0 ;
534 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
535 $flags |= FLAG_CRC if $got->value('CRC32') ;
536 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
537
538 $pkg->_createDeflateStream($flags,
539 $got->value('Level'),
540 $got->value('Method'),
541 $got->value('WindowBits'),
542 $got->value('MemLevel'),
543 $got->value('Strategy'),
544 $got->value('Bufsize'),
545 ) ;
546
547}
548
549sub Compress::Raw::Zlib::inflateScanStream::inflate
550{
551 my $self = shift ;
552 my $buffer = $_[1];
553 my $eof = $_[2];
554
555 my $status = $self->scan(@_);
556
557 if ($status == Z_OK() && $_[2]) {
558 my $byte = ' ';
559
560 $status = $self->scan(\$byte, $_[1]) ;
561 }
562
563 return $status ;
564}
565
566sub Compress::Raw::Zlib::deflateStream::deflateParams
567{
568 my $self = shift ;
569 my ($got) = ParseParameters(0, {
570 'Level' => [1, 1, Parse_signed, undef],
571 'Strategy' => [1, 1, Parse_unsigned, undef],
572 'Bufsize' => [1, 1, Parse_unsigned, undef],
573 },
574 @_) ;
575
576 croak "Compress::Raw::Zlib::deflateParams needs Level and/or Strategy"
577 unless $got->parsed('Level') + $got->parsed('Strategy') +
578 $got->parsed('Bufsize');
579
580 croak "Compress::Raw::Zlib::Inflate::deflateParams: Bufsize must be >= 1, you specified " .
581 $got->value('Bufsize')
582 if $got->parsed('Bufsize') && $got->value('Bufsize') <= 1;
583
584 my $flags = 0;
585 $flags |= 1 if $got->parsed('Level') ;
586 $flags |= 2 if $got->parsed('Strategy') ;
587 $flags |= 4 if $got->parsed('Bufsize') ;
588
589 $self->_deflateParams($flags, $got->value('Level'),
590 $got->value('Strategy'), $got->value('Bufsize'));
591
592}
593
594
25f0751f
PM
5951;
596__END__
597
598
599=head1 NAME
600
601Compress::Raw::Zlib - Low-Level Interface to zlib compression library
602
603=head1 SYNOPSIS
604
605 use Compress::Raw::Zlib ;
606
607 ($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) ;
608 $status = $d->deflate($input, $output) ;
609 $status = $d->flush($output [, $flush_type]) ;
319fab50 610 $d->deflateReset() ;
25f0751f
PM
611 $d->deflateParams(OPTS) ;
612 $d->deflateTune(OPTS) ;
613 $d->dict_adler() ;
614 $d->crc32() ;
615 $d->adler32() ;
616 $d->total_in() ;
617 $d->total_out() ;
618 $d->msg() ;
619 $d->get_Strategy();
620 $d->get_Level();
621 $d->get_BufSize();
622
623 ($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] ) ;
624 $status = $i->inflate($input, $output [, $eof]) ;
625 $status = $i->inflateSync($input) ;
e2f1db54 626 $i->inflateReset() ;
25f0751f
PM
627 $i->dict_adler() ;
628 $d->crc32() ;
629 $d->adler32() ;
630 $i->total_in() ;
631 $i->total_out() ;
632 $i->msg() ;
633 $d->get_BufSize();
634
635 $crc = adler32($buffer [,$crc]) ;
636 $crc = crc32($buffer [,$crc]) ;
637
f3d3633e
CBW
638 $crc = crc32_combine($crc1, $crc2, $len2);
639 $adler = adler32_combine($adler1, $adler2, $len2);
25f0751f 640
319fab50 641 my $version = Compress::Raw::Zlib::zlib_version();
589c1691 642 my $flags = Compress::Raw::Zlib::zlibCompileFlags();
25f0751f
PM
643
644=head1 DESCRIPTION
645
646The I<Compress::Raw::Zlib> module provides a Perl interface to the I<zlib>
647compression library (see L</AUTHOR> for details about where to get
648I<zlib>).
649
25f0751f
PM
650=head1 Compress::Raw::Zlib::Deflate
651
652This section defines an interface that allows in-memory compression using
653the I<deflate> interface provided by zlib.
654
655Here is a definition of the interface available:
656
25f0751f
PM
657=head2 B<($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) >
658
659Initialises a deflation object.
660
661If you are familiar with the I<zlib> library, it combines the
662features of the I<zlib> functions C<deflateInit>, C<deflateInit2>
663and C<deflateSetDictionary>.
664
665If successful, it will return the initialised deflation object, C<$d>
666and a C<$status> of C<Z_OK> in a list context. In scalar context it
667returns the deflation object, C<$d>, only.
668
669If not successful, the returned deflation object, C<$d>, will be
670I<undef> and C<$status> will hold the a I<zlib> error code.
671
672The function optionally takes a number of named options specified as
e7d45986 673C<< Name => value >> pairs. This allows individual options to be
25f0751f
PM
674tailored without having to specify them all in the parameter list.
675
676For backward compatibility, it is also possible to pass the parameters
677as a reference to a hash containing the name=>value pairs.
678
679Below is a list of the valid options:
680
681=over 5
682
683=item B<-Level>
684
685Defines the compression level. Valid values are 0 through 9,
686C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
687C<Z_DEFAULT_COMPRESSION>.
688
e11a3f9e 689The default is C<Z_DEFAULT_COMPRESSION>.
25f0751f
PM
690
691=item B<-Method>
692
693Defines the compression method. The only valid value at present (and
f02c02ec 694the default) is C<Z_DEFLATED>.
25f0751f
PM
695
696=item B<-WindowBits>
697
e11a3f9e
PM
698To compress an RFC 1950 data stream, set C<WindowBits> to a positive
699number between 8 and 15.
700
701To compress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
702
703To compress an RFC 1952 data stream (i.e. gzip), set C<WindowBits> to
704C<WANT_GZIP>.
705
25f0751f
PM
706For a definition of the meaning and valid values for C<WindowBits>
707refer to the I<zlib> documentation for I<deflateInit2>.
708
e11a3f9e 709Defaults to C<MAX_WBITS>.
25f0751f
PM
710
711=item B<-MemLevel>
712
713For a definition of the meaning and valid values for C<MemLevel>
714refer to the I<zlib> documentation for I<deflateInit2>.
715
e7d45986 716Defaults to MAX_MEM_LEVEL.
25f0751f
PM
717
718=item B<-Strategy>
719
720Defines the strategy used to tune the compression. The valid values are
721C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED>, C<Z_RLE>, C<Z_FIXED> and
722C<Z_HUFFMAN_ONLY>.
723
f02c02ec 724The default is C<Z_DEFAULT_STRATEGY>.
25f0751f
PM
725
726=item B<-Dictionary>
727
728When a dictionary is specified I<Compress::Raw::Zlib> will automatically
729call C<deflateSetDictionary> directly after calling C<deflateInit>. The
730Adler32 value for the dictionary can be obtained by calling the method
731C<$d-E<gt>dict_adler()>.
732
733The default is no dictionary.
734
735=item B<-Bufsize>
736
737Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
738and C<$d-E<gt>flush> methods. If the buffer has to be
739reallocated to increase the size, it will grow in increments of
740C<Bufsize>.
741
742The default buffer size is 4096.
743
744=item B<-AppendOutput>
745
746This option controls how data is written to the output buffer by the
747C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
748
749If the C<AppendOutput> option is set to false, the output buffers in the
750C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods will be truncated before
751uncompressed data is written to them.
752
753If the option is set to true, uncompressed data will be appended to the
754output buffer in the C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
755
756This option defaults to false.
757
758=item B<-CRC32>
759
760If set to true, a crc32 checksum of the uncompressed data will be
761calculated. Use the C<$d-E<gt>crc32> method to retrieve this value.
762
763This option defaults to false.
764
25f0751f
PM
765=item B<-ADLER32>
766
767If set to true, an adler32 checksum of the uncompressed data will be
768calculated. Use the C<$d-E<gt>adler32> method to retrieve this value.
769
770This option defaults to false.
771
25f0751f
PM
772=back
773
774Here is an example of using the C<Compress::Raw::Zlib::Deflate> optional
775parameter list to override the default buffer size and compression
776level. All other options will take their default values.
777
778 my $d = new Compress::Raw::Zlib::Deflate ( -Bufsize => 300,
779 -Level => Z_BEST_SPEED ) ;
780
25f0751f
PM
781=head2 B<$status = $d-E<gt>deflate($input, $output)>
782
783Deflates the contents of C<$input> and writes the compressed data to
784C<$output>.
785
786The C<$input> and C<$output> parameters can be either scalars or scalar
787references.
788
789When finished, C<$input> will be completely processed (assuming there
790were no errors). If the deflation was successful it writes the deflated
791data to C<$output> and returns a status value of C<Z_OK>.
792
793On error, it returns a I<zlib> error code.
794
795If the C<AppendOutput> option is set to true in the constructor for
796the C<$d> object, the compressed data will be appended to C<$output>. If
797it is false, C<$output> will be truncated before any compressed data is
798written to it.
799
800B<Note>: This method will not necessarily write compressed data to
801C<$output> every time it is called. So do not assume that there has been
802an error if the contents of C<$output> is empty on returning from
803this method. As long as the return code from the method is C<Z_OK>,
804the deflate has succeeded.
805
806=head2 B<$status = $d-E<gt>flush($output [, $flush_type]) >
807
808Typically used to finish the deflation. Any pending output will be
809written to C<$output>.
810
811Returns C<Z_OK> if successful.
812
813Note that flushing can seriously degrade the compression ratio, so it
814should only be used to terminate a decompression (using C<Z_FINISH>) or
815when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
816
817By default the C<flush_type> used is C<Z_FINISH>. Other valid values
818for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
819and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
820C<flush_type> parameter if you fully understand the implications of
821what it does. See the C<zlib> documentation for details.
822
823If the C<AppendOutput> option is set to true in the constructor for
824the C<$d> object, the compressed data will be appended to C<$output>. If
825it is false, C<$output> will be truncated before any compressed data is
826written to it.
827
319fab50
PM
828=head2 B<$status = $d-E<gt>deflateReset() >
829
830This method will reset the deflation object C<$d>. It can be used when you
831are compressing multiple data streams and want to use the same object to
832compress each of them. It should only be used once the previous data stream
833has been flushed successfully, i.e. a call to C<< $d->flush(Z_FINISH) >> has
834returned C<Z_OK>.
835
836Returns C<Z_OK> if successful.
837
25f0751f
PM
838=head2 B<$status = $d-E<gt>deflateParams([OPT])>
839
840Change settings for the deflate object C<$d>.
841
842The list of the valid options is shown below. Options not specified
843will remain unchanged.
844
25f0751f
PM
845=over 5
846
847=item B<-Level>
848
849Defines the compression level. Valid values are 0 through 9,
850C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
851C<Z_DEFAULT_COMPRESSION>.
852
853=item B<-Strategy>
854
855Defines the strategy used to tune the compression. The valid values are
856C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
857
858=item B<-BufSize>
859
860Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
861and C<$d-E<gt>flush> methods. If the buffer has to be
862reallocated to increase the size, it will grow in increments of
863C<Bufsize>.
864
25f0751f
PM
865=back
866
867=head2 B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)>
868
869Tune the internal settings for the deflate object C<$d>. This option is
870only available if you are running zlib 1.2.2.3 or better.
871
872Refer to the documentation in zlib.h for instructions on how to fly
873C<deflateTune>.
874
875=head2 B<$d-E<gt>dict_adler()>
876
877Returns the adler32 value for the dictionary.
878
879=head2 B<$d-E<gt>crc32()>
880
881Returns the crc32 value for the uncompressed data to date.
882
883If the C<CRC32> option is not enabled in the constructor for this object,
884this method will always return 0;
885
886=head2 B<$d-E<gt>adler32()>
887
888Returns the adler32 value for the uncompressed data to date.
889
890=head2 B<$d-E<gt>msg()>
891
892Returns the last error message generated by zlib.
893
894=head2 B<$d-E<gt>total_in()>
895
896Returns the total number of bytes uncompressed bytes input to deflate.
897
898=head2 B<$d-E<gt>total_out()>
899
900Returns the total number of compressed bytes output from deflate.
901
902=head2 B<$d-E<gt>get_Strategy()>
903
904Returns the deflation strategy currently used. Valid values are
905C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
906
25f0751f
PM
907=head2 B<$d-E<gt>get_Level()>
908
909Returns the compression level being used.
910
911=head2 B<$d-E<gt>get_BufSize()>
912
913Returns the buffer size used to carry out the compression.
914
915=head2 Example
916
25f0751f
PM
917Here is a trivial example of using C<deflate>. It simply reads standard
918input, deflates it and writes it to standard output.
919
920 use strict ;
921 use warnings ;
922
923 use Compress::Raw::Zlib ;
924
925 binmode STDIN;
926 binmode STDOUT;
927 my $x = new Compress::Raw::Zlib::Deflate
928 or die "Cannot create a deflation stream\n" ;
929
930 my ($output, $status) ;
931 while (<>)
932 {
933 $status = $x->deflate($_, $output) ;
934
935 $status == Z_OK
936 or die "deflation failed\n" ;
937
938 print $output ;
939 }
940
941 $status = $x->flush($output) ;
942
943 $status == Z_OK
944 or die "deflation failed\n" ;
945
946 print $output ;
947
948=head1 Compress::Raw::Zlib::Inflate
949
950This section defines an interface that allows in-memory uncompression using
951the I<inflate> interface provided by zlib.
952
953Here is a definition of the interface:
954
25f0751f
PM
955=head2 B< ($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] ) >
956
957Initialises an inflation object.
958
959In a list context it returns the inflation object, C<$i>, and the
960I<zlib> status code (C<$status>). In a scalar context it returns the
961inflation object only.
962
963If successful, C<$i> will hold the inflation object and C<$status> will
964be C<Z_OK>.
965
966If not successful, C<$i> will be I<undef> and C<$status> will hold the
967I<zlib> error code.
968
969The function optionally takes a number of named options specified as
e7d45986 970C<< -Name => value >> pairs. This allows individual options to be
25f0751f
PM
971tailored without having to specify them all in the parameter list.
972
973For backward compatibility, it is also possible to pass the parameters
e7d45986 974as a reference to a hash containing the C<< name=>value >> pairs.
25f0751f
PM
975
976Here is a list of the valid options:
977
978=over 5
979
980=item B<-WindowBits>
981
982To uncompress an RFC 1950 data stream, set C<WindowBits> to a positive
e11a3f9e 983number between 8 and 15.
25f0751f
PM
984
985To uncompress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
986
e11a3f9e
PM
987To uncompress an RFC 1952 data stream (i.e. gzip), set C<WindowBits> to
988C<WANT_GZIP>.
989
990To auto-detect and uncompress an RFC 1950 or RFC 1952 data stream (i.e.
991gzip), set C<WindowBits> to C<WANT_GZIP_OR_ZLIB>.
992
25f0751f
PM
993For a full definition of the meaning and valid values for C<WindowBits>
994refer to the I<zlib> documentation for I<inflateInit2>.
995
e11a3f9e 996Defaults to C<MAX_WBITS>.
25f0751f
PM
997
998=item B<-Bufsize>
999
1000Sets the initial size for the output buffer used by the C<$i-E<gt>inflate>
1001method. If the output buffer in this method has to be reallocated to
1002increase the size, it will grow in increments of C<Bufsize>.
1003
1004Default is 4096.
1005
1006=item B<-Dictionary>
1007
1008The default is no dictionary.
1009
1010=item B<-AppendOutput>
1011
1012This option controls how data is written to the output buffer by the
1013C<$i-E<gt>inflate> method.
1014
1015If the option is set to false, the output buffer in the C<$i-E<gt>inflate>
1016method will be truncated before uncompressed data is written to it.
1017
1018If the option is set to true, uncompressed data will be appended to the
1019output buffer by the C<$i-E<gt>inflate> method.
1020
1021This option defaults to false.
1022
25f0751f
PM
1023=item B<-CRC32>
1024
1025If set to true, a crc32 checksum of the uncompressed data will be
1026calculated. Use the C<$i-E<gt>crc32> method to retrieve this value.
1027
1028This option defaults to false.
1029
1030=item B<-ADLER32>
1031
1032If set to true, an adler32 checksum of the uncompressed data will be
1033calculated. Use the C<$i-E<gt>adler32> method to retrieve this value.
1034
1035This option defaults to false.
1036
1037=item B<-ConsumeInput>
1038
1039If set to true, this option will remove compressed data from the input
319fab50 1040buffer of the C<< $i->inflate >> method as the inflate progresses.
25f0751f
PM
1041
1042This option can be useful when you are processing compressed data that is
1043embedded in another file/buffer. In this case the data that immediately
1044follows the compressed stream will be left in the input buffer.
1045
1046This option defaults to true.
1047
319fab50
PM
1048=item B<-LimitOutput>
1049
1050The C<LimitOutput> option changes the behavior of the C<< $i->inflate >>
1051method so that the amount of memory used by the output buffer can be
1052limited.
1053
1054When C<LimitOutput> is used the size of the output buffer used will either
1055be the value of the C<Bufsize> option or the amount of memory already
1056allocated to C<$output>, whichever is larger. Predicting the output size
1057available is tricky, so don't rely on getting an exact output buffer size.
1058
1059When C<LimitOutout> is not specified C<< $i->inflate >> will use as much
1060memory as it takes to write all the uncompressed data it creates by
1061uncompressing the input buffer.
1062
319fab50
PM
1063If C<LimitOutput> is enabled, the C<ConsumeInput> option will also be
1064enabled.
1065
319fab50
PM
1066This option defaults to false.
1067
dc82791d
PM
1068See L</The LimitOutput option> for a discussion on why C<LimitOutput> is
1069needed and how to use it.
319fab50 1070
25f0751f
PM
1071=back
1072
1073Here is an example of using an optional parameter to override the default
1074buffer size.
1075
1076 my ($i, $status) = new Compress::Raw::Zlib::Inflate( -Bufsize => 300 ) ;
1077
1078=head2 B< $status = $i-E<gt>inflate($input, $output [,$eof]) >
1079
1080Inflates the complete contents of C<$input> and writes the uncompressed
1081data to C<$output>. The C<$input> and C<$output> parameters can either be
1082scalars or scalar references.
1083
1084Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
1085compressed data has been successfully reached.
1086
1087If not successful C<$status> will hold the I<zlib> error code.
1088
1089If the C<ConsumeInput> option has been set to true when the
1090C<Compress::Raw::Zlib::Inflate> object is created, the C<$input> parameter
1091is modified by C<inflate>. On completion it will contain what remains
1092of the input buffer after inflation. In practice, this means that when
1093the return status is C<Z_OK> the C<$input> parameter will contain an
1094empty string, and when the return status is C<Z_STREAM_END> the C<$input>
1095parameter will contains what (if anything) was stored in the input buffer
1096after the deflated data stream.
1097
1098This feature is useful when processing a file format that encapsulates
1099a compressed data stream (e.g. gzip, zip) and there is useful data
1100immediately after the deflation stream.
1101
1102If the C<AppendOutput> option is set to true in the constructor for
1103this object, the uncompressed data will be appended to C<$output>. If
1104it is false, C<$output> will be truncated before any uncompressed data
1105is written to it.
1106
1107The C<$eof> parameter needs a bit of explanation.
1108
1109Prior to version 1.2.0, zlib assumed that there was at least one trailing
1110byte immediately after the compressed data stream when it was carrying out
1111decompression. This normally isn't a problem because the majority of zlib
1112applications guarantee that there will be data directly after the
1113compressed data stream. For example, both gzip (RFC 1950) and zip both
1114define trailing data that follows the compressed data stream.
1115
1116The C<$eof> parameter only needs to be used if B<all> of the following
1117conditions apply
1118
1119=over 5
1120
1121=item 1
1122
1123You are either using a copy of zlib that is older than version 1.2.0 or you
1124want your application code to be able to run with as many different
1125versions of zlib as possible.
1126
1127=item 2
1128
1129You have set the C<WindowBits> parameter to C<-MAX_WBITS> in the constructor
1130for this object, i.e. you are uncompressing a raw deflated data stream
1131(RFC 1951).
1132
1133=item 3
1134
1135There is no data immediately after the compressed data stream.
1136
1137=back
1138
1139If B<all> of these are the case, then you need to set the C<$eof> parameter
1140to true on the final call (and only the final call) to C<$i-E<gt>inflate>.
1141
1142If you have built this module with zlib >= 1.2.0, the C<$eof> parameter is
1143ignored. You can still set it if you want, but it won't be used behind the
1144scenes.
1145
1146=head2 B<$status = $i-E<gt>inflateSync($input)>
1147
1148This method can be used to attempt to recover good data from a compressed
1149data stream that is partially corrupt.
1150It scans C<$input> until it reaches either a I<full flush point> or the
1151end of the buffer.
1152
1153If a I<full flush point> is found, C<Z_OK> is returned and C<$input>
1154will be have all data up to the flush point removed. This data can then be
1155passed to the C<$i-E<gt>inflate> method to be uncompressed.
1156
1157Any other return code means that a flush point was not found. If more
1158data is available, C<inflateSync> can be called repeatedly with more
1159compressed data until the flush point is found.
1160
1161Note I<full flush points> are not present by default in compressed
1162data streams. They must have been added explicitly when the data stream
1163was created by calling C<Compress::Deflate::flush> with C<Z_FULL_FLUSH>.
1164
e2f1db54
CBW
1165=head2 B<$status = $i-E<gt>inflateReset() >
1166
1167This method will reset the inflation object C<$i>. It can be used when you
1168are uncompressing multiple data streams and want to use the same object to
1169uncompress each of them.
1170
1171Returns C<Z_OK> if successful.
1172
25f0751f
PM
1173=head2 B<$i-E<gt>dict_adler()>
1174
1175Returns the adler32 value for the dictionary.
1176
1177=head2 B<$i-E<gt>crc32()>
1178
1179Returns the crc32 value for the uncompressed data to date.
1180
1181If the C<CRC32> option is not enabled in the constructor for this object,
1182this method will always return 0;
1183
1184=head2 B<$i-E<gt>adler32()>
1185
1186Returns the adler32 value for the uncompressed data to date.
1187
1188If the C<ADLER32> option is not enabled in the constructor for this object,
1189this method will always return 0;
1190
1191=head2 B<$i-E<gt>msg()>
1192
1193Returns the last error message generated by zlib.
1194
1195=head2 B<$i-E<gt>total_in()>
1196
1197Returns the total number of bytes compressed bytes input to inflate.
1198
1199=head2 B<$i-E<gt>total_out()>
1200
1201Returns the total number of uncompressed bytes output from inflate.
1202
1203=head2 B<$d-E<gt>get_BufSize()>
1204
1205Returns the buffer size used to carry out the decompression.
1206
319fab50 1207=head2 Examples
25f0751f
PM
1208
1209Here is an example of using C<inflate>.
1210
1211 use strict ;
1212 use warnings ;
1213
1214 use Compress::Raw::Zlib;
1215
1216 my $x = new Compress::Raw::Zlib::Inflate()
1217 or die "Cannot create a inflation stream\n" ;
1218
1219 my $input = '' ;
1220 binmode STDIN;
1221 binmode STDOUT;
1222
1223 my ($output, $status) ;
1224 while (read(STDIN, $input, 4096))
1225 {
319fab50 1226 $status = $x->inflate($input, $output) ;
25f0751f 1227
dc82791d 1228 print $output ;
25f0751f
PM
1229
1230 last if $status != Z_OK ;
1231 }
1232
1233 die "inflation failed\n"
1234 unless $status == Z_STREAM_END ;
1235
319fab50
PM
1236The next example show how to use the C<LimitOutput> option. Notice the use
1237of two nested loops in this case. The outer loop reads the data from the
1238input source - STDIN and the inner loop repeatedly calls C<inflate> until
1239C<$input> is exhausted, we get an error, or the end of the stream is
1240reached. One point worth remembering is by using the C<LimitOutput> option
1241you also get C<ConsumeInput> set as well - this makes the code below much
1242simpler.
1243
1244 use strict ;
1245 use warnings ;
1246
1247 use Compress::Raw::Zlib;
1248
1249 my $x = new Compress::Raw::Zlib::Inflate(LimitOutput => 1)
1250 or die "Cannot create a inflation stream\n" ;
1251
1252 my $input = '' ;
1253 binmode STDIN;
1254 binmode STDOUT;
1255
1256 my ($output, $status) ;
1257
1258 OUTER:
1259 while (read(STDIN, $input, 4096))
1260 {
1261 do
1262 {
1263 $status = $x->inflate($input, $output) ;
1264
1265 print $output ;
1266
1267 last OUTER
1268 unless $status == Z_OK || $status == Z_BUF_ERROR ;
1269 }
1270 while ($status == Z_OK && length $input);
1271 }
1272
1273 die "inflation failed\n"
1274 unless $status == Z_STREAM_END ;
1275
25f0751f
PM
1276=head1 CHECKSUM FUNCTIONS
1277
1278Two functions are provided by I<zlib> to calculate checksums. For the
1279Perl interface, the order of the two parameters in both functions has
1280been reversed. This allows both running checksums and one off
1281calculations to be done.
1282
1283 $crc = adler32($buffer [,$crc]) ;
1284 $crc = crc32($buffer [,$crc]) ;
1285
1286The buffer parameters can either be a scalar or a scalar reference.
1287
1288If the $crc parameters is C<undef>, the crc value will be reset.
1289
1290If you have built this module with zlib 1.2.3 or better, two more
1291CRC-related functions are available.
1292
f3d3633e
CBW
1293 $crc = crc32_combine($crc1, $crc2, $len2);
1294 $adler = adler32_combine($adler1, $adler2, $len2);
25f0751f
PM
1295
1296These functions allow checksums to be merged.
f3d3633e 1297Refer to the I<zlib> documentation for more details.
25f0751f 1298
319fab50
PM
1299=head1 Misc
1300
1301=head2 my $version = Compress::Raw::Zlib::zlib_version();
1302
1303Returns the version of the zlib library.
1304
589c1691
CBW
1305=head2 my $flags = Compress::Raw::Zlib::zlibCompileFlags();
1306
1307Returns the flags indicating compile-time options that were used to build
1308the zlib library. See the zlib documentation for a description of the flags
1309returned by C<zlibCompileFlags>.
1310
1311Note that when the zlib sources are built along with this module the
1312C<sprintf> flags (bits 24, 25 and 26) should be ignored.
1313
1314If you are using zlib 1.2.0 or older, C<zlibCompileFlags> will return 0.
1315
dc82791d
PM
1316=head1 The LimitOutput option.
1317
1318By default C<< $i->inflate($input, $output) >> will uncompress I<all> data
1319in C<$input> and write I<all> of the uncompressed data it has generated to
1320C<$output>. This makes the interface to C<inflate> much simpler - if the
1321method has uncompressed C<$input> successfully I<all> compressed data in
1322C<$input> will have been dealt with. So if you are reading from an input
1323source and uncompressing as you go the code will look something like this
1324
1325 use strict ;
1326 use warnings ;
1327
1328 use Compress::Raw::Zlib;
1329
1330 my $x = new Compress::Raw::Zlib::Inflate()
1331 or die "Cannot create a inflation stream\n" ;
1332
1333 my $input = '' ;
1334
1335 my ($output, $status) ;
1336 while (read(STDIN, $input, 4096))
1337 {
1338 $status = $x->inflate($input, $output) ;
1339
1340 print $output ;
1341
1342 last if $status != Z_OK ;
1343 }
1344
1345 die "inflation failed\n"
1346 unless $status == Z_STREAM_END ;
1347
1348The points to note are
1349
1350=over 5
1351
1352=item *
1353
1354The main processing loop in the code handles reading of compressed data
1355from STDIN.
1356
1357=item *
1358
1359The status code returned from C<inflate> will only trigger termination of
1360the main processing loop if it isn't C<Z_OK>. When C<LimitOutput> has not
ef379d05 1361been used the C<Z_OK> status means that the end of the compressed
dc82791d
PM
1362data stream has been reached or there has been an error in uncompression.
1363
1364=item *
1365
1366After the call to C<inflate> I<all> of the uncompressed data in C<$input>
1367will have been processed. This means the subsequent call to C<read> can
1368overwrite it's contents without any problem.
1369
1370=back
1371
1372For most use-cases the behavior described above is acceptable (this module
1373and it's predecessor, C<Compress::Zlib>, have used it for over 10 years
1374without an issue), but in a few very specific use-cases the amount of
1375memory required for C<$output> can prohibitively large. For example, if the
1376compressed data stream contains the same pattern repeated thousands of
1377times, a relatively small compressed data stream can uncompress into
1378hundreds of megabytes. Remember C<inflate> will keep allocating memory
1379until I<all> the uncompressed data has been written to the output buffer -
1380the size of C<$output> is unbounded.
1381
1382The C<LimitOutput> option is designed to help with this use-case.
1383
1384The main difference in your code when using C<LimitOutput> is having to
1385deal with cases where the C<$input> parameter still contains some
1386uncompressed data that C<inflate> hasn't processed yet. The status code
1387returned from C<inflate> will be C<Z_OK> if uncompression took place and
1388C<Z_BUF_ERROR> if the output buffer is full.
1389
1390Below is typical code that shows how to use C<LimitOutput>.
1391
1392 use strict ;
1393 use warnings ;
1394
1395 use Compress::Raw::Zlib;
1396
1397 my $x = new Compress::Raw::Zlib::Inflate(LimitOutput => 1)
1398 or die "Cannot create a inflation stream\n" ;
1399
1400 my $input = '' ;
1401 binmode STDIN;
1402 binmode STDOUT;
1403
1404 my ($output, $status) ;
1405
1406 OUTER:
1407 while (read(STDIN, $input, 4096))
1408 {
1409 do
1410 {
1411 $status = $x->inflate($input, $output) ;
1412
1413 print $output ;
1414
1415 last OUTER
1416 unless $status == Z_OK || $status == Z_BUF_ERROR ;
1417 }
1418 while ($status == Z_OK && length $input);
1419 }
1420
1421 die "inflation failed\n"
1422 unless $status == Z_STREAM_END ;
1423
1424Points to note this time:
1425
1426=over 5
1427
1428=item *
1429
1430There are now two nested loops in the code: the outer loop for reading the
1431compressed data from STDIN, as before; and the inner loop to carry out the
1432uncompression.
1433
1434=item *
1435
1436There are two exit points from the inner uncompression loop.
1437
1438Firstly when C<inflate> has returned a status other than C<Z_OK> or
1439C<Z_BUF_ERROR>. This means that either the end of the compressed data
1440stream has been reached (C<Z_STREAM_END>) or there is an error in the
1441compressed data. In either of these cases there is no point in continuing
1442with reading the compressed data, so both loops are terminated.
1443
1444The second exit point tests if there is any data left in the input buffer,
1445C<$input> - remember that the C<ConsumeInput> option is automatically
1446enabled when C<LimitOutput> is used. When the input buffer has been
1447exhausted, the outer loop can run again and overwrite a now empty
1448C<$input>.
1449
1450=back
1451
25f0751f
PM
1452=head1 ACCESSING ZIP FILES
1453
dcfdccf9 1454Although it is possible (with some effort on your part) to use this module
c788e059
CBW
1455to access .zip files, there are other perl modules available that will do
1456all the hard work for you. Check out C<Archive::Zip>,
1457C<Archive::Zip::SimpleZip>, C<IO::Compress::Zip> and
1458C<IO::Uncompress::Unzip>.
25f0751f 1459
9505dd85
CBW
1460=head1 FAQ
1461
1462=head2 Compatibility with Unix compress/uncompress.
1463
1464This module is not compatible with Unix C<compress>.
1465
1466If you have the C<uncompress> program available, you can use this to read
1467compressed files
1468
1469 open F, "uncompress -c $filename |";
1470 while (<F>)
1471 {
1472 ...
1473
1474Alternatively, if you have the C<gunzip> program available, you can use
1475this to read compressed files
1476
1477 open F, "gunzip -c $filename |";
1478 while (<F>)
1479 {
1480 ...
1481
1482and this to write compress files, if you have the C<compress> program
1483available
1484
1485 open F, "| compress -c $filename ";
1486 print F "data";
1487 ...
1488 close F ;
1489
1490=head2 Accessing .tar.Z files
1491
1492See previous FAQ item.
1493
1494If the C<Archive::Tar> module is installed and either the C<uncompress> or
1495C<gunzip> programs are available, you can use one of these workarounds to
1496read C<.tar.Z> files.
1497
1498Firstly with C<uncompress>
1499
1500 use strict;
1501 use warnings;
1502 use Archive::Tar;
1503
1504 open F, "uncompress -c $filename |";
1505 my $tar = Archive::Tar->new(*F);
1506 ...
1507
1508and this with C<gunzip>
1509
1510 use strict;
1511 use warnings;
1512 use Archive::Tar;
1513
1514 open F, "gunzip -c $filename |";
1515 my $tar = Archive::Tar->new(*F);
1516 ...
1517
1518Similarly, if the C<compress> program is available, you can use this to
1519write a C<.tar.Z> file
1520
1521 use strict;
1522 use warnings;
1523 use Archive::Tar;
1524 use IO::File;
1525
1526 my $fh = new IO::File "| compress -c >$filename";
1527 my $tar = Archive::Tar->new();
1528 ...
1529 $tar->write($fh);
1530 $fh->close ;
1531
1532=head2 Zlib Library Version Support
1533
1534By default C<Compress::Raw::Zlib> will build with a private copy of version
15351.2.5 of the zlib library. (See the F<README> file for details of
1536how to override this behaviour)
1537
1538If you decide to use a different version of the zlib library, you need to be
1539aware of the following issues
1540
1541=over 5
1542
1543=item *
1544
1545First off, you must have zlib 1.0.5 or better.
1546
1547=item *
1548
1549You need to have zlib 1.2.1 or better if you want to use the C<-Merge>
1550option with C<IO::Compress::Gzip>, C<IO::Compress::Deflate> and
1551C<IO::Compress::RawDeflate>.
1552
1553=back
1554
25f0751f
PM
1555=head1 CONSTANTS
1556
1557All the I<zlib> constants are automatically imported when you make use
1558of I<Compress::Raw::Zlib>.
1559
25f0751f
PM
1560=head1 SEE ALSO
1561
9b5fd1d4 1562L<Compress::Zlib>, 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::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
25f0751f 1563
71a82d22 1564L<IO::Compress::FAQ|IO::Compress::FAQ>
25f0751f
PM
1565
1566L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1567L<Archive::Tar|Archive::Tar>,
1568L<IO::Zlib|IO::Zlib>
1569
25f0751f
PM
1570For RFC 1950, 1951 and 1952 see
1571F<http://www.faqs.org/rfcs/rfc1950.html>,
1572F<http://www.faqs.org/rfcs/rfc1951.html> and
1573F<http://www.faqs.org/rfcs/rfc1952.html>
1574
1575The I<zlib> compression library was written by Jean-loup Gailly
1576F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1577
1578The primary site for the I<zlib> compression library is
1579F<http://www.zlib.org>.
1580
1581The primary site for gzip is F<http://www.gzip.org>.
1582
25f0751f
PM
1583=head1 AUTHOR
1584
cb7abd7f 1585This module was written by Paul Marquess, F<pmqs@cpan.org>.
25f0751f 1586
25f0751f
PM
1587=head1 MODIFICATION HISTORY
1588
1589See the Changes file.
1590
1591=head1 COPYRIGHT AND LICENSE
25f0751f 1592
f3d3633e 1593Copyright (c) 2005-2014 Paul Marquess. All rights reserved.
25f0751f
PM
1594
1595This program is free software; you can redistribute it and/or
1596modify it under the same terms as Perl itself.
1597