File Coverage

blib/lib/Compress/Huffman.pm
Criterion Covered Total %
statement 134 181 74.0
branch 35 68 51.4
condition 4 12 33.3
subroutine 14 18 77.7
pod 9 10 90.0
total 196 289 67.8


line stmt bran cond sub pod time code
1             package Compress::Huffman;
2             require Exporter;
3             @ISA = qw(Exporter);
4             @EXPORT_OK = qw//;
5             %EXPORT_TAGS = (
6             all => \@EXPORT_OK,
7             );
8 2     2   107991 use warnings;
  2         5  
  2         75  
9 2     2   16 use strict;
  2         6  
  2         59  
10 2     2   14 use Carp;
  2         11  
  2         137  
11 2     2   16 use Scalar::Util 'looks_like_number';
  2         6  
  2         406  
12 2     2   749 use POSIX qw/ceil/;
  2         12261  
  2         12  
13 2     2   3989 use JSON::Create '0.22', 'create_json';
  2         1875  
  2         267  
14 2     2   632 use JSON::Parse '0.42', 'parse_json';
  2         1794  
  2         253  
15             our $VERSION = '0.06';
16              
17             # eps is the allowed floating point error for summing the values of
18             # the symbol table to ensure they form a probability distribution.
19              
20 2     2   16 use constant 'eps' => 0.0001;
  2         5  
  2         3450  
