Upgrade Compression modules to 2.015
[p5sagit/p5-mst-13.2.git] / ext / Compress / Raw / Zlib / lib / Compress / Raw / Zlib.pm
CommitLineData
25f0751f 1
2package Compress::Raw::Zlib;
3
4require 5.004 ;
5require Exporter;
6use AutoLoader;
7use Carp ;
8
9#use Parse::Parameters;
10
11use strict ;
12use warnings ;
13use bytes ;
14our ($VERSION, $XS_VERSION, @ISA, @EXPORT, $AUTOLOAD);
15
9253672d 16$VERSION = '2.015';
25f0751f 17$XS_VERSION = $VERSION;
18$VERSION = eval $VERSION;
19
20@ISA = qw(Exporter);
21# Items to export into callers namespace by default. Note: do not export
22# names by default without a very good reason. Use EXPORT_OK instead.
23# Do not simply export all your public functions/methods/constants.
24@EXPORT = qw(
25 adler32 crc32
26
27 ZLIB_VERSION
28 ZLIB_VERNUM
29
30 DEF_WBITS
31 OS_CODE
32
33 MAX_MEM_LEVEL
34 MAX_WBITS
35
36 Z_ASCII
37 Z_BEST_COMPRESSION
38 Z_BEST_SPEED
39 Z_BINARY
40 Z_BLOCK
41 Z_BUF_ERROR
42 Z_DATA_ERROR
43 Z_DEFAULT_COMPRESSION
44 Z_DEFAULT_STRATEGY
45 Z_DEFLATED
46 Z_ERRNO
47 Z_FILTERED
48 Z_FIXED
49 Z_FINISH
50 Z_FULL_FLUSH
51 Z_HUFFMAN_ONLY
52 Z_MEM_ERROR
53 Z_NEED_DICT
54 Z_NO_COMPRESSION
55 Z_NO_FLUSH
56 Z_NULL
57 Z_OK
58 Z_PARTIAL_FLUSH
59 Z_RLE
60 Z_STREAM_END
61 Z_STREAM_ERROR
62 Z_SYNC_FLUSH
63 Z_UNKNOWN
64 Z_VERSION_ERROR
e11a3f9e 65
66 WANT_GZIP
67 WANT_GZIP_OR_ZLIB
25f0751f 68);
69
e11a3f9e 70use constant WANT_GZIP => 16;
71use constant WANT_GZIP_OR_ZLIB => 32;
25f0751f 72
73sub AUTOLOAD {
74 my($constname);
75 ($constname = $AUTOLOAD) =~ s/.*:://;
76 my ($error, $val) = constant($constname);
77 Carp::croak $error if $error;
78 no strict 'refs';
79 *{$AUTOLOAD} = sub { $val };
80 goto &{$AUTOLOAD};
81}
82
83use constant FLAG_APPEND => 1 ;
84use constant FLAG_CRC => 2 ;
85use constant FLAG_ADLER => 4 ;
86use constant FLAG_CONSUME_INPUT => 8 ;
9253672d 87use constant FLAG_LIMIT_OUTPUT => 16 ;
25f0751f 88
89eval {
90 require XSLoader;
91 XSLoader::load('Compress::Raw::Zlib', $XS_VERSION);
92 1;
93}
94or do {
95 require DynaLoader;
96 local @ISA = qw(DynaLoader);
97 bootstrap Compress::Raw::Zlib $XS_VERSION ;
98};
99
100
101use constant Parse_any => 0x01;
102use constant Parse_unsigned => 0x02;
103use constant Parse_signed => 0x04;
104use constant Parse_boolean => 0x08;
105use constant Parse_string => 0x10;
106use constant Parse_custom => 0x12;
107
108use constant Parse_store_ref => 0x100 ;
109
110use constant OFF_PARSED => 0 ;
111use constant OFF_TYPE => 1 ;
112use constant OFF_DEFAULT => 2 ;
113use constant OFF_FIXED => 3 ;
114use constant OFF_FIRST_ONLY => 4 ;
115use constant OFF_STICKY => 5 ;
116
117
118
119sub ParseParameters
120{
121 my $level = shift || 0 ;
122
123 my $sub = (caller($level + 1))[3] ;
124 #local $Carp::CarpLevel = 1 ;
125 my $p = new Compress::Raw::Zlib::Parameters() ;
126 $p->parse(@_)
127 or croak "$sub: $p->{Error}" ;
128
129 return $p;
130}
131
132
133sub Compress::Raw::Zlib::Parameters::new
134{
135 my $class = shift ;
136
137 my $obj = { Error => '',
138 Got => {},
139 } ;
140
141 #return bless $obj, ref($class) || $class || __PACKAGE__ ;
142 return bless $obj, 'Compress::Raw::Zlib::Parameters' ;
143}
144
145sub Compress::Raw::Zlib::Parameters::setError
146{
147 my $self = shift ;
148 my $error = shift ;
149 my $retval = @_ ? shift : undef ;
150
151 $self->{Error} = $error ;
152 return $retval;
153}
154
155#sub getError
156#{
157# my $self = shift ;
158# return $self->{Error} ;
159#}
160
161sub Compress::Raw::Zlib::Parameters::parse
162{
163 my $self = shift ;
164
165 my $default = shift ;
166
167 my $got = $self->{Got} ;
168 my $firstTime = keys %{ $got } == 0 ;
169
170 my (@Bad) ;
171 my @entered = () ;
172
173 # Allow the options to be passed as a hash reference or
174 # as the complete hash.
175 if (@_ == 0) {
176 @entered = () ;
177 }
178 elsif (@_ == 1) {
179 my $href = $_[0] ;
180 return $self->setError("Expected even number of parameters, got 1")
181 if ! defined $href or ! ref $href or ref $href ne "HASH" ;
182
183 foreach my $key (keys %$href) {
184 push @entered, $key ;
185 push @entered, \$href->{$key} ;
186 }
187 }
188 else {
189 my $count = @_;
190 return $self->setError("Expected even number of parameters, got $count")
191 if $count % 2 != 0 ;
192
193 for my $i (0.. $count / 2 - 1) {
194 push @entered, $_[2* $i] ;
195 push @entered, \$_[2* $i+1] ;
196 }
197 }
198
199
200 while (my ($key, $v) = each %$default)
201 {
202 croak "need 4 params [@$v]"
203 if @$v != 4 ;
204
205 my ($first_only, $sticky, $type, $value) = @$v ;
206 my $x ;
207 $self->_checkType($key, \$value, $type, 0, \$x)
208 or return undef ;
209
210 $key = lc $key;
211
212 if ($firstTime || ! $sticky) {
213 $got->{$key} = [0, $type, $value, $x, $first_only, $sticky] ;
214 }
215
216 $got->{$key}[OFF_PARSED] = 0 ;
217 }
218
219 for my $i (0.. @entered / 2 - 1) {
220 my $key = $entered[2* $i] ;
221 my $value = $entered[2* $i+1] ;
222
223 #print "Key [$key] Value [$value]" ;
224 #print defined $$value ? "[$$value]\n" : "[undef]\n";
225
226 $key =~ s/^-// ;
227 my $canonkey = lc $key;
228
229 if ($got->{$canonkey} && ($firstTime ||
230 ! $got->{$canonkey}[OFF_FIRST_ONLY] ))
231 {
232 my $type = $got->{$canonkey}[OFF_TYPE] ;
233 my $s ;
234 $self->_checkType($key, $value, $type, 1, \$s)
235 or return undef ;
236 #$value = $$value unless $type & Parse_store_ref ;
237 $value = $$value ;
238 $got->{$canonkey} = [1, $type, $value, $s] ;
239 }
240 else
241 { push (@Bad, $key) }
242 }
243
244 if (@Bad) {
245 my ($bad) = join(", ", @Bad) ;
246 return $self->setError("unknown key value(s) @Bad") ;
247 }
248
249 return 1;
250}
251
252sub Compress::Raw::Zlib::Parameters::_checkType
253{
254 my $self = shift ;
255
256 my $key = shift ;
257 my $value = shift ;
258 my $type = shift ;
259 my $validate = shift ;
260 my $output = shift;
261
262 #local $Carp::CarpLevel = $level ;
263 #print "PARSE $type $key $value $validate $sub\n" ;
264 if ( $type & Parse_store_ref)
265 {
266 #$value = $$value
267 # if ref ${ $value } ;
268
269 $$output = $value ;
270 return 1;
271 }
272
273 $value = $$value ;
274
275 if ($type & Parse_any)
276 {
277 $$output = $value ;
278 return 1;
279 }
280 elsif ($type & Parse_unsigned)
281 {
282 return $self->setError("Parameter '$key' must be an unsigned int, got 'undef'")
283 if $validate && ! defined $value ;
284 return $self->setError("Parameter '$key' must be an unsigned int, got '$value'")
285 if $validate && $value !~ /^\d+$/;
286
287 $$output = defined $value ? $value : 0 ;
288 return 1;
289 }
290 elsif ($type & Parse_signed)
291 {
292 return $self->setError("Parameter '$key' must be a signed int, got 'undef'")
293 if $validate && ! defined $value ;
294 return $self->setError("Parameter '$key' must be a signed int, got '$value'")
295 if $validate && $value !~ /^-?\d+$/;
296
297 $$output = defined $value ? $value : 0 ;
298 return 1 ;
299 }
300 elsif ($type & Parse_boolean)
301 {
302 return $self->setError("Parameter '$key' must be an int, got '$value'")
303 if $validate && defined $value && $value !~ /^\d*$/;
304 $$output = defined $value ? $value != 0 : 0 ;
305 return 1;
306 }
307 elsif ($type & Parse_string)
308 {
309 $$output = defined $value ? $value : "" ;
310 return 1;
311 }
312
313 $$output = $value ;
314 return 1;
315}
316
317
318
319sub Compress::Raw::Zlib::Parameters::parsed
320{
321 my $self = shift ;
322 my $name = shift ;
323
324 return $self->{Got}{lc $name}[OFF_PARSED] ;
325}
326
327sub Compress::Raw::Zlib::Parameters::value
328{
329 my $self = shift ;
330 my $name = shift ;
331
332 if (@_)
333 {
334 $self->{Got}{lc $name}[OFF_PARSED] = 1;
335 $self->{Got}{lc $name}[OFF_DEFAULT] = $_[0] ;
336 $self->{Got}{lc $name}[OFF_FIXED] = $_[0] ;
337 }
338
339 return $self->{Got}{lc $name}[OFF_FIXED] ;
340}
341
342sub Compress::Raw::Zlib::Deflate::new
343{
344 my $pkg = shift ;
345 my ($got) = ParseParameters(0,
346 {
347 'AppendOutput' => [1, 1, Parse_boolean, 0],
348 'CRC32' => [1, 1, Parse_boolean, 0],
349 'ADLER32' => [1, 1, Parse_boolean, 0],
350 'Bufsize' => [1, 1, Parse_unsigned, 4096],
351
352 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
353 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
354 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
355 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
356 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
357 'Dictionary' => [1, 1, Parse_any, ""],
358 }, @_) ;
359
360
361 croak "Compress::Raw::Zlib::Deflate::new: Bufsize must be >= 1, you specified " .
362 $got->value('Bufsize')
363 unless $got->value('Bufsize') >= 1;
364
365 my $flags = 0 ;
366 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
367 $flags |= FLAG_CRC if $got->value('CRC32') ;
368 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
369
e11a3f9e 370 my $windowBits = $got->value('WindowBits');
371 $windowBits += MAX_WBITS()
372 if ($windowBits & MAX_WBITS()) == 0 ;
373
25f0751f 374 _deflateInit($flags,
375 $got->value('Level'),
376 $got->value('Method'),
e11a3f9e 377 $windowBits,
25f0751f 378 $got->value('MemLevel'),
379 $got->value('Strategy'),
380 $got->value('Bufsize'),
381 $got->value('Dictionary')) ;
382
383}
384
385sub Compress::Raw::Zlib::Inflate::new
386{
387 my $pkg = shift ;
388 my ($got) = ParseParameters(0,
389 {
390 'AppendOutput' => [1, 1, Parse_boolean, 0],
9253672d 391 'LimitOutput' => [1, 1, Parse_boolean, 0],
25f0751f 392 'CRC32' => [1, 1, Parse_boolean, 0],
393 'ADLER32' => [1, 1, Parse_boolean, 0],
394 'ConsumeInput' => [1, 1, Parse_boolean, 1],
395 'Bufsize' => [1, 1, Parse_unsigned, 4096],
396
397 'WindowBits' => [1, 1, Parse_signed, MAX_WBITS()],
398 'Dictionary' => [1, 1, Parse_any, ""],
399 }, @_) ;
400
401
402 croak "Compress::Raw::Zlib::Inflate::new: Bufsize must be >= 1, you specified " .
403 $got->value('Bufsize')
404 unless $got->value('Bufsize') >= 1;
405
406 my $flags = 0 ;
407 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
408 $flags |= FLAG_CRC if $got->value('CRC32') ;
409 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
410 $flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
9253672d 411 $flags |= FLAG_LIMIT_OUTPUT if $got->value('LimitOutput') ;
412
25f0751f 413
e11a3f9e 414 my $windowBits = $got->value('WindowBits');
415 $windowBits += MAX_WBITS()
416 if ($windowBits & MAX_WBITS()) == 0 ;
417
418 _inflateInit($flags, $windowBits, $got->value('Bufsize'),
25f0751f 419 $got->value('Dictionary')) ;
420}
421
422sub Compress::Raw::Zlib::InflateScan::new
423{
424 my $pkg = shift ;
425 my ($got) = ParseParameters(0,
426 {
427 'CRC32' => [1, 1, Parse_boolean, 0],
428 'ADLER32' => [1, 1, Parse_boolean, 0],
429 'Bufsize' => [1, 1, Parse_unsigned, 4096],
430
431 'WindowBits' => [1, 1, Parse_signed, -MAX_WBITS()],
432 'Dictionary' => [1, 1, Parse_any, ""],
433 }, @_) ;
434
435
436 croak "Compress::Raw::Zlib::InflateScan::new: Bufsize must be >= 1, you specified " .
437 $got->value('Bufsize')
438 unless $got->value('Bufsize') >= 1;
439
440 my $flags = 0 ;
441 #$flags |= FLAG_APPEND if $got->value('AppendOutput') ;
442 $flags |= FLAG_CRC if $got->value('CRC32') ;
443 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
444 #$flags |= FLAG_CONSUME_INPUT if $got->value('ConsumeInput') ;
445
446 _inflateScanInit($flags, $got->value('WindowBits'), $got->value('Bufsize'),
447 '') ;
448}
449
450sub Compress::Raw::Zlib::inflateScanStream::createDeflateStream
451{
452 my $pkg = shift ;
453 my ($got) = ParseParameters(0,
454 {
455 'AppendOutput' => [1, 1, Parse_boolean, 0],
456 'CRC32' => [1, 1, Parse_boolean, 0],
457 'ADLER32' => [1, 1, Parse_boolean, 0],
458 'Bufsize' => [1, 1, Parse_unsigned, 4096],
459
460 'Level' => [1, 1, Parse_signed, Z_DEFAULT_COMPRESSION()],
461 'Method' => [1, 1, Parse_unsigned, Z_DEFLATED()],
462 'WindowBits' => [1, 1, Parse_signed, - MAX_WBITS()],
463 'MemLevel' => [1, 1, Parse_unsigned, MAX_MEM_LEVEL()],
464 'Strategy' => [1, 1, Parse_unsigned, Z_DEFAULT_STRATEGY()],
465 }, @_) ;
466
467 croak "Compress::Raw::Zlib::InflateScan::createDeflateStream: Bufsize must be >= 1, you specified " .
468 $got->value('Bufsize')
469 unless $got->value('Bufsize') >= 1;
470
471 my $flags = 0 ;
472 $flags |= FLAG_APPEND if $got->value('AppendOutput') ;
473 $flags |= FLAG_CRC if $got->value('CRC32') ;
474 $flags |= FLAG_ADLER if $got->value('ADLER32') ;
475
476 $pkg->_createDeflateStream($flags,
477 $got->value('Level'),
478 $got->value('Method'),
479 $got->value('WindowBits'),
480 $got->value('MemLevel'),
481 $got->value('Strategy'),
482 $got->value('Bufsize'),
483 ) ;
484
485}
486
487sub Compress::Raw::Zlib::inflateScanStream::inflate
488{
489 my $self = shift ;
490 my $buffer = $_[1];
491 my $eof = $_[2];
492
493 my $status = $self->scan(@_);
494
495 if ($status == Z_OK() && $_[2]) {
496 my $byte = ' ';
497
498 $status = $self->scan(\$byte, $_[1]) ;
499 }
500
501 return $status ;
502}
503
504sub Compress::Raw::Zlib::deflateStream::deflateParams
505{
506 my $self = shift ;
507 my ($got) = ParseParameters(0, {
508 'Level' => [1, 1, Parse_signed, undef],
509 'Strategy' => [1, 1, Parse_unsigned, undef],
510 'Bufsize' => [1, 1, Parse_unsigned, undef],
511 },
512 @_) ;
513
514 croak "Compress::Raw::Zlib::deflateParams needs Level and/or Strategy"
515 unless $got->parsed('Level') + $got->parsed('Strategy') +
516 $got->parsed('Bufsize');
517
518 croak "Compress::Raw::Zlib::Inflate::deflateParams: Bufsize must be >= 1, you specified " .
519 $got->value('Bufsize')
520 if $got->parsed('Bufsize') && $got->value('Bufsize') <= 1;
521
522 my $flags = 0;
523 $flags |= 1 if $got->parsed('Level') ;
524 $flags |= 2 if $got->parsed('Strategy') ;
525 $flags |= 4 if $got->parsed('Bufsize') ;
526
527 $self->_deflateParams($flags, $got->value('Level'),
528 $got->value('Strategy'), $got->value('Bufsize'));
529
530}
531
532
533# Autoload methods go after __END__, and are processed by the autosplit program.
534
5351;
536__END__
537
538
539=head1 NAME
540
541Compress::Raw::Zlib - Low-Level Interface to zlib compression library
542
543=head1 SYNOPSIS
544
545 use Compress::Raw::Zlib ;
546
547 ($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) ;
548 $status = $d->deflate($input, $output) ;
549 $status = $d->flush($output [, $flush_type]) ;
550 $d->deflateParams(OPTS) ;
551 $d->deflateTune(OPTS) ;
552 $d->dict_adler() ;
553 $d->crc32() ;
554 $d->adler32() ;
555 $d->total_in() ;
556 $d->total_out() ;
557 $d->msg() ;
558 $d->get_Strategy();
559 $d->get_Level();
560 $d->get_BufSize();
561
562 ($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] ) ;
563 $status = $i->inflate($input, $output [, $eof]) ;
564 $status = $i->inflateSync($input) ;
565 $i->dict_adler() ;
566 $d->crc32() ;
567 $d->adler32() ;
568 $i->total_in() ;
569 $i->total_out() ;
570 $i->msg() ;
571 $d->get_BufSize();
572
573 $crc = adler32($buffer [,$crc]) ;
574 $crc = crc32($buffer [,$crc]) ;
575
576 $crc = adler32_combine($crc1, $crc2, $len2)l
577 $crc = crc32_combine($adler1, $adler2, $len2)
578
579 ZLIB_VERSION
580 ZLIB_VERNUM
581
582=head1 DESCRIPTION
583
584The I<Compress::Raw::Zlib> module provides a Perl interface to the I<zlib>
585compression library (see L</AUTHOR> for details about where to get
586I<zlib>).
587
25f0751f 588=head1 Compress::Raw::Zlib::Deflate
589
590This section defines an interface that allows in-memory compression using
591the I<deflate> interface provided by zlib.
592
593Here is a definition of the interface available:
594
25f0751f 595=head2 B<($d, $status) = new Compress::Raw::Zlib::Deflate( [OPT] ) >
596
597Initialises a deflation object.
598
599If you are familiar with the I<zlib> library, it combines the
600features of the I<zlib> functions C<deflateInit>, C<deflateInit2>
601and C<deflateSetDictionary>.
602
603If successful, it will return the initialised deflation object, C<$d>
604and a C<$status> of C<Z_OK> in a list context. In scalar context it
605returns the deflation object, C<$d>, only.
606
607If not successful, the returned deflation object, C<$d>, will be
608I<undef> and C<$status> will hold the a I<zlib> error code.
609
610The function optionally takes a number of named options specified as
e7d45986 611C<< Name => value >> pairs. This allows individual options to be
25f0751f 612tailored without having to specify them all in the parameter list.
613
614For backward compatibility, it is also possible to pass the parameters
615as a reference to a hash containing the name=>value pairs.
616
617Below is a list of the valid options:
618
619=over 5
620
621=item B<-Level>
622
623Defines the compression level. Valid values are 0 through 9,
624C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
625C<Z_DEFAULT_COMPRESSION>.
626
e11a3f9e 627The default is C<Z_DEFAULT_COMPRESSION>.
25f0751f 628
629=item B<-Method>
630
631Defines the compression method. The only valid value at present (and
e7d45986 632the default) is Z_DEFLATED.
25f0751f 633
634=item B<-WindowBits>
635
e11a3f9e 636To compress an RFC 1950 data stream, set C<WindowBits> to a positive
637number between 8 and 15.
638
639To compress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
640
641To compress an RFC 1952 data stream (i.e. gzip), set C<WindowBits> to
642C<WANT_GZIP>.
643
25f0751f 644For a definition of the meaning and valid values for C<WindowBits>
645refer to the I<zlib> documentation for I<deflateInit2>.
646
e11a3f9e 647Defaults to C<MAX_WBITS>.
25f0751f 648
649=item B<-MemLevel>
650
651For a definition of the meaning and valid values for C<MemLevel>
652refer to the I<zlib> documentation for I<deflateInit2>.
653
e7d45986 654Defaults to MAX_MEM_LEVEL.
25f0751f 655
656=item B<-Strategy>
657
658Defines the strategy used to tune the compression. The valid values are
659C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED>, C<Z_RLE>, C<Z_FIXED> and
660C<Z_HUFFMAN_ONLY>.
661
e7d45986 662The default is Z_DEFAULT_STRATEGY.
25f0751f 663
664=item B<-Dictionary>
665
666When a dictionary is specified I<Compress::Raw::Zlib> will automatically
667call C<deflateSetDictionary> directly after calling C<deflateInit>. The
668Adler32 value for the dictionary can be obtained by calling the method
669C<$d-E<gt>dict_adler()>.
670
671The default is no dictionary.
672
673=item B<-Bufsize>
674
675Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
676and C<$d-E<gt>flush> methods. If the buffer has to be
677reallocated to increase the size, it will grow in increments of
678C<Bufsize>.
679
680The default buffer size is 4096.
681
682=item B<-AppendOutput>
683
684This option controls how data is written to the output buffer by the
685C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
686
687If the C<AppendOutput> option is set to false, the output buffers in the
688C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods will be truncated before
689uncompressed data is written to them.
690
691If the option is set to true, uncompressed data will be appended to the
692output buffer in the C<$d-E<gt>deflate> and C<$d-E<gt>flush> methods.
693
694This option defaults to false.
695
696=item B<-CRC32>
697
698If set to true, a crc32 checksum of the uncompressed data will be
699calculated. Use the C<$d-E<gt>crc32> method to retrieve this value.
700
701This option defaults to false.
702
25f0751f 703=item B<-ADLER32>
704
705If set to true, an adler32 checksum of the uncompressed data will be
706calculated. Use the C<$d-E<gt>adler32> method to retrieve this value.
707
708This option defaults to false.
709
25f0751f 710=back
711
712Here is an example of using the C<Compress::Raw::Zlib::Deflate> optional
713parameter list to override the default buffer size and compression
714level. All other options will take their default values.
715
716 my $d = new Compress::Raw::Zlib::Deflate ( -Bufsize => 300,
717 -Level => Z_BEST_SPEED ) ;
718
25f0751f 719=head2 B<$status = $d-E<gt>deflate($input, $output)>
720
721Deflates the contents of C<$input> and writes the compressed data to
722C<$output>.
723
724The C<$input> and C<$output> parameters can be either scalars or scalar
725references.
726
727When finished, C<$input> will be completely processed (assuming there
728were no errors). If the deflation was successful it writes the deflated
729data to C<$output> and returns a status value of C<Z_OK>.
730
731On error, it returns a I<zlib> error code.
732
733If the C<AppendOutput> option is set to true in the constructor for
734the C<$d> object, the compressed data will be appended to C<$output>. If
735it is false, C<$output> will be truncated before any compressed data is
736written to it.
737
738B<Note>: This method will not necessarily write compressed data to
739C<$output> every time it is called. So do not assume that there has been
740an error if the contents of C<$output> is empty on returning from
741this method. As long as the return code from the method is C<Z_OK>,
742the deflate has succeeded.
743
744=head2 B<$status = $d-E<gt>flush($output [, $flush_type]) >
745
746Typically used to finish the deflation. Any pending output will be
747written to C<$output>.
748
749Returns C<Z_OK> if successful.
750
751Note that flushing can seriously degrade the compression ratio, so it
752should only be used to terminate a decompression (using C<Z_FINISH>) or
753when you want to create a I<full flush point> (using C<Z_FULL_FLUSH>).
754
755By default the C<flush_type> used is C<Z_FINISH>. Other valid values
756for C<flush_type> are C<Z_NO_FLUSH>, C<Z_PARTIAL_FLUSH>, C<Z_SYNC_FLUSH>
757and C<Z_FULL_FLUSH>. It is strongly recommended that you only set the
758C<flush_type> parameter if you fully understand the implications of
759what it does. See the C<zlib> documentation for details.
760
761If the C<AppendOutput> option is set to true in the constructor for
762the C<$d> object, the compressed data will be appended to C<$output>. If
763it is false, C<$output> will be truncated before any compressed data is
764written to it.
765
766=head2 B<$status = $d-E<gt>deflateParams([OPT])>
767
768Change settings for the deflate object C<$d>.
769
770The list of the valid options is shown below. Options not specified
771will remain unchanged.
772
25f0751f 773=over 5
774
775=item B<-Level>
776
777Defines the compression level. Valid values are 0 through 9,
778C<Z_NO_COMPRESSION>, C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and
779C<Z_DEFAULT_COMPRESSION>.
780
781=item B<-Strategy>
782
783Defines the strategy used to tune the compression. The valid values are
784C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
785
786=item B<-BufSize>
787
788Sets the initial size for the output buffer used by the C<$d-E<gt>deflate>
789and C<$d-E<gt>flush> methods. If the buffer has to be
790reallocated to increase the size, it will grow in increments of
791C<Bufsize>.
792
25f0751f 793=back
794
795=head2 B<$status = $d-E<gt>deflateTune($good_length, $max_lazy, $nice_length, $max_chain)>
796
797Tune the internal settings for the deflate object C<$d>. This option is
798only available if you are running zlib 1.2.2.3 or better.
799
800Refer to the documentation in zlib.h for instructions on how to fly
801C<deflateTune>.
802
803=head2 B<$d-E<gt>dict_adler()>
804
805Returns the adler32 value for the dictionary.
806
807=head2 B<$d-E<gt>crc32()>
808
809Returns the crc32 value for the uncompressed data to date.
810
811If the C<CRC32> option is not enabled in the constructor for this object,
812this method will always return 0;
813
814=head2 B<$d-E<gt>adler32()>
815
816Returns the adler32 value for the uncompressed data to date.
817
818=head2 B<$d-E<gt>msg()>
819
820Returns the last error message generated by zlib.
821
822=head2 B<$d-E<gt>total_in()>
823
824Returns the total number of bytes uncompressed bytes input to deflate.
825
826=head2 B<$d-E<gt>total_out()>
827
828Returns the total number of compressed bytes output from deflate.
829
830=head2 B<$d-E<gt>get_Strategy()>
831
832Returns the deflation strategy currently used. Valid values are
833C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>.
834
25f0751f 835=head2 B<$d-E<gt>get_Level()>
836
837Returns the compression level being used.
838
839=head2 B<$d-E<gt>get_BufSize()>
840
841Returns the buffer size used to carry out the compression.
842
843=head2 Example
844
25f0751f 845Here is a trivial example of using C<deflate>. It simply reads standard
846input, deflates it and writes it to standard output.
847
848 use strict ;
849 use warnings ;
850
851 use Compress::Raw::Zlib ;
852
853 binmode STDIN;
854 binmode STDOUT;
855 my $x = new Compress::Raw::Zlib::Deflate
856 or die "Cannot create a deflation stream\n" ;
857
858 my ($output, $status) ;
859 while (<>)
860 {
861 $status = $x->deflate($_, $output) ;
862
863 $status == Z_OK
864 or die "deflation failed\n" ;
865
866 print $output ;
867 }
868
869 $status = $x->flush($output) ;
870
871 $status == Z_OK
872 or die "deflation failed\n" ;
873
874 print $output ;
875
876=head1 Compress::Raw::Zlib::Inflate
877
878This section defines an interface that allows in-memory uncompression using
879the I<inflate> interface provided by zlib.
880
881Here is a definition of the interface:
882
25f0751f 883=head2 B< ($i, $status) = new Compress::Raw::Zlib::Inflate( [OPT] ) >
884
885Initialises an inflation object.
886
887In a list context it returns the inflation object, C<$i>, and the
888I<zlib> status code (C<$status>). In a scalar context it returns the
889inflation object only.
890
891If successful, C<$i> will hold the inflation object and C<$status> will
892be C<Z_OK>.
893
894If not successful, C<$i> will be I<undef> and C<$status> will hold the
895I<zlib> error code.
896
897The function optionally takes a number of named options specified as
e7d45986 898C<< -Name => value >> pairs. This allows individual options to be
25f0751f 899tailored without having to specify them all in the parameter list.
900
901For backward compatibility, it is also possible to pass the parameters
e7d45986 902as a reference to a hash containing the C<< name=>value >> pairs.
25f0751f 903
904Here is a list of the valid options:
905
906=over 5
907
908=item B<-WindowBits>
909
910To uncompress an RFC 1950 data stream, set C<WindowBits> to a positive
e11a3f9e 911number between 8 and 15.
25f0751f 912
913To uncompress an RFC 1951 data stream, set C<WindowBits> to C<-MAX_WBITS>.
914
e11a3f9e 915To uncompress an RFC 1952 data stream (i.e. gzip), set C<WindowBits> to
916C<WANT_GZIP>.
917
918To auto-detect and uncompress an RFC 1950 or RFC 1952 data stream (i.e.
919gzip), set C<WindowBits> to C<WANT_GZIP_OR_ZLIB>.
920
25f0751f 921For a full definition of the meaning and valid values for C<WindowBits>
922refer to the I<zlib> documentation for I<inflateInit2>.
923
e11a3f9e 924Defaults to C<MAX_WBITS>.
25f0751f 925
926=item B<-Bufsize>
927
928Sets the initial size for the output buffer used by the C<$i-E<gt>inflate>
929method. If the output buffer in this method has to be reallocated to
930increase the size, it will grow in increments of C<Bufsize>.
931
932Default is 4096.
933
934=item B<-Dictionary>
935
936The default is no dictionary.
937
938=item B<-AppendOutput>
939
940This option controls how data is written to the output buffer by the
941C<$i-E<gt>inflate> method.
942
943If the option is set to false, the output buffer in the C<$i-E<gt>inflate>
944method will be truncated before uncompressed data is written to it.
945
946If the option is set to true, uncompressed data will be appended to the
947output buffer by the C<$i-E<gt>inflate> method.
948
949This option defaults to false.
950
25f0751f 951=item B<-CRC32>
952
953If set to true, a crc32 checksum of the uncompressed data will be
954calculated. Use the C<$i-E<gt>crc32> method to retrieve this value.
955
956This option defaults to false.
957
958=item B<-ADLER32>
959
960If set to true, an adler32 checksum of the uncompressed data will be
961calculated. Use the C<$i-E<gt>adler32> method to retrieve this value.
962
963This option defaults to false.
964
965=item B<-ConsumeInput>
966
967If set to true, this option will remove compressed data from the input
968buffer of the the C< $i-E<gt>inflate > method as the inflate progresses.
969
970This option can be useful when you are processing compressed data that is
971embedded in another file/buffer. In this case the data that immediately
972follows the compressed stream will be left in the input buffer.
973
974This option defaults to true.
975
976=back
977
978Here is an example of using an optional parameter to override the default
979buffer size.
980
981 my ($i, $status) = new Compress::Raw::Zlib::Inflate( -Bufsize => 300 ) ;
982
983=head2 B< $status = $i-E<gt>inflate($input, $output [,$eof]) >
984
985Inflates the complete contents of C<$input> and writes the uncompressed
986data to C<$output>. The C<$input> and C<$output> parameters can either be
987scalars or scalar references.
988
989Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
990compressed data has been successfully reached.
991
992If not successful C<$status> will hold the I<zlib> error code.
993
994If the C<ConsumeInput> option has been set to true when the
995C<Compress::Raw::Zlib::Inflate> object is created, the C<$input> parameter
996is modified by C<inflate>. On completion it will contain what remains
997of the input buffer after inflation. In practice, this means that when
998the return status is C<Z_OK> the C<$input> parameter will contain an
999empty string, and when the return status is C<Z_STREAM_END> the C<$input>
1000parameter will contains what (if anything) was stored in the input buffer
1001after the deflated data stream.
1002
1003This feature is useful when processing a file format that encapsulates
1004a compressed data stream (e.g. gzip, zip) and there is useful data
1005immediately after the deflation stream.
1006
1007If the C<AppendOutput> option is set to true in the constructor for
1008this object, the uncompressed data will be appended to C<$output>. If
1009it is false, C<$output> will be truncated before any uncompressed data
1010is written to it.
1011
1012The C<$eof> parameter needs a bit of explanation.
1013
1014Prior to version 1.2.0, zlib assumed that there was at least one trailing
1015byte immediately after the compressed data stream when it was carrying out
1016decompression. This normally isn't a problem because the majority of zlib
1017applications guarantee that there will be data directly after the
1018compressed data stream. For example, both gzip (RFC 1950) and zip both
1019define trailing data that follows the compressed data stream.
1020
1021The C<$eof> parameter only needs to be used if B<all> of the following
1022conditions apply
1023
1024=over 5
1025
1026=item 1
1027
1028You are either using a copy of zlib that is older than version 1.2.0 or you
1029want your application code to be able to run with as many different
1030versions of zlib as possible.
1031
1032=item 2
1033
1034You have set the C<WindowBits> parameter to C<-MAX_WBITS> in the constructor
1035for this object, i.e. you are uncompressing a raw deflated data stream
1036(RFC 1951).
1037
1038=item 3
1039
1040There is no data immediately after the compressed data stream.
1041
1042=back
1043
1044If B<all> of these are the case, then you need to set the C<$eof> parameter
1045to true on the final call (and only the final call) to C<$i-E<gt>inflate>.
1046
1047If you have built this module with zlib >= 1.2.0, the C<$eof> parameter is
1048ignored. You can still set it if you want, but it won't be used behind the
1049scenes.
1050
1051=head2 B<$status = $i-E<gt>inflateSync($input)>
1052
1053This method can be used to attempt to recover good data from a compressed
1054data stream that is partially corrupt.
1055It scans C<$input> until it reaches either a I<full flush point> or the
1056end of the buffer.
1057
1058If a I<full flush point> is found, C<Z_OK> is returned and C<$input>
1059will be have all data up to the flush point removed. This data can then be
1060passed to the C<$i-E<gt>inflate> method to be uncompressed.
1061
1062Any other return code means that a flush point was not found. If more
1063data is available, C<inflateSync> can be called repeatedly with more
1064compressed data until the flush point is found.
1065
1066Note I<full flush points> are not present by default in compressed
1067data streams. They must have been added explicitly when the data stream
1068was created by calling C<Compress::Deflate::flush> with C<Z_FULL_FLUSH>.
1069
25f0751f 1070=head2 B<$i-E<gt>dict_adler()>
1071
1072Returns the adler32 value for the dictionary.
1073
1074=head2 B<$i-E<gt>crc32()>
1075
1076Returns the crc32 value for the uncompressed data to date.
1077
1078If the C<CRC32> option is not enabled in the constructor for this object,
1079this method will always return 0;
1080
1081=head2 B<$i-E<gt>adler32()>
1082
1083Returns the adler32 value for the uncompressed data to date.
1084
1085If the C<ADLER32> option is not enabled in the constructor for this object,
1086this method will always return 0;
1087
1088=head2 B<$i-E<gt>msg()>
1089
1090Returns the last error message generated by zlib.
1091
1092=head2 B<$i-E<gt>total_in()>
1093
1094Returns the total number of bytes compressed bytes input to inflate.
1095
1096=head2 B<$i-E<gt>total_out()>
1097
1098Returns the total number of uncompressed bytes output from inflate.
1099
1100=head2 B<$d-E<gt>get_BufSize()>
1101
1102Returns the buffer size used to carry out the decompression.
1103
1104=head2 Example
1105
1106Here is an example of using C<inflate>.
1107
1108 use strict ;
1109 use warnings ;
1110
1111 use Compress::Raw::Zlib;
1112
1113 my $x = new Compress::Raw::Zlib::Inflate()
1114 or die "Cannot create a inflation stream\n" ;
1115
1116 my $input = '' ;
1117 binmode STDIN;
1118 binmode STDOUT;
1119
1120 my ($output, $status) ;
1121 while (read(STDIN, $input, 4096))
1122 {
1123 $status = $x->inflate(\$input, $output) ;
1124
1125 print $output
1126 if $status == Z_OK or $status == Z_STREAM_END ;
1127
1128 last if $status != Z_OK ;
1129 }
1130
1131 die "inflation failed\n"
1132 unless $status == Z_STREAM_END ;
1133
1134=head1 CHECKSUM FUNCTIONS
1135
1136Two functions are provided by I<zlib> to calculate checksums. For the
1137Perl interface, the order of the two parameters in both functions has
1138been reversed. This allows both running checksums and one off
1139calculations to be done.
1140
1141 $crc = adler32($buffer [,$crc]) ;
1142 $crc = crc32($buffer [,$crc]) ;
1143
1144The buffer parameters can either be a scalar or a scalar reference.
1145
1146If the $crc parameters is C<undef>, the crc value will be reset.
1147
1148If you have built this module with zlib 1.2.3 or better, two more
1149CRC-related functions are available.
1150
1151 $crc = adler32_combine($crc1, $crc2, $len2)l
1152 $crc = crc32_combine($adler1, $adler2, $len2)
1153
1154These functions allow checksums to be merged.
1155
1156=head1 ACCESSING ZIP FILES
1157
1158Although it is possible (with some effort on your part) to use this
1159module to access .zip files, there is a module on CPAN that will do all
1160the hard work for you. Check out the C<Archive::Zip> module on CPAN at
1161
1162 http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz
1163
25f0751f 1164=head1 CONSTANTS
1165
1166All the I<zlib> constants are automatically imported when you make use
1167of I<Compress::Raw::Zlib>.
1168
25f0751f 1169=head1 SEE ALSO
1170
258133d1 1171L<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::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress>
25f0751f 1172
1173L<Compress::Zlib::FAQ|Compress::Zlib::FAQ>
1174
1175L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>,
1176L<Archive::Tar|Archive::Tar>,
1177L<IO::Zlib|IO::Zlib>
1178
25f0751f 1179For RFC 1950, 1951 and 1952 see
1180F<http://www.faqs.org/rfcs/rfc1950.html>,
1181F<http://www.faqs.org/rfcs/rfc1951.html> and
1182F<http://www.faqs.org/rfcs/rfc1952.html>
1183
1184The I<zlib> compression library was written by Jean-loup Gailly
1185F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>.
1186
1187The primary site for the I<zlib> compression library is
1188F<http://www.zlib.org>.
1189
1190The primary site for gzip is F<http://www.gzip.org>.
1191
25f0751f 1192=head1 AUTHOR
1193
cb7abd7f 1194This module was written by Paul Marquess, F<pmqs@cpan.org>.
25f0751f 1195
25f0751f 1196=head1 MODIFICATION HISTORY
1197
1198See the Changes file.
1199
1200=head1 COPYRIGHT AND LICENSE
25f0751f 1201
d54256af 1202Copyright (c) 2005-2008 Paul Marquess. All rights reserved.
25f0751f 1203
1204This program is free software; you can redistribute it and/or
1205modify it under the same terms as Perl itself.
1206