Debian Codegraph @

lib/Protocol/HTTP2/Huffman.pm

raw
1 package Protocol::HTTP2::Huffman;
2 use strict;
3 use warnings;
4 use Protocol::HTTP2::HuffmanCodes;
5 use Protocol::HTTP2::Trace qw(tracer);
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 my $s = shift;
15 my $ret = my $bin = '';
16 for my $i ( 0 .. length($s) - 1 ) {
17 $bin .= $hcodes{ ord( substr $s, $i, 1 ) };
18 }
19 $bin .= substr( $hcodes{256}, 0, 8 - length($bin) % 8 ) if length($bin) % 8;
20 return $ret . pack( 'B*', $bin );
21 }
22
23 sub huffman_decode {
24 my $s = shift;
25 my $bin = unpack( 'B*', $s );
26
27 my $c = 0;
28 $s = pack 'C*', map { $c += length; $rhcodes{$_} } ( $bin =~ /$hre/g );
29 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 ) if $hcodes{256} !~ /^@{[ substr($bin, $c) ]}/;
40 return $s;
41 }
42
43 1;