This repository has been archived by the owner on Oct 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlz4.js
8417 lines (7290 loc) · 273 KB
/
lz4.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
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* LZ4 based compression and decompression
* Copyright (c) 2014 Pierre Curto
* MIT Licensed
*/
var __exports__ = {};
require = (function e(t, n, r) {
function s(o, u) {
if (!n[o]) {
if (!t[o]) {
var a = typeof require == "function" && require;
if (!u && a) return a(o, !0);
if (i) return i(o, !0);
var f = new Error("Cannot find module '" + o + "'");
throw ((f.code = "MODULE_NOT_FOUND"), f);
}
var l = (n[o] = { exports: {} });
t[o][0].call(
l.exports,
function (e) {
var n = t[o][1][e];
return s(n ? n : e);
},
l,
l.exports,
e,
t,
n,
r,
);
}
return n[o].exports;
}
var i = typeof require == "function" && require;
for (var o = 0; o < r.length; o++) s(r[o]);
return s;
})(
{
"./utils": [
function (require, module, exports) {
/**
* Javascript emulated bindings
*/
var XXH = require("xxhashjs");
var CHECKSUM_SEED = 0;
// Header checksum is second byte of xxhash using 0 as a seed
exports.descriptorChecksum = function (d) {
return (XXH(d, CHECKSUM_SEED).toNumber() >> 8) & 0xff;
};
exports.blockChecksum = function (d) {
return XXH(d, CHECKSUM_SEED).toNumber();
};
exports.streamChecksum = function (d, c) {
if (d === null) return c.digest().toNumber();
if (c === null) c = XXH(CHECKSUM_SEED);
return c.update(d);
};
// Provide simple readInt32LE as the Buffer ones from node and browserify are incompatible
exports.readInt32LE = function (buffer, offset) {
return (
buffer[offset] |
(buffer[offset + 1] << 8) |
(buffer[offset + 2] << 16) |
(buffer[offset + 3] << 24)
);
};
exports.bindings = require("./binding");
},
{ "./binding": 1, xxhashjs: 10 },
],
1: [
function (require, module, exports) {
/**
Javascript version of the key LZ4 C functions
*/
var uint32 = require("cuint").UINT32;
if (!Math.imul)
Math.imul = function imul(a, b) {
var ah = a >>> 16;
var al = a & 0xffff;
var bh = b >>> 16;
var bl = b & 0xffff;
return (al * bl + ((ah * bl + al * bh) << 16)) | 0;
};
/**
* Decode a block. Assumptions: input contains all sequences of a
* chunk, output is large enough to receive the decoded data.
* If the output buffer is too small, an error will be thrown.
* If the returned value is negative, an error occured at the returned offset.
*
* @param input {Buffer} input data
* @param output {Buffer} output data
* @return {Number} number of decoded bytes
* @private
*/
exports.uncompress = function (input, output, sIdx, eIdx) {
sIdx = sIdx || 0;
eIdx = eIdx || input.length - sIdx;
// Process each sequence in the incoming data
for (var i = sIdx, n = eIdx, j = 0; i < n; ) {
var token = input[i++];
// Literals
var literals_length = token >> 4;
if (literals_length > 0) {
// length of literals
var l = literals_length + 240;
while (l === 255) {
l = input[i++];
literals_length += l;
}
// Copy the literals
var end = i + literals_length;
while (i < end) output[j++] = input[i++];
// End of buffer?
if (i === n) return j;
}
// Match copy
// 2 bytes offset (little endian)
var offset = input[i++] | (input[i++] << 8);
// 0 is an invalid offset value
if (offset === 0 || offset > j) return -(i - 2);
// length of match copy
var match_length = token & 0xf;
var l = match_length + 240;
while (l === 255) {
l = input[i++];
match_length += l;
}
// Copy the match
var pos = j - offset; // position of the match copy in the current output
var end = j + match_length + 4; // minmatch = 4
while (j < end) output[j++] = output[pos++];
}
return j;
};
var maxInputSize = 0x7e000000,
minMatch = 4,
// uint32() optimization
hashLog = 16,
hashShift = minMatch * 8 - hashLog,
hashSize = 1 << hashLog,
copyLength = 8,
lastLiterals = 5,
mfLimit = copyLength + minMatch,
skipStrength = 6,
mlBits = 4,
mlMask = (1 << mlBits) - 1,
runBits = 8 - mlBits,
runMask = (1 << runBits) - 1,
hasher = 2654435761;
// CompressBound returns the maximum length of a lz4 block, given it's uncompressed length
exports.compressBound = function (isize) {
return isize > maxInputSize ? 0 : (isize + isize / 255 + 16) | 0;
};
exports.compress = function (src, dst, sIdx, eIdx) {
// V8 optimization: non sparse array with integers
var hashTable = new Array(hashSize);
for (var i = 0; i < hashSize; i++) {
hashTable[i] = 0;
}
return compressBlock(
src,
dst,
0,
hashTable,
sIdx || 0,
eIdx || dst.length,
);
};
exports.compressHC = exports.compress;
exports.compressDependent = compressBlock;
function compressBlock(src, dst, pos, hashTable, sIdx, eIdx) {
var dpos = sIdx;
var dlen = eIdx - sIdx;
var anchor = 0;
if (src.length >= maxInputSize) throw new Error("input too large");
// Minimum of input bytes for compression (LZ4 specs)
if (src.length > mfLimit) {
var n = exports.compressBound(src.length);
if (dlen < n) throw Error("output too small: " + dlen + " < " + n);
var step = 1,
findMatchAttempts = (1 << skipStrength) + 3,
// Keep last few bytes incompressible (LZ4 specs):
// last 5 bytes must be literals
srcLength = src.length - mfLimit;
while (pos + minMatch < srcLength) {
// Find a match
// min match of 4 bytes aka sequence
var sequenceLowBits = (src[pos + 1] << 8) | src[pos];
var sequenceHighBits = (src[pos + 3] << 8) | src[pos + 2];
// compute hash for the current sequence
var hash =
Math.imul(
sequenceLowBits | (sequenceHighBits << 16),
hasher,
) >>> hashShift;
// get the position of the sequence matching the hash
// NB. since 2 different sequences may have the same hash
// it is double-checked below
// do -1 to distinguish between initialized and uninitialized values
var ref = hashTable[hash] - 1;
// save position of current sequence in hash table
hashTable[hash] = pos + 1;
// first reference or within 64k limit or current sequence !== hashed one: no match
if (
ref < 0 ||
(pos - ref) >>> 16 > 0 ||
((src[ref + 3] << 8) | src[ref + 2]) != sequenceHighBits ||
((src[ref + 1] << 8) | src[ref]) != sequenceLowBits
) {
// increase step if nothing found within limit
step = findMatchAttempts++ >> skipStrength;
pos += step;
continue;
}
findMatchAttempts = (1 << skipStrength) + 3;
// got a match
var literals_length = pos - anchor;
var offset = pos - ref;
// minMatch already verified
pos += minMatch;
ref += minMatch;
// move to the end of the match (>=minMatch)
var match_length = pos;
while (pos < srcLength && src[pos] == src[ref]) {
pos++;
ref++;
}
// match length
match_length = pos - match_length;
// token
var token = match_length < mlMask ? match_length : mlMask;
// encode literals length
if (literals_length >= runMask) {
// add match length to the token
dst[dpos++] = (runMask << mlBits) + token;
for (
var len = literals_length - runMask;
len > 254;
len -= 255
) {
dst[dpos++] = 255;
}
dst[dpos++] = len;
} else {
// add match length to the token
dst[dpos++] = (literals_length << mlBits) + token;
}
// write literals
for (var i = 0; i < literals_length; i++) {
dst[dpos++] = src[anchor + i];
}
// encode offset
dst[dpos++] = offset;
dst[dpos++] = offset >> 8;
// encode match length
if (match_length >= mlMask) {
match_length -= mlMask;
while (match_length >= 255) {
match_length -= 255;
dst[dpos++] = 255;
}
dst[dpos++] = match_length;
}
anchor = pos;
}
}
// cannot compress input
if (anchor == 0) return 0;
// Write last literals
// encode literals length
literals_length = src.length - anchor;
if (literals_length >= runMask) {
// add match length to the token
dst[dpos++] = runMask << mlBits;
for (var ln = literals_length - runMask; ln > 254; ln -= 255) {
dst[dpos++] = 255;
}
dst[dpos++] = ln;
} else {
// add match length to the token
dst[dpos++] = literals_length << mlBits;
}
// write literals
pos = anchor;
while (pos < src.length) {
dst[dpos++] = src[pos++];
}
return dpos;
}
},
{ cuint: 7 },
],
2: [
function (require, module, exports) {
(function (Buffer) {
var Decoder = require("./decoder_stream");
/**
Decode an LZ4 stream
*/
function LZ4_uncompress(input, options) {
var output = [];
var decoder = new Decoder(options);
decoder.on("data", function (chunk) {
output.push(chunk);
});
decoder.end(input);
return Buffer.concat(output);
}
exports.LZ4_uncompress = LZ4_uncompress;
}).call(this, require("buffer").Buffer);
},
{ "./decoder_stream": 3, buffer: "buffer" },
],
3: [
function (require, module, exports) {
(function (Buffer) {
var Transform = require("stream").Transform;
var inherits = require("util").inherits;
var lz4_static = require("./static");
var utils = lz4_static.utils;
var lz4_binding = utils.bindings;
var lz4_jsbinding = require("./binding");
var STATES = lz4_static.STATES;
var SIZES = lz4_static.SIZES;
function Decoder(options) {
if (!(this instanceof Decoder)) return new Decoder(options);
Transform.call(this, options);
// Options
this.options = options || {};
this.binding = this.options.useJS ? lz4_jsbinding : lz4_binding;
// Encoded data being processed
this.buffer = null;
// Current position within the data
this.pos = 0;
this.descriptor = null;
// Current state of the parsing
this.state = STATES.MAGIC;
this.notEnoughData = false;
this.descriptorStart = 0;
this.streamSize = null;
this.dictId = null;
this.currentStreamChecksum = null;
this.dataBlockSize = 0;
this.skippableSize = 0;
}
inherits(Decoder, Transform);
Decoder.prototype._transform = function (data, encoding, done) {
// Handle skippable data
if (this.skippableSize > 0) {
this.skippableSize -= data.length;
if (this.skippableSize > 0) {
// More to skip
done();
return;
}
data = data.slice(-this.skippableSize);
this.skippableSize = 0;
this.state = STATES.MAGIC;
}
// Buffer the incoming data
this.buffer = this.buffer
? Buffer.concat(
[this.buffer, data],
this.buffer.length + data.length,
)
: data;
this._main(done);
};
Decoder.prototype.emit_Error = function (msg) {
this.emit("error", new Error(msg + " @" + this.pos));
};
Decoder.prototype.check_Size = function (n) {
var delta = this.buffer.length - this.pos;
if (delta <= 0 || delta < n) {
if (this.notEnoughData)
this.emit_Error("Unexpected end of LZ4 stream");
return true;
}
this.pos += n;
return false;
};
Decoder.prototype.read_MagicNumber = function () {
var pos = this.pos;
if (this.check_Size(SIZES.MAGIC)) return true;
var magic = utils.readInt32LE(this.buffer, pos);
// Skippable chunk
if ((magic & 0xfffffff0) === lz4_static.MAGICNUMBER_SKIPPABLE) {
this.state = STATES.SKIP_SIZE;
return;
}
// LZ4 stream
if (magic !== lz4_static.MAGICNUMBER) {
this.pos = pos;
this.emit_Error(
"Invalid magic number: " + magic.toString(16).toUpperCase(),
);
return true;
}
this.state = STATES.DESCRIPTOR;
};
Decoder.prototype.read_SkippableSize = function () {
var pos = this.pos;
if (this.check_Size(SIZES.SKIP_SIZE)) return true;
this.state = STATES.SKIP_DATA;
this.skippableSize = utils.readInt32LE(this.buffer, pos);
};
Decoder.prototype.read_Descriptor = function () {
// Flags
var pos = this.pos;
if (this.check_Size(SIZES.DESCRIPTOR)) return true;
this.descriptorStart = pos;
// version
var descriptor_flg = this.buffer[pos];
var version = descriptor_flg >> 6;
if (version !== lz4_static.VERSION) {
this.pos = pos;
this.emit_Error(
"Invalid version: " + version + " != " + lz4_static.VERSION,
);
return true;
}
// flags
// reserved bit should not be set
if ((descriptor_flg >> 1) & 0x1) {
this.pos = pos;
this.emit_Error("Reserved bit set");
return true;
}
var blockMaxSizeIndex = (this.buffer[pos + 1] >> 4) & 0x7;
var blockMaxSize = lz4_static.blockMaxSizes[blockMaxSizeIndex];
if (blockMaxSize === null) {
this.pos = pos;
this.emit_Error("Invalid block max size: " + blockMaxSizeIndex);
return true;
}
this.descriptor = {
blockIndependence: Boolean((descriptor_flg >> 5) & 0x1),
blockChecksum: Boolean((descriptor_flg >> 4) & 0x1),
blockMaxSize: blockMaxSize,
streamSize: Boolean((descriptor_flg >> 3) & 0x1),
streamChecksum: Boolean((descriptor_flg >> 2) & 0x1),
dict: Boolean(descriptor_flg & 0x1),
dictId: 0,
};
this.state = STATES.SIZE;
};
Decoder.prototype.read_Size = function () {
if (this.descriptor.streamSize) {
var pos = this.pos;
if (this.check_Size(SIZES.SIZE)) return true;
//TODO max size is unsigned 64 bits
this.streamSize = this.buffer.slice(pos, pos + 8);
}
this.state = STATES.DICTID;
};
Decoder.prototype.read_DictId = function () {
if (this.descriptor.dictId) {
var pos = this.pos;
if (this.check_Size(SIZES.DICTID)) return true;
this.dictId = utils.readInt32LE(this.buffer, pos);
}
this.state = STATES.DESCRIPTOR_CHECKSUM;
};
Decoder.prototype.read_DescriptorChecksum = function () {
var pos = this.pos;
if (this.check_Size(SIZES.DESCRIPTOR_CHECKSUM)) return true;
var checksum = this.buffer[pos];
var currentChecksum = utils.descriptorChecksum(
this.buffer.slice(this.descriptorStart, pos),
);
if (currentChecksum !== checksum) {
this.pos = pos;
this.emit_Error("Invalid stream descriptor checksum");
return true;
}
this.state = STATES.DATABLOCK_SIZE;
};
Decoder.prototype.read_DataBlockSize = function () {
var pos = this.pos;
if (this.check_Size(SIZES.DATABLOCK_SIZE)) return true;
var datablock_size = utils.readInt32LE(this.buffer, pos);
// Uncompressed
if (datablock_size === lz4_static.EOS) {
this.state = STATES.EOS;
return;
}
// if (datablock_size > this.descriptor.blockMaxSize) {
// this.emit_Error( 'ASSERTION: invalid datablock_size: ' + datablock_size.toString(16).toUpperCase() + ' > ' + this.descriptor.blockMaxSize.toString(16).toUpperCase() )
// }
this.dataBlockSize = datablock_size;
this.state = STATES.DATABLOCK_DATA;
};
Decoder.prototype.read_DataBlockData = function () {
var pos = this.pos;
var datablock_size = this.dataBlockSize;
if (datablock_size & 0x80000000) {
// Uncompressed size
datablock_size = datablock_size & 0x7fffffff;
}
if (this.check_Size(datablock_size)) return true;
this.dataBlock = this.buffer.slice(pos, pos + datablock_size);
this.state = STATES.DATABLOCK_CHECKSUM;
};
Decoder.prototype.read_DataBlockChecksum = function () {
var pos = this.pos;
if (this.descriptor.blockChecksum) {
if (this.check_Size(SIZES.DATABLOCK_CHECKSUM)) return true;
var checksum = utils.readInt32LE(this.buffer, this.pos - 4);
var currentChecksum = utils.blockChecksum(this.dataBlock);
if (currentChecksum !== checksum) {
this.pos = pos;
this.emit_Error("Invalid block checksum");
return true;
}
}
this.state = STATES.DATABLOCK_UNCOMPRESS;
};
Decoder.prototype.uncompress_DataBlock = function () {
var uncompressed;
// uncompressed?
if (this.dataBlockSize & 0x80000000) {
uncompressed = this.dataBlock;
} else {
uncompressed = new Buffer(this.descriptor.blockMaxSize);
var decodedSize = this.binding.uncompress(
this.dataBlock,
uncompressed,
);
if (decodedSize < 0) {
this.emit_Error("Invalid data block: " + -decodedSize);
return true;
}
if (decodedSize < this.descriptor.blockMaxSize)
uncompressed = uncompressed.slice(0, decodedSize);
}
this.dataBlock = null;
this.push(uncompressed);
// Stream checksum
if (this.descriptor.streamChecksum) {
this.currentStreamChecksum = utils.streamChecksum(
uncompressed,
this.currentStreamChecksum,
);
}
this.state = STATES.DATABLOCK_SIZE;
};
Decoder.prototype.read_EOS = function () {
if (this.descriptor.streamChecksum) {
var pos = this.pos;
if (this.check_Size(SIZES.EOS)) return true;
var checksum = utils.readInt32LE(this.buffer, pos);
if (
checksum !==
utils.streamChecksum(null, this.currentStreamChecksum)
) {
this.pos = pos;
this.emit_Error(
"Invalid stream checksum: " +
checksum.toString(16).toUpperCase(),
);
return true;
}
}
this.state = STATES.MAGIC;
};
Decoder.prototype._flush = function (done) {
// Error on missing data as no more will be coming
this.notEnoughData = true;
this._main(done);
};
Decoder.prototype._main = function (done) {
var pos = this.pos;
var notEnoughData;
while (!notEnoughData && this.pos < this.buffer.length) {
if (this.state === STATES.MAGIC)
notEnoughData = this.read_MagicNumber();
if (this.state === STATES.SKIP_SIZE)
notEnoughData = this.read_SkippableSize();
if (this.state === STATES.DESCRIPTOR)
notEnoughData = this.read_Descriptor();
if (this.state === STATES.SIZE) notEnoughData = this.read_Size();
if (this.state === STATES.DICTID)
notEnoughData = this.read_DictId();
if (this.state === STATES.DESCRIPTOR_CHECKSUM)
notEnoughData = this.read_DescriptorChecksum();
if (this.state === STATES.DATABLOCK_SIZE)
notEnoughData = this.read_DataBlockSize();
if (this.state === STATES.DATABLOCK_DATA)
notEnoughData = this.read_DataBlockData();
if (this.state === STATES.DATABLOCK_CHECKSUM)
notEnoughData = this.read_DataBlockChecksum();
if (this.state === STATES.DATABLOCK_UNCOMPRESS)
notEnoughData = this.uncompress_DataBlock();
if (this.state === STATES.EOS) notEnoughData = this.read_EOS();
}
if (this.pos > pos) {
this.buffer = this.buffer.slice(this.pos);
this.pos = 0;
}
done();
};
module.exports = Decoder;
}).call(this, require("buffer").Buffer);
},
{ "./binding": 1, "./static": 6, buffer: "buffer", stream: 33, util: 36 },
],
4: [
function (require, module, exports) {
(function (Buffer) {
var Encoder = require("./encoder_stream");
/**
Encode an LZ4 stream
*/
function LZ4_compress(input, options) {
var output = [];
var encoder = new Encoder(options);
encoder.on("data", function (chunk) {
output.push(chunk);
});
encoder.end(input);
return Buffer.concat(output);
}
exports.LZ4_compress = LZ4_compress;
}).call(this, require("buffer").Buffer);
},
{ "./encoder_stream": 5, buffer: "buffer" },
],
5: [
function (require, module, exports) {
(function (Buffer) {
var Transform = require("stream").Transform;
var inherits = require("util").inherits;
var lz4_static = require("./static");
var utils = lz4_static.utils;
var lz4_binding = utils.bindings;
var lz4_jsbinding = require("./binding");
var STATES = lz4_static.STATES;
var SIZES = lz4_static.SIZES;
var defaultOptions = {
blockIndependence: true,
blockChecksum: false,
blockMaxSize: 4 << 20,
streamSize: false,
streamChecksum: true,
dict: false,
dictId: 0,
highCompression: false,
};
function Encoder(options) {
if (!(this instanceof Encoder)) return new Encoder(options);
Transform.call(this, options);
// Set the options
var o = options || defaultOptions;
if (o !== defaultOptions)
Object.keys(defaultOptions).forEach(function (p) {
if (!o.hasOwnProperty(p)) o[p] = defaultOptions[p];
});
this.options = o;
this.binding = this.options.useJS ? lz4_jsbinding : lz4_binding;
this.compress = o.highCompression
? this.binding.compressHC
: this.binding.compress;
// Build the stream descriptor from the options
// flags
var descriptor_flg = 0;
descriptor_flg = descriptor_flg | (lz4_static.VERSION << 6); // Version
descriptor_flg = descriptor_flg | ((o.blockIndependence & 1) << 5); // Block independence
descriptor_flg = descriptor_flg | ((o.blockChecksum & 1) << 4); // Block checksum
descriptor_flg = descriptor_flg | ((o.streamSize & 1) << 3); // Stream size
descriptor_flg = descriptor_flg | ((o.streamChecksum & 1) << 2); // Stream checksum
// Reserved bit
descriptor_flg = descriptor_flg | (o.dict & 1); // Preset dictionary
// block maximum size
var descriptor_bd = lz4_static.blockMaxSizes.indexOf(
o.blockMaxSize,
);
if (descriptor_bd < 0)
throw new Error("Invalid blockMaxSize: " + o.blockMaxSize);
this.descriptor = {
flg: descriptor_flg,
bd: (descriptor_bd & 0x7) << 4,
};
// Data being processed
this.buffer = [];
this.length = 0;
this.first = true;
this.checksum = null;
}
inherits(Encoder, Transform);
// Header = magic number + stream descriptor
Encoder.prototype.headerSize = function () {
var streamSizeSize = this.options.streamSize ? SIZES.DESCRIPTOR : 0;
var dictSize = this.options.dict ? SIZES.DICTID : 0;
return SIZES.MAGIC + 1 + 1 + streamSizeSize + dictSize + 1;
};
Encoder.prototype.header = function () {
var headerSize = this.headerSize();
var output = new Buffer(headerSize);
this.state = STATES.MAGIC;
output.writeInt32LE(lz4_static.MAGICNUMBER, 0, true);
this.state = STATES.DESCRIPTOR;
var descriptor = output.slice(SIZES.MAGIC, output.length - 1);
// Update the stream descriptor
descriptor.writeUInt8(this.descriptor.flg, 0, true);
descriptor.writeUInt8(this.descriptor.bd, 1, true);
var pos = 2;
this.state = STATES.SIZE;
if (this.options.streamSize) {
//TODO only 32bits size supported
descriptor.writeInt32LE(0, pos, true);
descriptor.writeInt32LE(this.size, pos + 4, true);
pos += SIZES.SIZE;
}
this.state = STATES.DICTID;
if (this.options.dict) {
descriptor.writeInt32LE(this.dictId, pos, true);
pos += SIZES.DICTID;
}
this.state = STATES.DESCRIPTOR_CHECKSUM;
output.writeUInt8(
utils.descriptorChecksum(descriptor),
SIZES.MAGIC + pos,
false,
);
return output;
};
Encoder.prototype.update_Checksum = function (data) {
// Calculate the stream checksum
this.state = STATES.CHECKSUM_UPDATE;
if (this.options.streamChecksum) {
this.checksum = utils.streamChecksum(data, this.checksum);
}
};
Encoder.prototype.compress_DataBlock = function (data) {
this.state = STATES.DATABLOCK_COMPRESS;
var dbChecksumSize = this.options.blockChecksum
? SIZES.DATABLOCK_CHECKSUM
: 0;
var maxBufSize = this.binding.compressBound(data.length);
var buf = new Buffer(
SIZES.DATABLOCK_SIZE + maxBufSize + dbChecksumSize,
);
var compressed = buf.slice(
SIZES.DATABLOCK_SIZE,
SIZES.DATABLOCK_SIZE + maxBufSize,
);
var compressedSize = this.compress(data, compressed);
// Set the block size
this.state = STATES.DATABLOCK_SIZE;
// Block size shall never be larger than blockMaxSize
// console.log("blockMaxSize", this.options.blockMaxSize, "compressedSize", compressedSize)
if (
compressedSize > 0 &&
compressedSize <= this.options.blockMaxSize
) {
// highest bit is 0 (compressed data)
buf.writeUInt32LE(compressedSize, 0, true);
buf = buf.slice(
0,
SIZES.DATABLOCK_SIZE + compressedSize + dbChecksumSize,
);
} else {
// Cannot compress the data, leave it as is
// highest bit is 1 (uncompressed data)
buf.writeInt32LE(0x80000000 | data.length, 0, true);
buf = buf.slice(
0,
SIZES.DATABLOCK_SIZE + data.length + dbChecksumSize,
);
data.copy(buf, SIZES.DATABLOCK_SIZE);
}
// Set the block checksum
this.state = STATES.DATABLOCK_CHECKSUM;
if (this.options.blockChecksum) {
// xxHash checksum on undecoded data with a seed of 0
var checksum = buf.slice(-dbChecksumSize);
checksum.writeInt32LE(utils.blockChecksum(compressed), 0, true);
}
// Update the stream checksum
this.update_Checksum(data);
this.size += data.length;
return buf;
};
Encoder.prototype._transform = function (data, encoding, done) {
if (data) {
// Buffer the incoming data
this.buffer.push(data);
this.length += data.length;
}
// Stream header
if (this.first) {
this.push(this.header());
this.first = false;
}
var blockMaxSize = this.options.blockMaxSize;
// Not enough data for a block
if (this.length < blockMaxSize) return done();
// Build the data to be compressed
var buf = Buffer.concat(this.buffer, this.length);
for (
var j = 0, i = buf.length;
i >= blockMaxSize;
i -= blockMaxSize, j += blockMaxSize
) {
// Compress the block
this.push(
this.compress_DataBlock(buf.slice(j, j + blockMaxSize)),
);
}
// Set the remaining data
if (i > 0) {
this.buffer = [buf.slice(j)];
this.length = this.buffer[0].length;
} else {
this.buffer = [];
this.length = 0;
}
done();
};
Encoder.prototype._flush = function (done) {
if (this.first) {
this.push(this.header());
this.first = false;
}
if (this.length > 0) {
var buf = Buffer.concat(this.buffer, this.length);
this.buffer = [];
this.length = 0;
var cc = this.compress_DataBlock(buf);
this.push(cc);
}
if (this.options.streamChecksum) {
this.state = STATES.CHECKSUM;
var eos = new Buffer(SIZES.EOS + SIZES.CHECKSUM);
eos.writeInt32LE(
utils.streamChecksum(null, this.checksum),
SIZES.EOS,
true,
);
} else {