]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/GzipFilter.pm
d883130f39f7fb1cb938ffa6435175d679cc3fd4
[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 bytes (); # length
8 use Compress::Raw::Zlib qw(Z_FINISH Z_OK);
9 my %OPT = (-WindowBits => 15 + 16, -AppendOutput => 1);
10
11 sub new {
12         my ($gz, $err) = Compress::Raw::Zlib::Deflate->new(%OPT);
13         $err == Z_OK or die "Deflate->new failed: $err";
14         bless { gz => $gz }, shift;
15 }
16
17 # for Qspawn if using $env->{'pi-httpd.async'}
18 sub attach {
19         my ($self, $fh) = @_;
20         $self->{fh} = $fh;
21         $self
22 }
23
24 # for GetlineBody (via Qspawn) when NOT using $env->{'pi-httpd.async'}
25 sub translate ($$) {
26         my $self = $_[0];
27         my $zbuf = delete($self->{zbuf});
28         if (defined $_[1]) { # my $buf = $_[1];
29                 my $err = $self->{gz}->deflate($_[1], $zbuf);
30                 die "gzip->deflate: $err" if $err != Z_OK;
31                 return $zbuf if length($zbuf) >= 8192;
32
33                 $self->{zbuf} = $zbuf;
34                 '';
35         } else { # undef == EOF
36                 my $err = $self->{gz}->flush($zbuf, Z_FINISH);
37                 die "gzip->flush: $err" if $err != Z_OK;
38                 $zbuf;
39         }
40 }
41
42 sub write {
43         # my $ret = bytes::length($_[1]); # XXX does anybody care?
44         $_[0]->{fh}->write(translate($_[0], $_[1]));
45 }
46
47 sub close {
48         my ($self) = @_;
49         my $fh = delete $self->{fh};
50         $fh->write(translate($self, undef));
51         $fh->close;
52 }
53
54 1;