File Coverage

blib/lib/Protocol/HTTP2/Huffman.pm
Criterion Covered Total %
statement 28 28 100.0
branch 4 6 66.6
condition n/a
subroutine 6 6 100.0
pod 0 2 0.0
total 38 42 90.4


line stmt bran cond sub pod time code
1             package Protocol::HTTP2::Huffman;
2 12     12   35719 use strict;
  12         19  
  12         1358  
3 12     12   55 use warnings;
  12         22  
  12         2531  
4 12     12   6794 use Protocol::HTTP2::HuffmanCodes;
  12         32  
  12         1703  
5 12     12   3987 use Protocol::HTTP2::Trace qw(tracer);
  12         25  
  12         4756  
6             our ( %hcodes, %rhcodes, $hre );
7             require Exporter;
8             our @ISA = qw(Exporter);
9             our @EXPORT = qw(huffman_encode huffman_decode);
10              
11             # Memory unefficient algorithm (well suited for short strings)
12              
13             sub huffman_encode {
14 77     77 0 13564 my $s = shift;
15 77         13654 my $ret = my $bin = '';
16 77         13733 for my $i ( 0 .. length($s) - 1 ) {
17 1361         29814 $bin .= $hcodes{ ord( substr $s, $i, 1 ) };
18             }
19 77 100       13788 $bin .= substr( $hcodes{256}, 0, 8 - length($bin) % 8 ) if length($bin) % 8;
20 77         27187 return $ret . pack( 'B*', $bin );
21             }
22              
23             sub huffman_decode {
24 64     64 0 13035 my $s = shift;
25 64         12585 my $bin = unpack( 'B*', $s );
26              
27 64         12268 my $c = 0;
28 64         14136 $s = pack 'C*', map { $c += length; $rhcodes{$_} } ( $bin =~ /$hre/g );
  1307         265196  
  1307         531107  
29 64 50       12684 tracer->warning(
30             sprintf(
31             "malformed data in string at position %i, " . " length: %i",
32             $c, length($bin)
33             )
34             ) if length($bin) - $c > 8;
35             tracer->warning(
36             sprintf "no huffman code 256 at the end of encoded string '%s': %s\n",
37             substr( $s, 0, 30 ),
38             substr( $bin, $c )
39 64 50       12330 ) if $hcodes{256} !~ /^@{[ substr($bin, $c) ]}/;
  64         25622  
40 64         24828 return $s;
41             }
42              
43             1;