1 # Copyright (C) 2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
5 package PublicInbox::GzipFilter;
7 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
8 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
10 sub new { bless {}, shift }
12 # for Qspawn if using $env->{'pi-httpd.async'}
19 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
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";
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;
37 $self->{zbuf} = $zbuf;
39 } else { # undef == EOF
40 my $err = $gz->flush($zbuf, Z_FINISH);
41 die "gzip->flush: $err" if $err != Z_OK;
47 # my $ret = bytes::length($_[1]); # XXX does anybody care?
48 $_[0]->{fh}->write(translate($_[0], $_[1]));
53 my $fh = delete $self->{fh};
54 $fh->write(translate($self, undef));