-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.js
56 lines (41 loc) · 1.34 KB
/
utils.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
"use strict";
const BufferStream = require("./BufferStream");
// Ref: http://grain.exout.net/lz4/lz4.js
module.exports.unlz4 = function(bufIn) {
let stream = new BufferStream(bufIn, false);
stream.pos = 4;
let decompressedSize = stream.readUInt32();
let dataSize = stream.readUInt32();
let endPos = dataSize + 16;
stream.pos = 16;
let output = Buffer.alloc(decompressedSize);
let outputPos = 0;
let readAdditionalSize = () => {
let size = stream.readUInt8();
if(size === 255) return size + readAdditionalSize();
else return size;
};
while(true) {
let token = stream.readUInt8();
let sqSize = token >> 4;
let matchSize = (token & 0x0f) + 4;
if(sqSize === 15) sqSize += readAdditionalSize();
stream.read(sqSize).copy(output, outputPos);
outputPos += sqSize;
if(endPos - 1 <= stream.pos) break;
let offset = stream.readUInt16();
if(matchSize === 19) matchSize += readAdditionalSize();
if(offset < matchSize) {
let matchPos = outputPos - offset;
while(true) {
output.copy(output, outputPos, matchPos, matchPos + offset);
outputPos += offset;
matchSize -= offset;
if(matchSize < offset) break;
}
}
output.copy(output, outputPos, outputPos - offset, outputPos - offset + matchSize);
outputPos += matchSize;
}
return output;
};