-
Notifications
You must be signed in to change notification settings - Fork 33
/
lz77_encoding.pl
95 lines (69 loc) · 1.98 KB
/
lz77_encoding.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/perl
# Author: Trizen
# Date: 02 May 2024
# https://github.com/trizen
# Simple implementation of LZ77 encoding.
use 5.036;
sub lz77_encode ($str) {
my $la = 0;
my $prefix = '';
my @chars = split(//, $str);
my $end = $#chars;
my (@literals, @distances, @lengths);
while ($la <= $end) {
my $n = 1;
my $p = length($prefix);
my $tmp;
my $token = $chars[$la];
while ( $n <= 255
and $la + $n <= $end
and ($tmp = rindex($prefix, $token, $p)) >= 0) {
$p = $tmp;
$token .= $chars[$la + $n];
++$n;
}
--$n;
push @distances, $la - $p;
push @lengths, $n;
push @literals, $chars[$la + $n];
$la += $n + 1;
$prefix .= $token;
}
return (\@literals, \@distances, \@lengths);
}
sub lz77_decode ($literals, $distances, $lengths) {
my $chunk = '';
my $offset = 0;
foreach my $i (0 .. $#$literals) {
$chunk .= substr($chunk, $offset - $distances->[$i], $lengths->[$i]) . $literals->[$i];
$offset += $lengths->[$i] + 1;
}
return $chunk;
}
my $string = "TOBEORNOTTOBEORTOBEORNOT";
my ($literals, $distances, $lengths) = lz77_encode($string);
my $decoded = lz77_decode($literals, $distances, $lengths);
$string eq $decoded or die "error: <<$string>> != <<$decoded>>";
foreach my $i (0 .. $#$literals) {
say "$literals->[$i] -- [$distances->[$i], $lengths->[$i]]";
}
foreach my $file (__FILE__, $^X) { # several tests
my $string = do {
open my $fh, '<:raw', $file or die "error for <<$file>>: $!";
local $/;
<$fh>;
};
my ($literals, $distances, $lengths) = lz77_encode($string);
my $decoded = lz77_decode($literals, $distances, $lengths);
$string eq $decoded or die "error: <<$string>> != <<$decoded>>";
}
__END__
T -- [0, 0]
O -- [0, 0]
B -- [0, 0]
E -- [0, 0]
R -- [3, 1]
N -- [0, 0]
T -- [3, 1]
T -- [9, 6]
T -- [15, 7]