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