21              
22             # Private methods/functions
23              
24             # Add the prefix $i to everything underneath us.
25              
26             sub addcodetosubtable
27             {
28 21     21 0 44 my ($fakes, $h, $k, $size, $i) = @_;
29 21         28 my $subhuff = $fakes->{$k};
30 21         38 for my $j (0..$size - 1) {
31 47         64 my $subk = $subhuff->[$j];
32 47 100       79 if ($subk =~ /^fake/) {
33 11         40 addcodetosubtable ($fakes, $h, $subk, $size, $i);
34             }
35             else {
36 36         77 $h->{$subk} = $i . $h->{$subk};
37             }
38             }
39             }
40              
41             # Public methods below here
42              
43             sub new
44             {
45 3     3 1 627 return bless {};
46             }
47              
48             sub symbols
49             {
50             # Object and the table of symbols.
51 5     5 1 2368 my ($o, $s, %options) = @_;
52 5 50       13 if ($options{verbose}) {
53 5         14 $o->{verbose} = 1;
54             }
55             else {
56 0         0 $o->{verbose} = undef;
57             }
58             # Check $s is a hash reference.
59 5 50       15 if (ref $s ne 'HASH') {
60 0         0 croak "Use as \$o->symbols (\\\%symboltable, options...)";
61             }
62             # Copy the symbol table into our own thing. We need to put extra
63             # symbols in to it.
64 5         20 my %c = %$s;
65 5         14 $o->{c} = \%c;
66             # The number of symbols we encode with this Huffman code.
67 5         10 my $nentries = scalar keys %$s;
68 5 50       10 if (! $nentries) {
69 0         0 croak "Symbol table has no entries";
70             }
71             # Check we have numbers.
72 5         13 for my $k (keys %$s) {
73 27 50       65 if (! looks_like_number ($s->{$k})) {
74 0         0 croak "Non-numerical value '$s->{$k}' for key '$k'";
75             }
76             }
77 5 50       14 if ($o->{verbose}) {
78 5         60 print "Checked for numerical keys.\n";
79             }
80 5         13 my $size = $options{size};
81 5 100       13 if (! defined $size) {
82 3         5 $size = 2;
83             }
84 5 50 33     28 if ($size < 2 || int ($size) != $size) {
85 0         0 croak "Bad size $size for Huffman table, must be integer >= 2";
86             }
87 5 50 33     12 if ($size > 10 && ! $options{alphabet}) {
88 0         0 croak "Use \$o->symbols (\%t, alphabet => ['a', 'b',...]) for table sizes bigger than 10";
89             }
90 5 50       15 if ($o->{verbose}) {
91 5         23 print "Set size of Huffman code alphabet to $size.\n";
92             }
93             # If this is supposed to be a probability distribution, check
94 5         10 my $notprob = $options{notprob};
95 5 100       12 if ($notprob) {
96 2         4 my $total = 0.0;
97 2         5 for my $k (keys %$s) {
98 6         11 my $value = $s->{$k};
99 6 50       10 if ($value < 0.0) {
100 0         0 croak "Negative weight $value for symbol $k";
101             }
102 6         11 $total += $value;
103             }
104             }
105             else {
106 3         7 my $total = 0.0;
107 3         7 for my $k (keys %$s) {
108 21         23 my $value = $s->{$k};
109 21 50 33     50 if ($value < 0.0 || $value > 1.0) {
110 0         0 croak "Value $value for symbol $k is not a probability; use \$o->symbols (\\\%s, notprob => 1) if not a probability distribution";
111             }
112 21         31 $total += $s->{$k};
113             }
114 3 50       14 if (abs ($total - 1.0) > eps) {
115 0         0 croak "Input values don't sum to 1.0; use \$o->symbols (\\\%s, notprob => 1) if not a probability distribution";
116             }
117 3 50       5 if ($o->{verbose}) {
118 3         20 print "Is a valid probability distribution (total = $total).\n";
119             }
120             }
121             # The number of tables. We need $t - 1 pointers to tables, which
122             # each require one table entry, so $t is the smallest number which
123             # satisfies
124             #
125             # $t * $size >= $nentries + $t - 1
126              
127 5         38 my $t = ceil (($nentries -1) / ($size - 1));
128 5 50       17 if ($o->{verbose}) {
129 5         30 print "This symbol table requires $t Huffman tables of size $size.\n";
130             }
131 5         14 my $ndummies = 0;
132 5 100       11 if ($size > 2) {
133             # The number of dummy entries we need is
134 2         5 my $ndummies = $t * ($size - 1) - $nentries + 1;
135 2 50       6 if ($o->{verbose}) {
136 2         6 print "The Huffman tables need $ndummies dummy entries.\n";
137             }
138 2 50       5 if ($ndummies > 0) {
139             # Insert $ndummies dummy entries with probability zero into
140             # our copy of the symbol table.
141 0         0 for (0..$ndummies - 1) {
142 0         0 my $dummy = "dummy$_";
143 0 0       0 if ($c{$dummy}) {
144             # This is a bug not a user error.
145 0         0 die "The symbol table already has an entry '$dummy'";
146             }
147 0         0 $c{$dummy} = 0.0;
148             }
149             }
150             }
151             # The end-product, the Huffman encoding of the symbol table.
152 5         21 my %h;
153 5         6 my $nfake = 0;
154 5         7 my %fakes;
155 5         11 while ($nfake < $t) {
156 15 50       24 if ($o->{verbose}) {
157 15         43 print "Making key list for sub-table $nfake / $t.\n";
158             }
159 15         20 my $total = 0;
160 15         20 my @keys;
161              
162             # Find the $size keys with the minimum value and go through,
163             # picking them out.
164              
165 15         24 for my $i (0..$size - 1) {
166 37         52 my $min = 'inf';
167 37         41 my $minkey;
168 37         96 for my $k (sort keys %c) {
169 132 100       237 if ($c{$k} < $min) {
170 43         58 $min = $c{$k};
171 43         61 $minkey = $k;
172             }
173             }
174 37         53 $total += $min;
175 37 50       57 if ($o->{verbose}) {
176 37         158 print "Choosing $minkey with $min for symbol $i\n";
177             }
178 37         60 delete $c{$minkey};
179 37         52 push @keys, $minkey;
180 37         84 $h{$minkey} = $i;
181             }
182             # The total weight of this table.
183             # The next table
184 15         17 my @huff;
185 15         24 for my $i (0..$size - 1) {
186 37         47 my $k = $keys[$i];
187 37 50       55 if (! defined $k) {
188 0         0 last;
189             }
190 37         48 push @huff, $k;
191 37 100       83 if ($k =~ /^fake/) {
192 10         25 addcodetosubtable (\%fakes, \%h, $k, $size, $i);
193             }
194             }
195 15         21 my $fakekey = 'fake'.$nfake;
196 15         30 $c{$fakekey} = $total;
197 15         23 $fakes{$fakekey} = \@huff;
198 15         36 $nfake++;
199             }
200 5 50       14 if ($o->{verbose}) {
201 5         19 print "Deleting dummy keys.\n";
202             }
203 5         18 for my $k (keys %h) {
204 37 100       87 if ($k =~ /fake|dummy/) {
205 10         22 delete $h{$k};
206             }
207             }
208 5         14 $o->{h} = \%h;
209 5         9 $o->{s} = $s;
210             # Blank this out for the case that the user inserts a new symbol
211             # table, etc.
212 5         9 $o->{value_re} = undef;
213 5         22 $o->{r} = undef;
214             }
215              
216             sub xl
217             {
218 1     1 1 228 my ($o) = @_;
219 1         2 my $h = $o->{h};
220 1         2 my $s = $o->{s};
221 1 50 33     5 croak "Bad object" unless $h && $s;
222 1         2 my $len = 0.0;
223 1         2 my $total = 0.0;
224 1         2 for my $k (keys %$h) {
225 3         8 $len += length ($h->{$k}) * $s->{$k};
226 3         4 $total += $s->{$k};
227 3 50       9 if ($o->{verbose}) {
228 3         13 print "$k $h->{$k} $s->{$k} $len\n";
229             }
230             }
231 1         4 return $len / $total;
232             }
233              
234             sub table
235             {
236 0     0 1 0 my ($o) = @_;
237 0         0 return $o->{h};
238             }
239              
240             sub encode_array
241             {
242 0     0 1 0 my ($o, $msg) = @_;
243 0         0 my @output;
244 0         0 for my $k (@$msg) {
245 0         0 my $h = $o->{h}{$k};
246 0 0       0 if (! defined $h) {
247 0         0 carp "Symbol '$k' is not in the symbol table";
248 0         0 next;
249             }
250 0         0 push @output, $h;
251             }
252 0         0 return \@output;
253             }
254              
255             sub encode
256             {
257 0     0 1 0 my ($o, $msg) = @_;
258 0         0 my $output = $o->encode_array ($msg);
259 0         0 return join '', @$output;
260             }
261              
262             sub decode
263             {
264 0     0 1 0 my ($o, $msg) = @_;
265 0 0       0 if (! $o->{value_re}) {
266 0         0 my @values = sort {length ($b) <=> length ($a)} values %{$o->{h}};
  0         0  
  0         0  
267 0         0 my $value_re = '(' . join ('|', @values) . ')';
268 0         0 $o->{value_re} = $value_re;
269 0 0       0 if ($o->{verbose}) {
270 0         0 print "Value regex is ", $o->{value_re}, "\n";
271             }
272             }
273 0 0       0 if (! $o->{r}) {
274 0         0 $o->{r} = {reverse %{$o->{h}}};
  0         0  
275             }
276 0         0 my @output;
277 0         0 while ($msg =~ s/^$o->{value_re}//) {
278 0         0 push @output, $o->{r}{$1};
279             }
280 0 0       0 if (length ($msg) > 0) {
281 0         0 carp "Input starting from $msg was not Huffman encoded using this table";
282             }
283 0         0 return \@output;
284             }
285              
286             sub save
287             {
288 1     1 1 6 my ($o) = @_;
289 1         11 return create_json ($o);
290             }
291              
292             sub load
293             {
294 1     1 1 6 my ($o, $data) = @_;
295 1         10 my $input = parse_json ($data);
296 1         4 for my $k (keys %$input) {
297 6         11 $o->{$k} = $input->{$k};
298             }
299             }
300              
301              
302             1;