Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1020 lines
27 KiB

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