-
Notifications
You must be signed in to change notification settings - Fork 34
/
lzss_encoding.pl
129 lines (97 loc) · 2.62 KB
/
lzss_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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/perl
# Author: Trizen
# Date: 03 May 2024
# https://github.com/trizen
# Simple implementation of LZSS encoding.
use 5.036;
sub lzss_encode ($str) {
my $la = 0;
my $prefix = '';
my @chars = split(//, $str);
my $end = $#chars;
my $min_len = 3;
my $max_len = 255;
my (@literals, @distances, @lengths);
while ($la <= $end) {
my $n = 1;
my $p = length($prefix);
my $tmp;
my $token = $chars[$la];
while ( $n <= $max_len
and $la + $n <= $end
and ($tmp = rindex($prefix, $token, $p)) >= 0) {
$p = $tmp;
$token .= $chars[$la + $n];
++$n;
}
if ($n > $min_len) {
push @lengths, $n - 1;
push @distances, $la - $p;
push @literals, undef;
$la += $n - 1;
$prefix .= substr($token, 0, -1);
}
else {
my @bytes = split(//, substr($prefix, $p, $n - 1) . $chars[$la + $n - 1]);
push @lengths, (0) x scalar(@bytes);
push @distances, (0) x scalar(@bytes);
push @literals, @bytes;
$la += $n;
$prefix .= $token;
}
}
return (\@literals, \@distances, \@lengths);
}
sub lzss_decode ($literals, $distances, $lengths) {
my $chunk = '';
my $offset = 0;
foreach my $i (0 .. $#$literals) {
if ($lengths->[$i] != 0) {
$chunk .= substr($chunk, $offset - $distances->[$i], $lengths->[$i]);
$offset += $lengths->[$i];
}
else {
$chunk .= $literals->[$i];
$offset += 1;
}
}
return $chunk;
}
my $string = "TOBEORNOTTOBEORTOBEORNOT";
my ($literals, $distances, $lengths) = lzss_encode($string);
my $decoded = lzss_decode($literals, $distances, $lengths);
$string eq $decoded or die "error: <<$string>> != <<$decoded>>";
foreach my $i (0 .. $#$literals) {
if ($lengths->[$i] == 0) {
say $literals->[$i];
}
else {
say "[$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) = lzss_encode($string);
my $decoded = lzss_decode($literals, $distances, $lengths);
say "Ratio: ", scalar(@$literals) / scalar(grep { defined($_) } @$literals);
$string eq $decoded or die "error: <<$string>> != <<$decoded>>";
}
__END__
T
O
B
E
O
R
N
O
T
[9, 6]
[15, 8]
T
Ratio: 1.44887348353553
Ratio: 1.50565184626978