home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2006 December / PCpro_2006_12.ISO / ossdvd / server / Perl2 / site / lib / Compress / Zlib.pm
Encoding:
Perl POD Document  |  2002-12-01  |  26.7 KB  |  1,017 lines

  1. # File      : Zlib.pm
  2. # Author  : Paul Marquess
  3. # Created : 13 December 2001
  4. # Version : 1.16
  5. #
  6. #     Copyright (c) 1995-2001 Paul Marquess. All rights reserved.
  7. #     This program is free software; you can redistribute it and/or
  8. #     modify it under the same terms as Perl itself.
  9. #
  10.  
  11. package Compress::Zlib;
  12.  
  13. require 5.004 ;
  14. require Exporter;
  15. require DynaLoader;
  16. use AutoLoader;
  17. use Carp ;
  18. use IO::Handle ;
  19.  
  20. use strict ;
  21. use warnings ;
  22. our ($VERSION, @ISA, @EXPORT, $AUTOLOAD);
  23. our ($deflateDefault, $deflateParamsDefault, $inflateDefault);
  24.  
  25. $VERSION = "1.16" ;
  26.  
  27. @ISA = qw(Exporter DynaLoader);
  28. # Items to export into callers namespace by default. Note: do not export
  29. # names by default without a very good reason. Use EXPORT_OK instead.
  30. # Do not simply export all your public functions/methods/constants.
  31. @EXPORT = qw(
  32.     deflateInit 
  33.     inflateInit
  34.  
  35.     compress 
  36.     uncompress
  37.  
  38.     gzip gunzip
  39.  
  40.     gzopen 
  41.     $gzerrno
  42.  
  43.     adler32 
  44.     crc32
  45.  
  46.     ZLIB_VERSION
  47.  
  48.     DEF_WBITS
  49.     OS_CODE
  50.  
  51.         MAX_MEM_LEVEL
  52.     MAX_WBITS
  53.  
  54.     Z_ASCII
  55.     Z_BEST_COMPRESSION
  56.     Z_BEST_SPEED
  57.     Z_BINARY
  58.     Z_BUF_ERROR
  59.     Z_DATA_ERROR
  60.     Z_DEFAULT_COMPRESSION
  61.     Z_DEFAULT_STRATEGY
  62.         Z_DEFLATED
  63.     Z_ERRNO
  64.     Z_FILTERED
  65.     Z_FINISH
  66.     Z_FULL_FLUSH
  67.     Z_HUFFMAN_ONLY
  68.     Z_MEM_ERROR
  69.     Z_NEED_DICT
  70.     Z_NO_COMPRESSION
  71.     Z_NO_FLUSH
  72.     Z_NULL
  73.     Z_OK
  74.     Z_PARTIAL_FLUSH
  75.     Z_STREAM_END
  76.     Z_STREAM_ERROR
  77.     Z_SYNC_FLUSH
  78.     Z_UNKNOWN
  79.     Z_VERSION_ERROR
  80. );
  81.  
  82.  
  83.  
  84. sub AUTOLOAD {
  85.     my($constname);
  86.     ($constname = $AUTOLOAD) =~ s/.*:://;
  87.     my ($error, $val) = constant($constname);
  88.     Carp::croak $error if $error;
  89.     no strict 'refs';
  90.     *{$AUTOLOAD} = sub { $val };
  91.     goto &{$AUTOLOAD};
  92. }
  93.  
  94. bootstrap Compress::Zlib $VERSION ;
  95.  
  96. # Preloaded methods go here.
  97.  
  98. sub isaFilehandle
  99. {
  100.     my $fh = shift ;
  101.  
  102.     return ((UNIVERSAL::isa($fh,'GLOB') or UNIVERSAL::isa(\$fh,'GLOB')) 
  103.         and defined fileno($fh)  )
  104.  
  105. }
  106.  
  107. sub isaFilename
  108. {
  109.     my $name = shift ;
  110.  
  111.     return (! ref $name and UNIVERSAL::isa(\$name, 'SCALAR')) ;
  112. }
  113.  
  114. sub gzopen
  115. {
  116.     my ($file, $mode) = @_ ;
  117.  
  118.     if (isaFilehandle $file) {
  119.     IO::Handle::flush($file) ;
  120.         gzdopen_(fileno($file), $mode, tell($file)) 
  121.     }
  122.     elsif (isaFilename $file) {
  123.     gzopen_($file, $mode) 
  124.     }
  125.     else {
  126.     croak "gzopen: file parameter is not a filehandle or filename"
  127.     }
  128. }
  129.  
  130. sub ParseParameters($@)
  131. {
  132.     my ($default, @rest) = @_ ;
  133.     my (%got) = %$default ;
  134.     my (@Bad) ;
  135.     my ($key, $value) ;
  136.     my $sub = (caller(1))[3] ;
  137.     my %options = () ;
  138.  
  139.     # allow the options to be passed as a hash reference or
  140.     # as the complete hash.
  141.     if (@rest == 1) {
  142.  
  143.         croak "$sub: parameter is not a reference to a hash"
  144.             if ref $rest[0] ne "HASH" ;
  145.  
  146.         %options = %{ $rest[0] } ;
  147.     }
  148.     elsif (@rest >= 2) {
  149.         %options = @rest ;
  150.     }
  151.  
  152.     while (($key, $value) = each %options)
  153.     {
  154.     $key =~ s/^-// ;
  155.  
  156.         if (exists $default->{$key})
  157.           { $got{$key} = $value }
  158.         else
  159.       { push (@Bad, $key) }
  160.     }
  161.     
  162.     if (@Bad) {
  163.         my ($bad) = join(", ", @Bad) ;
  164.         croak "unknown key value(s) @Bad" ;
  165.     }
  166.  
  167.     return \%got ;
  168. }
  169.  
  170. $deflateDefault = {
  171.     'Level'         =>    Z_DEFAULT_COMPRESSION(),
  172.     'Method'     =>    Z_DEFLATED(),
  173.     'WindowBits' =>    MAX_WBITS(),
  174.     'MemLevel'   =>    MAX_MEM_LEVEL(),
  175.     'Strategy'   =>    Z_DEFAULT_STRATEGY(),
  176.     'Bufsize'    =>    4096,
  177.     'Dictionary' =>    "",
  178.     } ;
  179.  
  180. $deflateParamsDefault = {
  181.     'Level'         =>    Z_DEFAULT_COMPRESSION(),
  182.     'Strategy'   =>    Z_DEFAULT_STRATEGY(),
  183.     } ;
  184.  
  185. $inflateDefault = {
  186.     'WindowBits' =>    MAX_WBITS(),
  187.     'Bufsize'    =>    4096,
  188.     'Dictionary' =>    "",
  189.     } ;
  190.  
  191.  
  192. sub deflateInit
  193. {
  194.     my ($got) = ParseParameters($deflateDefault, @_) ;
  195.     _deflateInit($got->{Level}, $got->{Method}, $got->{WindowBits}, 
  196.         $got->{MemLevel}, $got->{Strategy}, $got->{Bufsize},
  197.         $got->{Dictionary}) ;
  198.         
  199. }
  200.  
  201. sub inflateInit
  202. {
  203.     my ($got) = ParseParameters($inflateDefault, @_) ;
  204.     _inflateInit($got->{WindowBits}, $got->{Bufsize}, $got->{Dictionary}) ;
  205.  
  206. }
  207.  
  208. sub compress($)
  209. {
  210.     my ($x, $output, $out, $err, $in) ;
  211.  
  212.     if (ref $_[0] ) {
  213.         $in = $_[0] ;
  214.     croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
  215.     }
  216.     else {
  217.         $in = \$_[0] ;
  218.     }
  219.  
  220.     if ( (($x, $err) = deflateInit())[1] == Z_OK()) {
  221.  
  222.         ($output, $err) = $x->deflate($in) ;
  223.         return undef unless $err == Z_OK() ;
  224.  
  225.         ($out, $err) = $x->flush() ;
  226.         return undef unless $err == Z_OK() ;
  227.     
  228.         return ($output . $out) ;
  229.  
  230.     }
  231.  
  232.     return undef ;
  233. }
  234.  
  235.  
  236. sub uncompress($)
  237. {
  238.     my ($x, $output, $err, $in) ;
  239.  
  240.     if (ref $_[0] ) {
  241.         $in = $_[0] ;
  242.     croak "not a scalar reference" unless ref $in eq 'SCALAR' ;
  243.     }
  244.     else {
  245.         $in = \$_[0] ;
  246.     }
  247.  
  248.     if ( (($x, $err) = inflateInit())[1] == Z_OK())  {
  249.  
  250.         ($output, $err) = $x->__unc_inflate($in) ;
  251.         return undef unless $err == Z_STREAM_END() ;
  252.  
  253.     return $output ;
  254.     }
  255.  
  256.     return undef ;
  257. }
  258.  
  259.  
  260. # Constants
  261. use constant MAGIC1    => 0x1f ;
  262. use constant MAGIC2    => 0x8b ;
  263. use constant OSCODE    => 3 ;
  264.  
  265. use constant FTEXT    => 1 ;
  266. use constant FHCRC    => 2 ;
  267. use constant FEXTRA    => 4 ;
  268. use constant FNAME    => 8 ;
  269. use constant FCOMMENT    => 16 ;
  270. use constant NULL    => pack("C", 0) ;
  271. use constant RESERVED    => 0xE0 ;
  272.  
  273. use constant MIN_HDR_SIZE => 10 ; # minimum gzip header size
  274.  
  275. sub memGzip
  276. {
  277.   my $x = deflateInit(
  278.                       -Level         => Z_BEST_COMPRESSION(),
  279.                       -WindowBits     =>  - MAX_WBITS(),
  280.                      )
  281.       or return undef ;
  282.  
  283.   # write a minimal gzip header
  284.   my(@m);
  285.   push @m, pack("C" . MIN_HDR_SIZE, 
  286.                 MAGIC1, MAGIC2, Z_DEFLATED(), 0,0,0,0,0,0, OSCODE) ;
  287.  
  288.   # if the deflation buffer isn't a reference, make it one
  289.   my $string = (ref $_[0] ? $_[0] : \$_[0]) ;
  290.  
  291.   my ($output, $status) = $x->deflate($string) ;
  292.   push @m, $output ;
  293.   $status == Z_OK()
  294.       or return undef ;
  295.  
  296.   ($output, $status) = $x->flush() ;
  297.   push @m, $output ;
  298.   $status == Z_OK()
  299.       or return undef ;
  300.  
  301.   push @m, pack("V V", crc32($string), length($$string)) ;
  302.  
  303.   return join "", @m;
  304. }
  305.  
  306. sub _removeGzipHeader
  307. {
  308.     my $string = shift ;
  309.  
  310.     return Z_DATA_ERROR() 
  311.         if length($$string) < MIN_HDR_SIZE ;
  312.  
  313.     my ($magic1, $magic2, $method, $flags, $time, $xflags, $oscode) = 
  314.         unpack ('CCCCVCC', $$string);
  315.  
  316.     return Z_DATA_ERROR()
  317.         unless $magic1 == MAGIC1 and $magic2 == MAGIC2 and
  318.            $method == Z_DEFLATED() and !($flags & RESERVED()) ;
  319.     substr($$string, 0, MIN_HDR_SIZE) = '' ;
  320.  
  321.     # skip extra field
  322.     if ($flags & FEXTRA)
  323.     {
  324.         return Z_DATA_ERROR()
  325.             if length($$string) < 2 ;
  326.  
  327.         my ($extra_len) = unpack ('v', $$string);
  328.         $extra_len += 2;
  329.         return Z_DATA_ERROR()
  330.             if length($$string) < $extra_len ;
  331.  
  332.         substr($$string, 0, $extra_len) = '';
  333.     }
  334.  
  335.     # skip orig name
  336.     if ($flags & FNAME)
  337.     {
  338.         my $name_end = index ($$string, NULL);
  339.         return Z_DATA_ERROR()
  340.            if $name_end == -1 ;
  341.         substr($$string, 0, $name_end + 1) =  '';
  342.     }
  343.  
  344.     # skip comment
  345.     if ($flags & FCOMMENT)
  346.     {
  347.         my $comment_end = index ($$string, NULL);
  348.         return Z_DATA_ERROR()
  349.             if $comment_end == -1 ;
  350.         substr($$string, 0, $comment_end + 1) = '';
  351.     }
  352.  
  353.     # skip header crc
  354.     if ($flags & FHCRC)
  355.     {
  356.         return Z_DATA_ERROR()
  357.             if length ($$string) < 2 ;
  358.         substr($$string, 0, 2) = '';
  359.     }
  360.     
  361.     return Z_OK();
  362. }
  363.  
  364.  
  365. sub memGunzip
  366. {
  367.     # if the buffer isn't a reference, make it one
  368.     my $string = (ref $_[0] ? $_[0] : \$_[0]);
  369.  
  370.     _removeGzipHeader($string) == Z_OK() 
  371.         or return undef;
  372.      
  373.     my $x = inflateInit( -WindowBits => - MAX_WBITS()) 
  374.               or return undef;
  375.     my ($output, $status) = $x->inflate($string);
  376.     return undef 
  377.         unless $status == Z_STREAM_END();
  378.     my ($crc, $len) = unpack ("VV", substr($$string, 0, 8));
  379.     substr($$string, 0, 8) = '';
  380.     return undef 
  381.         unless $len == length($output) and
  382.                $crc == crc32($output);
  383.     return $output;   
  384. }
  385.  
  386. # Autoload methods go after __END__, and are processed by the autosplit program.
  387.  
  388. 1;
  389. __END__
  390.  
  391. =cut
  392.  
  393. =head1 NAME
  394.  
  395. Compress::Zlib - Interface to zlib compression library
  396.  
  397. =head1 SYNOPSIS
  398.  
  399.     use Compress::Zlib ;
  400.  
  401.     ($d, $status) = deflateInit( [OPT] ) ;
  402.     ($out, $status) = $d->deflate($buffer) ;
  403.     ($out, $status) = $d->flush() ;
  404.     $d->dict_adler() ;
  405.  
  406.     ($i, $status) = inflateInit( [OPT] ) ;
  407.     ($out, $status) = $i->inflate($buffer) ;
  408.     $i->dict_adler() ;
  409.  
  410.     $dest = compress($source) ;
  411.     $dest = uncompress($source) ;
  412.  
  413.     $gz = gzopen($filename or filehandle, $mode) ;
  414.     $bytesread = $gz->gzread($buffer [,$size]) ;
  415.     $bytesread = $gz->gzreadline($line) ;
  416.     $byteswritten = $gz->gzwrite($buffer) ;
  417.     $status = $gz->gzflush($flush) ;
  418.     $status = $gz->gzclose() ;
  419.     $errstring = $gz->gzerror() ; 
  420.     $gzerrno
  421.  
  422.     $dest = Compress::Zlib::memGzip($buffer) ;
  423.     $dest = Compress::Zlib::memGunzip($buffer) ;
  424.  
  425.     $crc = adler32($buffer [,$crc]) ;
  426.     $crc = crc32($buffer [,$crc]) ;
  427.  
  428.     ZLIB_VERSION
  429.  
  430. =head1 DESCRIPTION
  431.  
  432. The I<Compress::Zlib> module provides a Perl interface to the I<zlib>
  433. compression library (see L</AUTHOR> for details about where to get
  434. I<zlib>). Most of the functionality provided by I<zlib> is available
  435. in I<Compress::Zlib>.
  436.  
  437. The module can be split into two general areas of functionality, namely
  438. in-memory compression/decompression and read/write access to I<gzip>
  439. files. Each of these areas will be discussed separately below.
  440.  
  441. =head1 DEFLATE 
  442.  
  443. The interface I<Compress::Zlib> provides to the in-memory I<deflate>
  444. (and I<inflate>) functions has been modified to fit into a Perl model.
  445.  
  446. The main difference is that for both inflation and deflation, the Perl
  447. interface will I<always> consume the complete input buffer before
  448. returning. Also the output buffer returned will be automatically grown
  449. to fit the amount of output available.
  450.  
  451. Here is a definition of the interface available:
  452.  
  453.  
  454. =head2 B<($d, $status) = deflateInit( [OPT] )>
  455.  
  456. Initialises a deflation stream. 
  457.  
  458. It combines the features of the I<zlib> functions B<deflateInit>,
  459. B<deflateInit2> and B<deflateSetDictionary>.
  460.  
  461. If successful, it will return the initialised deflation stream, B<$d>
  462. and B<$status> of C<Z_OK> in a list context. In scalar context it
  463. returns the deflation stream, B<$d>, only.
  464.  
  465. If not successful, the returned deflation stream (B<$d>) will be
  466. I<undef> and B<$status> will hold the exact I<zlib> error code.
  467.  
  468. The function optionally takes a number of named options specified as
  469. C<-Name=E<gt>value> pairs. This allows individual options to be
  470. tailored without having to specify them all in the parameter list.
  471.  
  472. For backward compatibility, it is also possible to pass the parameters
  473. as a reference to a hash containing the name=>value pairs.
  474.  
  475. The function takes one optional parameter, a reference to a hash.  The
  476. contents of the hash allow the deflation interface to be tailored.
  477.  
  478. Here is a list of the valid options:
  479.  
  480. =over 5
  481.  
  482. =item B<-Level>
  483.  
  484. Defines the compression level. Valid values are 1 through 9,
  485. C<Z_BEST_SPEED>, C<Z_BEST_COMPRESSION>, and C<Z_DEFAULT_COMPRESSION>.
  486.  
  487. The default is C<-Level =E<gt>Z_DEFAULT_COMPRESSION>.
  488.  
  489. =item B<-Method>
  490.  
  491. Defines the compression method. The only valid value at present (and
  492. the default) is C<-Method =E<gt>Z_DEFLATED>.
  493.  
  494. =item B<-WindowBits>
  495.  
  496. For a definition of the meaning and valid values for B<WindowBits>
  497. refer to the I<zlib> documentation for I<deflateInit2>.
  498.  
  499. Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
  500.  
  501. =item B<-MemLevel>
  502.  
  503. For a definition of the meaning and valid values for B<MemLevel>
  504. refer to the I<zlib> documentation for I<deflateInit2>.
  505.  
  506. Defaults to C<-MemLevel =E<gt>MAX_MEM_LEVEL>.
  507.  
  508. =item B<-Strategy>
  509.  
  510. Defines the strategy used to tune the compression. The valid values are
  511. C<Z_DEFAULT_STRATEGY>, C<Z_FILTERED> and C<Z_HUFFMAN_ONLY>. 
  512.  
  513. The default is C<-Strategy =E<gt>Z_DEFAULT_STRATEGY>.
  514.  
  515. =item B<-Dictionary>
  516.  
  517. When a dictionary is specified I<Compress::Zlib> will automatically
  518. call B<deflateSetDictionary> directly after calling B<deflateInit>. The
  519. Adler32 value for the dictionary can be obtained by calling the method 
  520. C<$d->dict_adler()>.
  521.  
  522. The default is no dictionary.
  523.  
  524. =item B<-Bufsize>
  525.  
  526. Sets the initial size for the deflation buffer. If the buffer has to be
  527. reallocated to increase the size, it will grow in increments of
  528. B<Bufsize>.
  529.  
  530. The default is 4096.
  531.  
  532. =back
  533.  
  534. Here is an example of using the B<deflateInit> optional parameter list
  535. to override the default buffer size and compression level. All other
  536. options will take their default values.
  537.  
  538.     deflateInit( -Bufsize => 300, 
  539.                  -Level => Z_BEST_SPEED  ) ;
  540.  
  541.  
  542. =head2 B<($out, $status) = $d-E<gt>deflate($buffer)>
  543.  
  544.  
  545. Deflates the contents of B<$buffer>. The buffer can either be a scalar
  546. or a scalar reference.  When finished, B<$buffer> will be
  547. completely processed (assuming there were no errors). If the deflation
  548. was successful it returns the deflated output, B<$out>, and a status
  549. value, B<$status>, of C<Z_OK>.
  550.  
  551. On error, B<$out> will be I<undef> and B<$status> will contain the
  552. I<zlib> error code.
  553.  
  554. In a scalar context B<deflate> will return B<$out> only.
  555.  
  556. As with the I<deflate> function in I<zlib>, it is not necessarily the
  557. case that any output will be produced by this method. So don't rely on
  558. the fact that B<$out> is empty for an error test.
  559.  
  560.  
  561. =head2 B<($out, $status) = $d-E<gt>flush([flush_type])>
  562.  
  563. Finishes the deflation. Any pending output will be returned via B<$out>.
  564. B<$status> will have a value C<Z_OK> if successful.
  565.  
  566. In a scalar context B<flush> will return B<$out> only.
  567.  
  568. Note that flushing can degrade the compression ratio, so it should only
  569. be used to terminate a decompression.
  570.  
  571. By default the C<flush_type> used is C<Z_FINISH>. Other valid values
  572. for C<flush_type> are Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH
  573. and Z_FULL_FLUSH. It is strongly recommended that you only set the
  574. C<flush_type> parameter if you fully understand what it does. See the
  575. C<zlib> documentation for details.
  576.  
  577. =head2 B<$d-E<gt>dict_adler()>
  578.  
  579. Returns the adler32 value for the dictionary.
  580.  
  581. =head2 Example
  582.  
  583.  
  584. Here is a trivial example of using B<deflate>. It simply reads standard
  585. input, deflates it and writes it to standard output.
  586.  
  587.     use strict ;
  588.     use warnings ;
  589.  
  590.     use Compress::Zlib ;
  591.  
  592.     binmode STDIN;
  593.     binmode STDOUT;
  594.     my $x = deflateInit()
  595.        or die "Cannot create a deflation stream\n" ;
  596.  
  597.     my ($output, $status) ;
  598.     while (<>)
  599.     {
  600.         ($output, $status) = $x->deflate($_) ;
  601.     
  602.         $status == Z_OK
  603.             or die "deflation failed\n" ;
  604.     
  605.         print $output ;
  606.     }
  607.     
  608.     ($output, $status) = $x->flush() ;
  609.     
  610.     $status == Z_OK
  611.         or die "deflation failed\n" ;
  612.     
  613.     print $output ;
  614.  
  615. =head1 INFLATE
  616.  
  617. Here is a definition of the interface:
  618.  
  619.  
  620. =head2 B<($i, $status) = inflateInit()>
  621.  
  622. Initialises an inflation stream. 
  623.  
  624. In a list context it returns the inflation stream, B<$i>, and the
  625. I<zlib> status code (B<$status>). In a scalar context it returns the
  626. inflation stream only.
  627.  
  628. If successful, B<$i> will hold the inflation stream and B<$status> will
  629. be C<Z_OK>.
  630.  
  631. If not successful, B<$i> will be I<undef> and B<$status> will hold the
  632. I<zlib> error code.
  633.  
  634. The function optionally takes a number of named options specified as
  635. C<-Name=E<gt>value> pairs. This allows individual options to be
  636. tailored without having to specify them all in the parameter list.
  637.  
  638. For backward compatibility, it is also possible to pass the parameters
  639. as a reference to a hash containing the name=>value pairs.
  640.  
  641. The function takes one optional parameter, a reference to a hash.  The
  642. contents of the hash allow the deflation interface to be tailored.
  643.  
  644. Here is a list of the valid options:
  645.  
  646. =over 5
  647.  
  648. =item B<-WindowBits>
  649.  
  650. For a definition of the meaning and valid values for B<WindowBits>
  651. refer to the I<zlib> documentation for I<inflateInit2>.
  652.  
  653. Defaults to C<-WindowBits =E<gt>MAX_WBITS>.
  654.  
  655. =item B<-Bufsize>
  656.  
  657. Sets the initial size for the inflation buffer. If the buffer has to be
  658. reallocated to increase the size, it will grow in increments of
  659. B<Bufsize>. 
  660.  
  661. Default is 4096.
  662.  
  663. =item B<-Dictionary>
  664.  
  665. The default is no dictionary.
  666.  
  667. =back
  668.  
  669. Here is an example of using the B<inflateInit> optional parameter to
  670. override the default buffer size.
  671.  
  672.     inflateInit( -Bufsize => 300 ) ;
  673.  
  674. =head2 B<($out, $status) = $i-E<gt>inflate($buffer)>
  675.  
  676. Inflates the complete contents of B<$buffer>. The buffer can either be
  677. a scalar or a scalar reference.
  678.  
  679. Returns C<Z_OK> if successful and C<Z_STREAM_END> if the end of the
  680. compressed data has been successfully reached. 
  681. If not successful, B<$out> will be I<undef> and B<$status> will hold
  682. the I<zlib> error code.
  683.  
  684. The C<$buffer> parameter is modified by C<inflate>. On completion it
  685. will contain what remains of the input buffer after inflation. This
  686. means that C<$buffer> will be an empty string when the return status is
  687. C<Z_OK>. When the return status is C<Z_STREAM_END> the C<$buffer>
  688. parameter will contains what (if anything) was stored in the input
  689. buffer after the deflated data stream.
  690.  
  691. This feature is useful when processing a file format that encapsulates
  692. a  compressed data stream (e.g. gzip, zip).
  693.  
  694. =head2 B<$i-E<gt>dict_adler()>
  695.  
  696. Returns the adler32 value for the dictionary.
  697.  
  698. =head2 Example
  699.  
  700. Here is an example of using B<inflate>.
  701.  
  702.     use strict ;
  703.     use warnings ;
  704.     
  705.     use Compress::Zlib ;
  706.     
  707.     my $x = inflateInit()
  708.        or die "Cannot create a inflation stream\n" ;
  709.     
  710.     my $input = '' ;
  711.     binmode STDIN;
  712.     binmode STDOUT;
  713.     
  714.     my ($output, $status) ;
  715.     while (read(STDIN, $input, 4096))
  716.     {
  717.         ($output, $status) = $x->inflate(\$input) ;
  718.     
  719.         print $output 
  720.             if $status == Z_OK or $status == Z_STREAM_END ;
  721.     
  722.         last if $status != Z_OK ;
  723.     }
  724.     
  725.     die "inflation failed\n"
  726.         unless $status == Z_STREAM_END ;
  727.  
  728. =head1 COMPRESS/UNCOMPRESS
  729.  
  730. Two high-level functions are provided by I<zlib> to perform in-memory
  731. compression. They are B<compress> and B<uncompress>. Two Perl subs are
  732. provided which provide similar functionality.
  733.  
  734. =over 5
  735.  
  736. =item B<$dest = compress($source) ;>
  737.  
  738. Compresses B<$source>. If successful it returns the
  739. compressed data. Otherwise it returns I<undef>.
  740.  
  741. The source buffer can either be a scalar or a scalar reference.
  742.  
  743. =item B<$dest = uncompress($source) ;>
  744.  
  745. Uncompresses B<$source>. If successful it returns the uncompressed
  746. data. Otherwise it returns I<undef>.
  747.  
  748. The source buffer can either be a scalar or a scalar reference.
  749.  
  750. =back
  751.  
  752. =head1 GZIP INTERFACE
  753.  
  754. A number of functions are supplied in I<zlib> for reading and writing
  755. I<gzip> files. This module provides an interface to most of them. In
  756. general the interface provided by this module operates identically to
  757. the functions provided by I<zlib>. Any differences are explained
  758. below.
  759.  
  760. =over 5
  761.  
  762. =item B<$gz = gzopen(filename or filehandle, mode)>
  763.  
  764. This function operates identically to the I<zlib> equivalent except
  765. that it returns an object which is used to access the other I<gzip>
  766. methods.
  767.  
  768. As with the I<zlib> equivalent, the B<mode> parameter is used to
  769. specify both whether the file is opened for reading or writing and to
  770. optionally specify a a compression level. Refer to the I<zlib>
  771. documentation for the exact format of the B<mode> parameter.
  772.  
  773. If a reference to an open filehandle is passed in place of the
  774. filename, gzdopen will be called behind the scenes. The third example
  775. at the end of this section, I<gzstream>, uses this feature.
  776.  
  777. =item B<$bytesread = $gz-E<gt>gzread($buffer [, $size]) ;>
  778.  
  779. Reads B<$size> bytes from the compressed file into B<$buffer>. If
  780. B<$size> is not specified, it will default to 4096. If the scalar
  781. B<$buffer> is not large enough, it will be extended automatically.
  782.  
  783. Returns the number of bytes actually read. On EOF it returns 0 and in
  784. the case of an error, -1.
  785.  
  786. =item B<$bytesread = $gz-E<gt>gzreadline($line) ;>
  787.  
  788. Reads the next line from the compressed file into B<$line>. 
  789.  
  790. Returns the number of bytes actually read. On EOF it returns 0 and in
  791. the case of an error, -1.
  792.  
  793. It is legal to intermix calls to B<gzread> and B<gzreadline>.
  794.  
  795. At this time B<gzreadline> ignores the variable C<$/>
  796. (C<$INPUT_RECORD_SEPARATOR> or C<$RS> when C<English> is in use). The
  797. end of a line is denoted by the C character C<'\n'>.
  798.  
  799. =item B<$byteswritten = $gz-E<gt>gzwrite($buffer) ;>
  800.  
  801. Writes the contents of B<$buffer> to the compressed file. Returns the
  802. number of bytes actually written, or 0 on error.
  803.  
  804. =item B<$status = $gz-E<gt>gzflush($flush) ;>
  805.  
  806. Flushes all pending output into the compressed file.
  807. Works identically to the I<zlib> function it interfaces to. Note that
  808. the use of B<gzflush> can degrade compression.
  809.  
  810. Refer to the I<zlib> documentation for the valid values of B<$flush>.
  811.  
  812. =item B<$gz-E<gt>gzclose>
  813.  
  814. Closes the compressed file. Any pending data is flushed to the file
  815. before it is closed.
  816.  
  817. =item B<$gz-E<gt>gzerror>
  818.  
  819. Returns the I<zlib> error message or number for the last operation
  820. associated with B<$gz>. The return value will be the I<zlib> error
  821. number when used in a numeric context and the I<zlib> error message
  822. when used in a string context. The I<zlib> error number constants,
  823. shown below, are available for use.
  824.  
  825.     Z_OK
  826.     Z_STREAM_END
  827.     Z_ERRNO
  828.     Z_STREAM_ERROR
  829.     Z_DATA_ERROR
  830.     Z_MEM_ERROR
  831.     Z_BUF_ERROR
  832.  
  833. =item B<$gzerrno>
  834.  
  835. The B<$gzerrno> scalar holds the error code associated with the most
  836. recent I<gzip> routine. Note that unlike B<gzerror()>, the error is
  837. I<not> associated with a particular file.
  838.  
  839. As with B<gzerror()> it returns an error number in numeric context and
  840. an error message in string context. Unlike B<gzerror()> though, the
  841. error message will correspond to the I<zlib> message when the error is
  842. associated with I<zlib> itself, or the UNIX error message when it is
  843. not (i.e. I<zlib> returned C<Z_ERRORNO>).
  844.  
  845. As there is an overlap between the error numbers used by I<zlib> and
  846. UNIX, B<$gzerrno> should only be used to check for the presence of
  847. I<an> error in numeric context. Use B<gzerror()> to check for specific
  848. I<zlib> errors. The I<gzcat> example below shows how the variable can
  849. be used safely.
  850.  
  851. =back
  852.  
  853.  
  854. =head2 Examples
  855.  
  856. Here is an example script which uses the interface. It implements a
  857. I<gzcat> function.
  858.  
  859.     use strict ;
  860.     use warnings ;
  861.     
  862.     use Compress::Zlib ;
  863.     
  864.     die "Usage: gzcat file...\n"
  865.         unless @ARGV ;
  866.     
  867.     my $file ;
  868.     
  869.     foreach $file (@ARGV) {
  870.         my $buffer ;
  871.     
  872.         my $gz = gzopen($file, "rb") 
  873.              or die "Cannot open $file: $gzerrno\n" ;
  874.     
  875.         print $buffer while $gz->gzread($buffer) > 0 ;
  876.     
  877.         die "Error reading from $file: $gzerrno" . ($gzerrno+0) . "\n" 
  878.             if $gzerrno != Z_STREAM_END ;
  879.         
  880.         $gz->gzclose() ;
  881.     }
  882.  
  883. Below is a script which makes use of B<gzreadline>. It implements a
  884. very simple I<grep> like script.
  885.  
  886.     use strict ;
  887.     use warnings ;
  888.     
  889.     use Compress::Zlib ;
  890.     
  891.     die "Usage: gzgrep pattern file...\n"
  892.         unless @ARGV >= 2;
  893.     
  894.     my $pattern = shift ;
  895.     
  896.     my $file ;
  897.     
  898.     foreach $file (@ARGV) {
  899.         my $gz = gzopen($file, "rb") 
  900.              or die "Cannot open $file: $gzerrno\n" ;
  901.     
  902.         while ($gz->gzreadline($_) > 0) {
  903.             print if /$pattern/ ;
  904.         }
  905.     
  906.         die "Error reading from $file: $gzerrno\n" 
  907.             if $gzerrno != Z_STREAM_END ;
  908.         
  909.         $gz->gzclose() ;
  910.     }
  911.  
  912. This script, I<gzstream>, does the opposite of the I<gzcat> script
  913. above. It reads from standard input and writes a gzip file to standard
  914. output.
  915.  
  916.     use strict ;
  917.     use warnings ;
  918.     
  919.     use Compress::Zlib ;
  920.     
  921.     binmode STDOUT;    # gzopen only sets it on the fd
  922.     
  923.     my $gz = gzopen(\*STDOUT, "wb")
  924.           or die "Cannot open stdout: $gzerrno\n" ;
  925.     
  926.     while (<>) {
  927.         $gz->gzwrite($_) 
  928.         or die "error writing: $gzerrno\n" ;
  929.     }
  930.  
  931.     $gz->gzclose ;
  932.  
  933. =head2 Compress::Zlib::memGzip
  934.  
  935. This function is used to create an in-memory gzip file. 
  936. It creates a minimal gzip header.
  937.  
  938.     $dest = Compress::Zlib::memGzip($buffer) ;
  939.  
  940. If successful, it returns the in-memory gzip file, otherwise it returns
  941. undef.
  942.  
  943. The buffer parameter can either be a scalar or a scalar reference.
  944.  
  945. =head2 Compress::Zlib::memGunzip
  946.  
  947. This function is used to uncompress an in-memory gzip file.
  948.  
  949.     $dest = Compress::Zlib::memGunzip($buffer) ;
  950.  
  951. If successful, it returns the uncompressed gzip file, otherwise it
  952. returns undef.
  953.  
  954. The buffer parameter can either be a scalar or a scalar reference. The contents
  955. of the buffer parameter are destroyed after calling this function.
  956.  
  957. =head1 CHECKSUM FUNCTIONS
  958.  
  959. Two functions are provided by I<zlib> to calculate a checksum. For the
  960. Perl interface, the order of the two parameters in both functions has
  961. been reversed. This allows both running checksums and one off
  962. calculations to be done.
  963.  
  964.     $crc = adler32($buffer [,$crc]) ;
  965.     $crc = crc32($buffer [,$crc]) ;
  966.  
  967. The buffer parameters can either be a scalar or a scalar reference.
  968.  
  969. If the $crc parameters is C<undef>, the crc value will be reset.
  970.  
  971. =head1 ACCESSING ZIP FILES
  972.  
  973. Although it is possible to use this module to access .zip files, there
  974. is a module on CPAN that will do all the hard work for you. Check out
  975.  
  976.     http://www.cpan.org/modules/by-module/Archive/Archive-Zip-*.tar.gz    
  977.  
  978. Assuming you don't want to use this module to access zip files there
  979. are a number of undocumented features in the zlib library you need to
  980. be aware of.
  981.  
  982. =over 5
  983.  
  984. =item 1.
  985.  
  986. When calling B<inflateInit> or B<deflateInit> the B<WindowBits> parameter
  987. must be set to C<-MAX_WBITS>. This disables the creation of the zlib
  988. header.
  989.  
  990. =item 2.
  991.  
  992. The zlib function B<inflate>, and so the B<inflate> method supplied in
  993. this module, assume that there is at least one trailing byte after the
  994. compressed data stream. Normally this isn't a problem because both
  995. the gzip and zip file formats will guarantee that there is data directly
  996. after the compressed data stream.
  997.  
  998. =back
  999.  
  1000. =head1 CONSTANTS
  1001.  
  1002. All the I<zlib> constants are automatically imported when you make use
  1003. of I<Compress::Zlib>.
  1004.  
  1005. =head1 AUTHOR
  1006.  
  1007. The I<Compress::Zlib> module was written by Paul Marquess,
  1008. F<Paul.Marquess@btinternet.com>. The latest copy of the module can be
  1009. found on CPAN in F<modules/by-module/Compress/Compress-Zlib-x.x.tar.gz>.
  1010.  
  1011. The primary site for the I<zlib> compression library is
  1012. F<http://www.gzip.org/zlib/>.
  1013.  
  1014. =head1 MODIFICATION HISTORY
  1015.  
  1016. See the README file.
  1017.