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