]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GzipFilter.pm
gzipfilter: minor cleanups
[public-inbox.git] / lib / PublicInbox / GzipFilter.pm
1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # Qspawn filter
5 package PublicInbox::GzipFilter;
6 use strict;
7 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
8 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
9
10 sub new { bless {}, shift }
11
12 # for Qspawn if using $env->{'pi-httpd.async'}
13 sub attach {
14         my ($self, $fh) = @_;
15         $self->{fh} = $fh;
16         $self
17 }
18
19 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
20 sub translate ($$) {
21         my $self = $_[0];
22
23         # allocate the zlib context lazily here, instead of in ->new.
24         # Deflate contexts are memory-intensive and this object may
25         # be sitting in the Qspawn limiter queue for a while.
26         my $gz = $self->{gz} //= do {
27                 my ($g, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
28                 $err == Z_OK or die "Deflate->new failed: $err";
29                 $g;
30         };
31         my $zbuf = delete($self->{zbuf});
32         if (defined $_[1]) { # my $buf = $_[1];
33                 my $err = $gz->deflate($_[1], $zbuf);
34                 die "gzip->deflate: $err" if $err != Z_OK;
35                 return $zbuf if length($zbuf) >= 8192;
36
37                 $self->{zbuf} = $zbuf;
38                 '';
39         } else { # undef == EOF
40                 my $err = $gz->flush($zbuf, Z_FINISH);
41                 die "gzip->flush: $err" if $err != Z_OK;
42                 $zbuf;
43         }
44 }
45
46 sub write {
47         # my $ret = bytes::length($_[1]); # XXX does anybody care?
48         $_[0]->{fh}->write(translate($_[0], $_[1]));
49 }
50
51 sub close {
52         my ($self) = @_;
53         my $fh = delete $self->{fh};
54         $fh->write(translate($self, undef));
55         $fh->close;
56 }
57
58 1;