-
Notifications
You must be signed in to change notification settings - Fork 4
/
derle.js
59 lines (58 loc) · 1.57 KB
/
derle.js
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
function derle(data, method, progress) {
let report = Date.now();
let word = method > 1;
let result = word ? new Uint16Array(data.length) : new Uint8Array(data.length);
let dread, cread;
switch (method) {
case 1:
dread = read8;
cread = read15;
break;
case 2:
dread = cread = read15;
break;
case 3:
dread = read15;
cread = readN;
break;
default:
throw "Ehm, please implement " + method;
}
let writepos = 0;
let readpos = 0;
while (readpos < data.length) {
if (Date.now() - report > 100) {
progress(readpos, data.length);
report = Date.now();
}
let d = dread(),
c = cread() + 1;
if (writepos + c >= result.length)
resize(result.length * 2);
result.fill(d, writepos, writepos + c);
writepos += c;
}
resize(writepos);
return result;
function read8() {
return data[readpos++];
}
function read15() {
let d = data[readpos++];
if (d > 127)
d = ((d - 128) << 8) + data[readpos++];
return d;
}
function readN() {
throw "Ehm, please implement readN";
}
function resize(len) {
if (result.length === len)
return;
let realloc = word ? new Uint16Array(len) : new Uint8Array(len);
len = Math.min(len, result.length);
for (let i = 0; i < len; i++)
realloc[i] = result[i];
result = realloc;
}
}