1
0
Fork 0
mirror of https://github.com/codedread/bitjs synced 2025-10-04 10:09:16 +02:00

Start the move to es6: Change all vars to lets/consts

This commit is contained in:
codedread 2017-02-20 12:47:17 -08:00
parent 87cdd92981
commit 639a23e69b
11 changed files with 514 additions and 555 deletions

View file

@ -16,16 +16,16 @@ bitjs.archive = bitjs.archive || {};
// =========================================================================== // ===========================================================================
// Stolen from Closure because it's the best way to do Java-like inheritance. // Stolen from Closure because it's the best way to do Java-like inheritance.
bitjs.base = function(me, opt_methodName, var_args) { bitjs.base = function(me, opt_methodName, var_args) {
var caller = arguments.callee.caller; const caller = arguments.callee.caller;
if (caller.superClass_) { if (caller.superClass_) {
// This is a constructor. Call the superclass constructor. // This is a constructor. Call the superclass constructor.
return caller.superClass_.constructor.apply( return caller.superClass_.constructor.apply(
me, Array.prototype.slice.call(arguments, 1)); me, Array.prototype.slice.call(arguments, 1));
} }
var args = Array.prototype.slice.call(arguments, 2); const args = Array.prototype.slice.call(arguments, 2);
var foundCaller = false; let foundCaller = false;
for (var ctor = me.constructor; for (let ctor = me.constructor;
ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) { ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
if (ctor.prototype[opt_methodName] === caller) { if (ctor.prototype[opt_methodName] === caller) {
foundCaller = true; foundCaller = true;
@ -210,7 +210,7 @@ bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) {
* @type {Map.<string, Array>} * @type {Map.<string, Array>}
*/ */
this.listeners_ = {}; this.listeners_ = {};
for (var type in bitjs.archive.UnarchiveEvent.Type) { for (let type in bitjs.archive.UnarchiveEvent.Type) {
this.listeners_[bitjs.archive.UnarchiveEvent.Type[type]] = []; this.listeners_[bitjs.archive.UnarchiveEvent.Type[type]] = [];
} }
}; };
@ -253,7 +253,7 @@ bitjs.archive.Unarchiver.prototype.addEventListener = function(type, listener) {
*/ */
bitjs.archive.Unarchiver.prototype.removeEventListener = function(type, listener) { bitjs.archive.Unarchiver.prototype.removeEventListener = function(type, listener) {
if (type in this.listeners_) { if (type in this.listeners_) {
var index = this.listeners_[type].indexOf(listener); const index = this.listeners_[type].indexOf(listener);
if (index != -1) { if (index != -1) {
this.listeners_[type].splice(index, 1); this.listeners_[type].splice(index, 1);
} }
@ -282,8 +282,8 @@ bitjs.archive.Unarchiver.prototype.handleWorkerEvent_ = function(e) {
* Starts the unarchive in a separate Web Worker thread and returns immediately. * Starts the unarchive in a separate Web Worker thread and returns immediately.
*/ */
bitjs.archive.Unarchiver.prototype.start = function() { bitjs.archive.Unarchiver.prototype.start = function() {
var me = this; const me = this;
var scriptFileName = this.pathToBitJS_ + this.getScriptFileName(); const scriptFileName = this.pathToBitJS_ + this.getScriptFileName();
if (scriptFileName) { if (scriptFileName) {
this.worker_ = new Worker(scriptFileName); this.worker_ = new Worker(scriptFileName);
@ -326,7 +326,7 @@ bitjs.archive.Unzipper = function(arrayBuffer, opt_pathToBitJS) {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); bitjs.base(this, arrayBuffer, opt_pathToBitJS);
}; };
bitjs.inherits(bitjs.archive.Unzipper, bitjs.archive.Unarchiver); bitjs.inherits(bitjs.archive.Unzipper, bitjs.archive.Unarchiver);
bitjs.archive.Unzipper.prototype.getScriptFileName = function() { return 'unzip.js' }; bitjs.archive.Unzipper.prototype.getScriptFileName = function() { return 'archive/unzip.js' };
/** /**
* Unrarrer * Unrarrer
@ -337,7 +337,7 @@ bitjs.archive.Unrarrer = function(arrayBuffer, opt_pathToBitJS) {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); bitjs.base(this, arrayBuffer, opt_pathToBitJS);
}; };
bitjs.inherits(bitjs.archive.Unrarrer, bitjs.archive.Unarchiver); bitjs.inherits(bitjs.archive.Unrarrer, bitjs.archive.Unarchiver);
bitjs.archive.Unrarrer.prototype.getScriptFileName = function() { return 'unrar.js' }; bitjs.archive.Unrarrer.prototype.getScriptFileName = function() { return 'archive/unrar.js' };
/** /**
* Untarrer * Untarrer
@ -348,7 +348,7 @@ bitjs.archive.Untarrer = function(arrayBuffer, opt_pathToBitJS) {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); bitjs.base(this, arrayBuffer, opt_pathToBitJS);
}; };
bitjs.inherits(bitjs.archive.Untarrer, bitjs.archive.Unarchiver); bitjs.inherits(bitjs.archive.Untarrer, bitjs.archive.Unarchiver);
bitjs.archive.Untarrer.prototype.getScriptFileName = function() { return 'untar.js' }; bitjs.archive.Untarrer.prototype.getScriptFileName = function() { return 'archive/untar.js' };
/** /**
* Factory method that creates an unarchiver based on the byte signature found * Factory method that creates an unarchiver based on the byte signature found
@ -358,9 +358,9 @@ bitjs.archive.Untarrer.prototype.getScriptFileName = function() { return 'untar.
* @return {bitjs.archive.Unarchiver} * @return {bitjs.archive.Unarchiver}
*/ */
bitjs.archive.GetUnarchiver = function(ab, opt_pathToBitJS) { bitjs.archive.GetUnarchiver = function(ab, opt_pathToBitJS) {
var unarchiver = null; let unarchiver = null;
var pathToBitJS = opt_pathToBitJS || ''; const pathToBitJS = opt_pathToBitJS || '';
var h = new Uint8Array(ab, 0, 10); const h = new Uint8Array(ab, 0, 10);
if (h[0] == 0x52 && h[1] == 0x61 && h[2] == 0x72 && h[3] == 0x21) { // Rar! if (h[0] == 0x52 && h[1] == 0x61 && h[2] == 0x72 && h[3] == 0x21) { // Rar!
unarchiver = new bitjs.archive.Unrarrer(ab, pathToBitJS); unarchiver = new bitjs.archive.Unrarrer(ab, pathToBitJS);

View file

@ -9,12 +9,12 @@
/** /**
* CRC Implementation. * CRC Implementation.
*/ */
var CRCTab = new Array(256).fill(0); const CRCTab = new Array(256).fill(0);
function InitCRC() { function InitCRC() {
for (var i = 0; i < 256; ++i) { for (let i = 0; i < 256; ++i) {
var c = i; let c = i;
for (var j = 0; j < 8; ++j) { for (let j = 0; j < 8; ++j) {
// Read http://stackoverflow.com/questions/6798111/bitwise-operations-on-32-bit-unsigned-ints // Read http://stackoverflow.com/questions/6798111/bitwise-operations-on-32-bit-unsigned-ints
// for the bitwise operator issue (JS interprets operands as 32-bit signed // for the bitwise operator issue (JS interprets operands as 32-bit signed
// integers and we need to deal with unsigned ones here). // integers and we need to deal with unsigned ones here).
@ -60,8 +60,8 @@ function CRC(startCRC, arr) {
#endif #endif
*/ */
for (var i = 0; i < arr.length; ++i) { for (let i = 0; i < arr.length; ++i) {
var byte = ((startCRC ^ arr[i]) >>> 0) & 0xff; const byte = ((startCRC ^ arr[i]) >>> 0) & 0xff;
startCRC = (CRCTab[byte] ^ (startCRC >>> 8)) >>> 0; startCRC = (CRCTab[byte] ^ (startCRC >>> 8)) >>> 0;
} }
@ -74,17 +74,17 @@ function CRC(startCRC, arr) {
/** /**
* RarVM Implementation. * RarVM Implementation.
*/ */
var VM_MEMSIZE = 0x40000; const VM_MEMSIZE = 0x40000;
var VM_MEMMASK = (VM_MEMSIZE - 1); const VM_MEMMASK = (VM_MEMSIZE - 1);
var VM_GLOBALMEMADDR = 0x3C000; const VM_GLOBALMEMADDR = 0x3C000;
var VM_GLOBALMEMSIZE = 0x2000; const VM_GLOBALMEMSIZE = 0x2000;
var VM_FIXEDGLOBALSIZE = 64; const VM_FIXEDGLOBALSIZE = 64;
var MAXWINSIZE = 0x400000; const MAXWINSIZE = 0x400000;
var MAXWINMASK = (MAXWINSIZE - 1); const MAXWINMASK = (MAXWINSIZE - 1);
/** /**
*/ */
var VM_Commands = { const VM_Commands = {
VM_MOV: 0, VM_MOV: 0,
VM_CMP: 1, VM_CMP: 1,
VM_ADD: 2, VM_ADD: 2,
@ -141,7 +141,7 @@ var VM_Commands = {
/** /**
*/ */
var VM_StandardFilters = { const VM_StandardFilters = {
VMSF_NONE: 0, VMSF_NONE: 0,
VMSF_E8: 1, VMSF_E8: 1,
VMSF_E8E9: 2, VMSF_E8E9: 2,
@ -154,7 +154,7 @@ var VM_StandardFilters = {
/** /**
*/ */
var VM_Flags = { const VM_Flags = {
VM_FC: 1, VM_FC: 1,
VM_FZ: 2, VM_FZ: 2,
VM_FS: 0x80000000, VM_FS: 0x80000000,
@ -162,7 +162,7 @@ var VM_Flags = {
/** /**
*/ */
var VM_OpType = { const VM_OpType = {
VM_OPREG: 0, VM_OPREG: 0,
VM_OPINT: 1, VM_OPINT: 1,
VM_OPREGMEM: 2, VM_OPREGMEM: 2,
@ -177,7 +177,7 @@ var VM_OpType = {
* @return {string} The key/enum value as a string. * @return {string} The key/enum value as a string.
*/ */
function findKeyForValue(obj, val) { function findKeyForValue(obj, val) {
for (var key in obj) { for (let key in obj) {
if (obj[key] === val) { if (obj[key] === val) {
return key; return key;
} }
@ -186,7 +186,7 @@ function findKeyForValue(obj, val) {
} }
function getDebugString(obj, val) { function getDebugString(obj, val) {
var s = 'Unknown.'; let s = 'Unknown.';
if (obj === VM_Commands) { if (obj === VM_Commands) {
s = 'VM_Commands.'; s = 'VM_Commands.';
} else if (obj === VM_StandardFilters) { } else if (obj === VM_StandardFilters) {
@ -204,7 +204,7 @@ function getDebugString(obj, val) {
* @struct * @struct
* @constructor * @constructor
*/ */
var VM_PreparedOperand = function() { const VM_PreparedOperand = function() {
/** @type {VM_OpType} */ /** @type {VM_OpType} */
this.Type; this.Type;
@ -235,7 +235,7 @@ VM_PreparedOperand.prototype.toString = function() {
* @struct * @struct
* @constructor * @constructor
*/ */
var VM_PreparedCommand = function() { const VM_PreparedCommand = function() {
/** @type {VM_Commands} */ /** @type {VM_Commands} */
this.OpCode; this.OpCode;
@ -267,7 +267,7 @@ VM_PreparedCommand.prototype.toString = function(indent) {
* @struct * @struct
* @constructor * @constructor
*/ */
var VM_PreparedProgram = function() { const VM_PreparedProgram = function() {
/** @type {Array<VM_PreparedCommand>} */ /** @type {Array<VM_PreparedCommand>} */
this.Cmd = []; this.Cmd = [];
@ -292,8 +292,8 @@ var VM_PreparedProgram = function() {
/** @return {string} */ /** @return {string} */
VM_PreparedProgram.prototype.toString = function() { VM_PreparedProgram.prototype.toString = function() {
var s = '{\n Cmd: [\n'; let s = '{\n Cmd: [\n';
for (var i = 0; i < this.Cmd.length; ++i) { for (let i = 0; i < this.Cmd.length; ++i) {
s += this.Cmd[i].toString(' ') + ',\n'; s += this.Cmd[i].toString(' ') + ',\n';
} }
s += '],\n'; s += '],\n';
@ -306,7 +306,7 @@ VM_PreparedProgram.prototype.toString = function() {
* @struct * @struct
* @constructor * @constructor
*/ */
var UnpackFilter = function() { const UnpackFilter = function() {
/** @type {number} */ /** @type {number} */
this.BlockStart = 0; this.BlockStart = 0;
@ -328,17 +328,17 @@ var UnpackFilter = function() {
this.Prg = new VM_PreparedProgram(); this.Prg = new VM_PreparedProgram();
}; };
var VMCF_OP0 = 0; const VMCF_OP0 = 0;
var VMCF_OP1 = 1; const VMCF_OP1 = 1;
var VMCF_OP2 = 2; const VMCF_OP2 = 2;
var VMCF_OPMASK = 3; const VMCF_OPMASK = 3;
var VMCF_BYTEMODE = 4; const VMCF_BYTEMODE = 4;
var VMCF_JUMP = 8; const VMCF_JUMP = 8;
var VMCF_PROC = 16; const VMCF_PROC = 16;
var VMCF_USEFLAGS = 32; const VMCF_USEFLAGS = 32;
var VMCF_CHFLAGS = 64; const VMCF_CHFLAGS = 64;
var VM_CmdFlags = [ const VM_CmdFlags = [
/* VM_MOV */ VMCF_OP2 | VMCF_BYTEMODE , /* VM_MOV */ VMCF_OP2 | VMCF_BYTEMODE ,
/* VM_CMP */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_CMP */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
/* VM_ADD */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_ADD */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS ,
@ -389,7 +389,7 @@ var VM_CmdFlags = [
* @struct * @struct
* @constructor * @constructor
*/ */
var StandardFilterSignature = function(length, crc, type) { const StandardFilterSignature = function(length, crc, type) {
/** @type {number} */ /** @type {number} */
this.Length = length; this.Length = length;
@ -403,7 +403,7 @@ var StandardFilterSignature = function(length, crc, type) {
/** /**
* @type {Array<StandardFilterSignature>} * @type {Array<StandardFilterSignature>}
*/ */
var StdList = [ const StdList = [
new StandardFilterSignature(53, 0xad576887, VM_StandardFilters.VMSF_E8), new StandardFilterSignature(53, 0xad576887, VM_StandardFilters.VMSF_E8),
new StandardFilterSignature(57, 0x3cd7e57e, VM_StandardFilters.VMSF_E8E9), new StandardFilterSignature(57, 0x3cd7e57e, VM_StandardFilters.VMSF_E8E9),
new StandardFilterSignature(120, 0x3769893f, VM_StandardFilters.VMSF_ITANIUM), new StandardFilterSignature(120, 0x3769893f, VM_StandardFilters.VMSF_ITANIUM),
@ -416,7 +416,7 @@ var StdList = [
/** /**
* @constructor * @constructor
*/ */
var RarVM = function() { const RarVM = function() {
/** @private {Uint8Array} */ /** @private {Uint8Array} */
this.mem_ = null; this.mem_ = null;
@ -441,8 +441,8 @@ RarVM.prototype.init = function() {
* @return {VM_StandardFilters} * @return {VM_StandardFilters}
*/ */
RarVM.prototype.isStandardFilter = function(code) { RarVM.prototype.isStandardFilter = function(code) {
var codeCRC = (CRC(0xffffffff, code, code.length) ^ 0xffffffff) >>> 0; const codeCRC = (CRC(0xffffffff, code, code.length) ^ 0xffffffff) >>> 0;
for (var i = 0; i < StdList.length; ++i) { for (let i = 0; i < StdList.length; ++i) {
if (StdList[i].CRC == codeCRC && StdList[i].Length == code.length) if (StdList[i].CRC == codeCRC && StdList[i].Length == code.length)
return StdList[i].Type; return StdList[i].Type;
} }
@ -456,7 +456,7 @@ RarVM.prototype.isStandardFilter = function(code) {
* @param {bitjs.io.BitStream} bstream A rtl bit stream. * @param {bitjs.io.BitStream} bstream A rtl bit stream.
*/ */
RarVM.prototype.decodeArg = function(op, byteMode, bstream) { RarVM.prototype.decodeArg = function(op, byteMode, bstream) {
var data = bstream.peekBits(16); const data = bstream.peekBits(16);
if (data & 0x8000) { if (data & 0x8000) {
op.Type = VM_OpType.VM_OPREG; // Operand is register (R[0]..R[7]) op.Type = VM_OpType.VM_OPREG; // Operand is register (R[0]..R[7])
bstream.readBits(1); // 1 flag bit and... bstream.readBits(1); // 1 flag bit and...
@ -502,12 +502,12 @@ RarVM.prototype.decodeArg = function(op, byteMode, bstream) {
RarVM.prototype.execute = function(prg) { RarVM.prototype.execute = function(prg) {
this.R_.set(prg.InitR); this.R_.set(prg.InitR);
var globalSize = Math.min(prg.GlobalData.length, VM_GLOBALMEMSIZE); const globalSize = Math.min(prg.GlobalData.length, VM_GLOBALMEMSIZE);
if (globalSize) { if (globalSize) {
this.mem_.set(prg.GlobalData.subarray(0, globalSize), VM_GLOBALMEMADDR); this.mem_.set(prg.GlobalData.subarray(0, globalSize), VM_GLOBALMEMADDR);
} }
var staticSize = Math.min(prg.StaticData.length, VM_GLOBALMEMSIZE - globalSize); const staticSize = Math.min(prg.StaticData.length, VM_GLOBALMEMSIZE - globalSize);
if (staticSize) { if (staticSize) {
this.mem_.set(prg.StaticData.subarray(0, staticSize), VM_GLOBALMEMADDR + globalSize); this.mem_.set(prg.StaticData.subarray(0, staticSize), VM_GLOBALMEMADDR + globalSize);
} }
@ -515,15 +515,15 @@ RarVM.prototype.execute = function(prg) {
this.R_[7] = VM_MEMSIZE; this.R_[7] = VM_MEMSIZE;
this.flags_ = 0; this.flags_ = 0;
var preparedCodes = prg.AltCmd ? prg.AltCmd : prg.Cmd; const preparedCodes = prg.AltCmd ? prg.AltCmd : prg.Cmd;
if (prg.Cmd.length > 0 && !this.executeCode(preparedCodes)) { if (prg.Cmd.length > 0 && !this.executeCode(preparedCodes)) {
// Invalid VM program. Let's replace it with 'return' command. // Invalid VM program. Let's replace it with 'return' command.
preparedCode.OpCode = VM_Commands.VM_RET; preparedCode.OpCode = VM_Commands.VM_RET;
} }
var dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR); const dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR);
var newBlockPos = dataView.getUint32(0x20, true /* little endian */) & VM_MEMMASK; let newBlockPos = dataView.getUint32(0x20, true /* little endian */) & VM_MEMMASK;
var newBlockSize = dataView.getUint32(0x1c, true /* little endian */) & VM_MEMMASK; const newBlockSize = dataView.getUint32(0x1c, true /* little endian */) & VM_MEMMASK;
if (newBlockPos + newBlockSize >= VM_MEMSIZE) { if (newBlockPos + newBlockSize >= VM_MEMSIZE) {
newBlockPos = newBlockSize = 0; newBlockPos = newBlockSize = 0;
} }
@ -531,10 +531,9 @@ RarVM.prototype.execute = function(prg) {
prg.GlobalData = new Uint8Array(0); prg.GlobalData = new Uint8Array(0);
var dataSize = Math.min(dataView.getUint32(0x30), const dataSize = Math.min(dataView.getUint32(0x30), (VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE));
(VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE));
if (dataSize != 0) { if (dataSize != 0) {
var len = dataSize + VM_FIXEDGLOBALSIZE; const len = dataSize + VM_FIXEDGLOBALSIZE;
prg.GlobalData = new Uint8Array(len); prg.GlobalData = new Uint8Array(len);
prg.GlobalData.set(mem.subarray(VM_GLOBALMEMADDR, VM_GLOBALMEMADDR + len)); prg.GlobalData.set(mem.subarray(VM_GLOBALMEMADDR, VM_GLOBALMEMADDR + len));
} }
@ -545,8 +544,8 @@ RarVM.prototype.execute = function(prg) {
* @return {boolean} * @return {boolean}
*/ */
RarVM.prototype.executeCode = function(preparedCodes) { RarVM.prototype.executeCode = function(preparedCodes) {
var codeIndex = 0; let codeIndex = 0;
var cmd = preparedCodes[codeIndex]; let cmd = preparedCodes[codeIndex];
// TODO: Why is this an infinite loop instead of just returning // TODO: Why is this an infinite loop instead of just returning
// when a VM_RET is hit? // when a VM_RET is hit?
while (1) { while (1) {
@ -578,13 +577,13 @@ RarVM.prototype.executeCode = function(preparedCodes) {
RarVM.prototype.executeStandardFilter = function(filterType) { RarVM.prototype.executeStandardFilter = function(filterType) {
switch (filterType) { switch (filterType) {
case VM_StandardFilters.VMSF_DELTA: case VM_StandardFilters.VMSF_DELTA:
var dataSize = this.R_[4]; const dataSize = this.R_[4];
var channels = this.R_[0]; const channels = this.R_[0];
var srcPos = 0; let srcPos = 0;
var border = dataSize * 2; const border = dataSize * 2;
//SET_VALUE(false,&Mem[VM_GLOBALMEMADDR+0x20],DataSize); //SET_VALUE(false,&Mem[VM_GLOBALMEMADDR+0x20],DataSize);
var dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR); const dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR);
dataView.setUint32(0x20, dataSize, true /* little endian */); dataView.setUint32(0x20, dataSize, true /* little endian */);
if (dataSize >= VM_GLOBALMEMADDR / 2) { if (dataSize >= VM_GLOBALMEMADDR / 2) {
@ -593,9 +592,9 @@ RarVM.prototype.executeStandardFilter = function(filterType) {
// Bytes from same channels are grouped to continual data blocks, // Bytes from same channels are grouped to continual data blocks,
// so we need to place them back to their interleaving positions. // so we need to place them back to their interleaving positions.
for (var curChannel = 0; curChannel < channels; ++curChannel) { for (let curChannel = 0; curChannel < channels; ++curChannel) {
var prevByte = 0; let prevByte = 0;
for (var destPos = dataSize + curChannel; destPos < border; destPos += channels) { for (let destPos = dataSize + curChannel; destPos < border; destPos += channels) {
prevByte = (prevByte - this.mem_[srcPos++]) & 0xff; prevByte = (prevByte - this.mem_[srcPos++]) & 0xff;
this.mem_[destPos] = prevByte; this.mem_[destPos] = prevByte;
} }
@ -614,15 +613,15 @@ RarVM.prototype.executeStandardFilter = function(filterType) {
* @param {VM_PreparedProgram} prg * @param {VM_PreparedProgram} prg
*/ */
RarVM.prototype.prepare = function(code, prg) { RarVM.prototype.prepare = function(code, prg) {
var codeSize = code.length; let codeSize = code.length;
//InitBitInput(); //InitBitInput();
//memcpy(InBuf,Code,Min(CodeSize,BitInput::MAX_SIZE)); //memcpy(InBuf,Code,Min(CodeSize,BitInput::MAX_SIZE));
var bstream = new bitjs.io.BitStream(code.buffer, true /* rtl */); const bstream = new bitjs.io.BitStream(code.buffer, true /* rtl */);
// Calculate the single byte XOR checksum to check validity of VM code. // Calculate the single byte XOR checksum to check validity of VM code.
var xorSum=0; let xorSum = 0;
for (var i = 1; i < codeSize; ++i) { for (let i = 1; i < codeSize; ++i) {
xorSum ^= code[i]; xorSum ^= code[i];
} }
@ -632,10 +631,10 @@ RarVM.prototype.prepare = function(code, prg) {
// VM code is valid if equal. // VM code is valid if equal.
if (xorSum == code[0]) { if (xorSum == code[0]) {
var filterType = this.isStandardFilter(code); const filterType = this.isStandardFilter(code);
if (filterType != VM_StandardFilters.VMSF_NONE) { if (filterType != VM_StandardFilters.VMSF_NONE) {
// VM code is found among standard filters. // VM code is found among standard filters.
var curCmd = new VM_PreparedCommand(); const curCmd = new VM_PreparedCommand();
prg.Cmd.push(curCmd); prg.Cmd.push(curCmd);
curCmd.OpCode = VM_Commands.VM_STANDARD; curCmd.OpCode = VM_Commands.VM_STANDARD;
@ -648,17 +647,17 @@ RarVM.prototype.prepare = function(code, prg) {
codeSize = 0; codeSize = 0;
} }
var dataFlag = bstream.readBits(1); const dataFlag = bstream.readBits(1);
// Read static data contained in DB operators. This data cannot be // Read static data contained in DB operators. This data cannot be
// changed, it is a part of VM code, not a filter parameter. // changed, it is a part of VM code, not a filter parameter.
if (dataFlag & 0x8000) { if (dataFlag & 0x8000) {
var dataSize = RarVM.readData(bstream) + 1; const dataSize = RarVM.readData(bstream) + 1;
// TODO: This accesses the byte pointer of the bstream directly. Is that ok? // TODO: This accesses the byte pointer of the bstream directly. Is that ok?
for (var i = 0; i < bstream.bytePtr < codeSize && i < dataSize; ++i) { for (let i = 0; i < bstream.bytePtr < codeSize && i < dataSize; ++i) {
// Append a byte to the program's static data. // Append a byte to the program's static data.
var newStaticData = new Uint8Array(prg.StaticData.length + 1); const newStaticData = new Uint8Array(prg.StaticData.length + 1);
newStaticData.set(prg.StaticData); newStaticData.set(prg.StaticData);
newStaticData[newStaticData.length - 1] = bstream.readBits(8); newStaticData[newStaticData.length - 1] = bstream.readBits(8);
prg.StaticData = newStaticData; prg.StaticData = newStaticData;
@ -666,9 +665,9 @@ RarVM.prototype.prepare = function(code, prg) {
} }
while (bstream.bytePtr < codeSize) { while (bstream.bytePtr < codeSize) {
var curCmd = new VM_PreparedCommand(); const curCmd = new VM_PreparedCommand();
prg.Cmd.push(curCmd); // Prg->Cmd.Add(1) prg.Cmd.push(curCmd); // Prg->Cmd.Add(1)
var flag = bstream.peekBits(1); const flag = bstream.peekBits(1);
if (!flag) { // (Data&0x8000)==0 if (!flag) { // (Data&0x8000)==0
curCmd.OpCode = bstream.readBits(4); curCmd.OpCode = bstream.readBits(4);
} else { } else {
@ -682,7 +681,7 @@ RarVM.prototype.prepare = function(code, prg) {
} }
curCmd.Op1.Type = VM_OpType.VM_OPNONE; curCmd.Op1.Type = VM_OpType.VM_OPNONE;
curCmd.Op2.Type = VM_OpType.VM_OPNONE; curCmd.Op2.Type = VM_OpType.VM_OPNONE;
var opNum = (VM_CmdFlags[curCmd.OpCode] & VMCF_OPMASK); const opNum = (VM_CmdFlags[curCmd.OpCode] & VMCF_OPMASK);
curCmd.Op1.Addr = null; curCmd.Op1.Addr = null;
curCmd.Op2.Addr = null; curCmd.Op2.Addr = null;
if (opNum > 0) { if (opNum > 0) {
@ -692,7 +691,7 @@ RarVM.prototype.prepare = function(code, prg) {
} else { } else {
if (curCmd.Op1.Type == VM_OpType.VM_OPINT && (VM_CmdFlags[curCmd.OpCode] & (VMCF_JUMP|VMCF_PROC))) { if (curCmd.Op1.Type == VM_OpType.VM_OPINT && (VM_CmdFlags[curCmd.OpCode] & (VMCF_JUMP|VMCF_PROC))) {
// Calculating jump distance. // Calculating jump distance.
var distance = curCmd.Op1.Data; let distance = curCmd.Op1.Data;
if (distance >= 256) { if (distance >= 256) {
distance -= 256; distance -= 256;
} else { } else {
@ -716,7 +715,7 @@ RarVM.prototype.prepare = function(code, prg) {
} // while ((uint)InAddr<CodeSize) } // while ((uint)InAddr<CodeSize)
} // if (XorSum==Code[0]) } // if (XorSum==Code[0])
var curCmd = new VM_PreparedCommand(); const curCmd = new VM_PreparedCommand();
prg.Cmd.push(curCmd); prg.Cmd.push(curCmd);
curCmd.OpCode = VM_Commands.VM_RET; curCmd.OpCode = VM_Commands.VM_RET;
// TODO: Addr=&CurCmd->Op1.Data // TODO: Addr=&CurCmd->Op1.Data
@ -730,8 +729,8 @@ RarVM.prototype.prepare = function(code, prg) {
// VM_OPINT type operands (usual integers) or maybe if something was // VM_OPINT type operands (usual integers) or maybe if something was
// not set properly for other operands. 'Addr' field is required // not set properly for other operands. 'Addr' field is required
// for quicker addressing of operand data. // for quicker addressing of operand data.
for (var i = 0; i < prg.Cmd.length; ++i) { for (let i = 0; i < prg.Cmd.length; ++i) {
var cmd = prg.Cmd[i]; const cmd = prg.Cmd[i];
if (cmd.Op1.Addr == null) { if (cmd.Op1.Addr == null) {
cmd.Op1.Addr = [cmd.Op1.Data]; cmd.Op1.Addr = [cmd.Op1.Data];
} }
@ -754,7 +753,7 @@ RarVM.prototype.prepare = function(code, prg) {
* @param {number} offset Offset into arr to start setting the value, defaults to 0. * @param {number} offset Offset into arr to start setting the value, defaults to 0.
*/ */
RarVM.prototype.setLowEndianValue = function(arr, value, offset) { RarVM.prototype.setLowEndianValue = function(arr, value, offset) {
var i = offset || 0; const i = offset || 0;
arr[i] = value & 0xff; arr[i] = value & 0xff;
arr[i + 1] = (value >>> 8) & 0xff; arr[i + 1] = (value >>> 8) & 0xff;
arr[i + 2] = (value >>> 16) & 0xff; arr[i + 2] = (value >>> 16) & 0xff;
@ -770,8 +769,8 @@ RarVM.prototype.setLowEndianValue = function(arr, value, offset) {
*/ */
RarVM.prototype.setMemory = function(pos, buffer, dataSize) { RarVM.prototype.setMemory = function(pos, buffer, dataSize) {
if (pos < VM_MEMSIZE) { if (pos < VM_MEMSIZE) {
var numBytes = Math.min(dataSize, VM_MEMSIZE - pos); const numBytes = Math.min(dataSize, VM_MEMSIZE - pos);
for (var i = 0; i < numBytes; ++i) { for (let i = 0; i < numBytes; ++i) {
this.mem_[pos + i] = buffer[i]; this.mem_[pos + i] = buffer[i];
} }
} }
@ -785,7 +784,7 @@ RarVM.prototype.setMemory = function(pos, buffer, dataSize) {
*/ */
RarVM.readData = function(bstream) { RarVM.readData = function(bstream) {
// Read in the first 2 bits. // Read in the first 2 bits.
var flags = bstream.readBits(2); const flags = bstream.readBits(2);
switch (flags) { // Data&0xc000 switch (flags) { // Data&0xc000
// Return the next 4 bits. // Return the next 4 bits.
case 0: case 0:
@ -805,7 +804,7 @@ RarVM.readData = function(bstream) {
// Read in the next 16. // Read in the next 16.
case 2: // 0x8000 case 2: // 0x8000
var val = bstream.getBits(); const val = bstream.getBits();
bstream.readBits(16); bstream.readBits(16);
return val; //bstream.readBits(16); return val; //bstream.readBits(16);

File diff suppressed because it is too large Load diff

View file

@ -15,21 +15,21 @@ importScripts('../io/bytestream.js');
importScripts('archive.js'); importScripts('archive.js');
// Progress variables. // Progress variables.
var currentFilename = ""; let currentFilename = "";
var currentFileNumber = 0; let currentFileNumber = 0;
var currentBytesUnarchivedInFile = 0; let currentBytesUnarchivedInFile = 0;
var currentBytesUnarchived = 0; let currentBytesUnarchived = 0;
var totalUncompressedBytesInArchive = 0; let totalUncompressedBytesInArchive = 0;
var totalFilesInArchive = 0; let totalFilesInArchive = 0;
// Helper functions. // Helper functions.
var info = function(str) { const info = function(str) {
postMessage(new bitjs.archive.UnarchiveInfoEvent(str)); postMessage(new bitjs.archive.UnarchiveInfoEvent(str));
}; };
var err = function(str) { const err = function(str) {
postMessage(new bitjs.archive.UnarchiveErrorEvent(str)); postMessage(new bitjs.archive.UnarchiveErrorEvent(str));
}; };
var postProgress = function() { const postProgress = function() {
postMessage(new bitjs.archive.UnarchiveProgressEvent( postMessage(new bitjs.archive.UnarchiveProgressEvent(
currentFilename, currentFilename,
currentFileNumber, currentFileNumber,
@ -40,14 +40,14 @@ var postProgress = function() {
}; };
// Removes all characters from the first zero-byte in the string onwards. // Removes all characters from the first zero-byte in the string onwards.
var readCleanString = function(bstr, numBytes) { const readCleanString = function(bstr, numBytes) {
var str = bstr.readString(numBytes); const str = bstr.readString(numBytes);
var zIndex = str.indexOf(String.fromCharCode(0)); const zIndex = str.indexOf(String.fromCharCode(0));
return zIndex != -1 ? str.substr(0, zIndex) : str; return zIndex != -1 ? str.substr(0, zIndex) : str;
}; };
// takes a ByteStream and parses out the local file information // takes a ByteStream and parses out the local file information
var TarLocalFile = function(bstream) { const TarLocalFile = function(bstream) {
this.isValid = false; this.isValid = false;
// Read in the header block // Read in the header block
@ -89,7 +89,7 @@ var TarLocalFile = function(bstream) {
// A regular file. // A regular file.
if (this.typeflag == 0) { if (this.typeflag == 0) {
info(" This is a regular file."); info(" This is a regular file.");
var sizeInBytes = parseInt(this.size); const sizeInBytes = parseInt(this.size);
this.fileData = new Uint8Array(bstream.bytes.buffer, bstream.ptr, this.size); this.fileData = new Uint8Array(bstream.bytes.buffer, bstream.ptr, this.size);
if (this.name.length > 0 && this.size > 0 && this.fileData && this.fileData.buffer) { if (this.name.length > 0 && this.size > 0 && this.fileData && this.fileData.buffer) {
this.isValid = true; this.isValid = true;
@ -98,7 +98,7 @@ var TarLocalFile = function(bstream) {
bstream.readBytes(this.size); bstream.readBytes(this.size);
// Round up to 512-byte blocks. // Round up to 512-byte blocks.
var remaining = 512 - bstream.ptr % 512; const remaining = 512 - bstream.ptr % 512;
if (remaining > 0 && remaining < 512) { if (remaining > 0 && remaining < 512) {
bstream.readBytes(remaining); bstream.readBytes(remaining);
} }
@ -110,7 +110,7 @@ var TarLocalFile = function(bstream) {
// Takes an ArrayBuffer of a tar file in // Takes an ArrayBuffer of a tar file in
// returns null on error // returns null on error
// returns an array of DecompressedFile objects on success // returns an array of DecompressedFile objects on success
var untar = function(arrayBuffer) { const untar = function(arrayBuffer) {
currentFilename = ""; currentFilename = "";
currentFileNumber = 0; currentFileNumber = 0;
currentBytesUnarchivedInFile = 0; currentBytesUnarchivedInFile = 0;
@ -119,12 +119,12 @@ var untar = function(arrayBuffer) {
totalFilesInArchive = 0; totalFilesInArchive = 0;
postMessage(new bitjs.archive.UnarchiveStartEvent()); postMessage(new bitjs.archive.UnarchiveStartEvent());
var bstream = new bitjs.io.ByteStream(arrayBuffer); const bstream = new bitjs.io.ByteStream(arrayBuffer);
var localFiles = []; const localFiles = [];
// While we don't encounter an empty block, keep making TarLocalFiles. // While we don't encounter an empty block, keep making TarLocalFiles.
while (bstream.peekNumber(4) != 0) { while (bstream.peekNumber(4) != 0) {
var oneLocalFile = new TarLocalFile(bstream); const oneLocalFile = new TarLocalFile(bstream);
if (oneLocalFile && oneLocalFile.isValid) { if (oneLocalFile && oneLocalFile.isValid) {
localFiles.push(oneLocalFile); localFiles.push(oneLocalFile);
totalUncompressedBytesInArchive += oneLocalFile.size; totalUncompressedBytesInArchive += oneLocalFile.size;
@ -134,29 +134,7 @@ var untar = function(arrayBuffer) {
// got all local files, now sort them // got all local files, now sort them
localFiles.sort(function(a,b) { localFiles.sort(function(a,b) {
var aname = a.filename; return a.filename > b.filename ? 1 : -1;
var bname = b.filename;
return aname > bname ? 1 : -1;
// extract the number at the end of both filenames
/*
var aname = a.filename;
var bname = b.filename;
var aindex = aname.length, bindex = bname.length;
// Find the last number character from the back of the filename.
while (aname[aindex-1] < '0' || aname[aindex-1] > '9') --aindex;
while (bname[bindex-1] < '0' || bname[bindex-1] > '9') --bindex;
// Find the first number character from the back of the filename
while (aname[aindex-1] >= '0' && aname[aindex-1] <= '9') --aindex;
while (bname[bindex-1] >= '0' && bname[bindex-1] <= '9') --bindex;
// parse them into numbers and return comparison
var anum = parseInt(aname.substr(aindex), 10),
bnum = parseInt(bname.substr(bindex), 10);
return anum - bnum;
*/
}); });
// report # files and total length // report # files and total length
@ -165,8 +143,8 @@ var untar = function(arrayBuffer) {
} }
// now do the shipping of each file // now do the shipping of each file
for (var i = 0; i < localFiles.length; ++i) { for (let i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i]; const localfile = localFiles[i];
info("Sending file '" + localfile.filename + "' up"); info("Sending file '" + localfile.filename + "' up");
// update progress // update progress
@ -185,6 +163,6 @@ var untar = function(arrayBuffer) {
// event.data.file has the ArrayBuffer. // event.data.file has the ArrayBuffer.
onmessage = function(event) { onmessage = function(event) {
var ab = event.data.file; const ab = event.data.file;
untar(ab); untar(ab);
}; };

View file

@ -19,21 +19,21 @@ importScripts('../io/bytestream.js');
importScripts('archive.js'); importScripts('archive.js');
// Progress variables. // Progress variables.
var currentFilename = ""; let currentFilename = "";
var currentFileNumber = 0; let currentFileNumber = 0;
var currentBytesUnarchivedInFile = 0; let currentBytesUnarchivedInFile = 0;
var currentBytesUnarchived = 0; let currentBytesUnarchived = 0;
var totalUncompressedBytesInArchive = 0; let totalUncompressedBytesInArchive = 0;
var totalFilesInArchive = 0; let totalFilesInArchive = 0;
// Helper functions. // Helper functions.
var info = function(str) { const info = function(str) {
postMessage(new bitjs.archive.UnarchiveInfoEvent(str)); postMessage(new bitjs.archive.UnarchiveInfoEvent(str));
}; };
var err = function(str) { const err = function(str) {
postMessage(new bitjs.archive.UnarchiveErrorEvent(str)); postMessage(new bitjs.archive.UnarchiveErrorEvent(str));
}; };
var postProgress = function() { const postProgress = function() {
postMessage(new bitjs.archive.UnarchiveProgressEvent( postMessage(new bitjs.archive.UnarchiveProgressEvent(
currentFilename, currentFilename,
currentFileNumber, currentFileNumber,
@ -43,15 +43,15 @@ var postProgress = function() {
totalFilesInArchive)); totalFilesInArchive));
}; };
var zLocalFileHeaderSignature = 0x04034b50; const zLocalFileHeaderSignature = 0x04034b50;
var zArchiveExtraDataSignature = 0x08064b50; const zArchiveExtraDataSignature = 0x08064b50;
var zCentralFileHeaderSignature = 0x02014b50; const zCentralFileHeaderSignature = 0x02014b50;
var zDigitalSignatureSignature = 0x05054b50; const zDigitalSignatureSignature = 0x05054b50;
var zEndOfCentralDirSignature = 0x06064b50; const zEndOfCentralDirSignature = 0x06064b50;
var zEndOfCentralDirLocatorSignature = 0x07064b50; const zEndOfCentralDirLocatorSignature = 0x07064b50;
// takes a ByteStream and parses out the local file information // takes a ByteStream and parses out the local file information
var ZipLocalFile = function(bstream) { const ZipLocalFile = function(bstream) {
if (typeof bstream != typeof {} || !bstream.readNumber || typeof bstream.readNumber != typeof function(){}) { if (typeof bstream != typeof {} || !bstream.readNumber || typeof bstream.readNumber != typeof function(){}) {
return null; return null;
} }
@ -112,7 +112,6 @@ var ZipLocalFile = function(bstream) {
// determine what kind of compressed data we have and decompress // determine what kind of compressed data we have and decompress
ZipLocalFile.prototype.unzip = function() { ZipLocalFile.prototype.unzip = function() {
// Zip Version 1.0, no compression (store only) // Zip Version 1.0, no compression (store only)
if (this.compressionMethod == 0 ) { if (this.compressionMethod == 0 ) {
info("ZIP v"+this.version+", store only: " + this.filename + " (" + this.compressedSize + " bytes)"); info("ZIP v"+this.version+", store only: " + this.filename + " (" + this.compressedSize + " bytes)");
@ -134,7 +133,7 @@ ZipLocalFile.prototype.unzip = function() {
// Takes an ArrayBuffer of a zip file in // Takes an ArrayBuffer of a zip file in
// returns null on error // returns null on error
// returns an array of DecompressedFile objects on success // returns an array of DecompressedFile objects on success
var unzip = function(arrayBuffer) { const unzip = function(arrayBuffer) {
postMessage(new bitjs.archive.UnarchiveStartEvent()); postMessage(new bitjs.archive.UnarchiveStartEvent());
currentFilename = ""; currentFilename = "";
@ -145,13 +144,13 @@ var unzip = function(arrayBuffer) {
totalFilesInArchive = 0; totalFilesInArchive = 0;
currentBytesUnarchived = 0; currentBytesUnarchived = 0;
var bstream = new bitjs.io.ByteStream(arrayBuffer); const bstream = new bitjs.io.ByteStream(arrayBuffer);
// detect local file header signature or return null // detect local file header signature or return null
if (bstream.peekNumber(4) == zLocalFileHeaderSignature) { if (bstream.peekNumber(4) == zLocalFileHeaderSignature) {
var localFiles = []; const localFiles = [];
// loop until we don't see any more local files // loop until we don't see any more local files
while (bstream.peekNumber(4) == zLocalFileHeaderSignature) { while (bstream.peekNumber(4) == zLocalFileHeaderSignature) {
var oneLocalFile = new ZipLocalFile(bstream); const oneLocalFile = new ZipLocalFile(bstream);
// this should strip out directories/folders // this should strip out directories/folders
if (oneLocalFile && oneLocalFile.uncompressedSize > 0 && oneLocalFile.fileData) { if (oneLocalFile && oneLocalFile.uncompressedSize > 0 && oneLocalFile.fileData) {
localFiles.push(oneLocalFile); localFiles.push(oneLocalFile);
@ -162,29 +161,7 @@ var unzip = function(arrayBuffer) {
// got all local files, now sort them // got all local files, now sort them
localFiles.sort(function(a,b) { localFiles.sort(function(a,b) {
var aname = a.filename; return a.filename > b.filename ? 1 : -1;
var bname = b.filename;
return aname > bname ? 1 : -1;
// extract the number at the end of both filenames
/*
var aname = a.filename;
var bname = b.filename;
var aindex = aname.length, bindex = bname.length;
// Find the last number character from the back of the filename.
while (aname[aindex-1] < '0' || aname[aindex-1] > '9') --aindex;
while (bname[bindex-1] < '0' || bname[bindex-1] > '9') --bindex;
// Find the first number character from the back of the filename
while (aname[aindex-1] >= '0' && aname[aindex-1] <= '9') --aindex;
while (bname[bindex-1] >= '0' && bname[bindex-1] <= '9') --bindex;
// parse them into numbers and return comparison
var anum = parseInt(aname.substr(aindex), 10),
bnum = parseInt(bname.substr(bindex), 10);
return anum - bnum;
*/
}); });
// archive extra data record // archive extra data record
@ -193,7 +170,7 @@ var unzip = function(arrayBuffer) {
// skipping this record for now // skipping this record for now
bstream.readNumber(4); bstream.readNumber(4);
var archiveExtraFieldLength = bstream.readNumber(4); const archiveExtraFieldLength = bstream.readNumber(4);
bstream.readString(archiveExtraFieldLength); bstream.readString(archiveExtraFieldLength);
} }
@ -214,9 +191,9 @@ var unzip = function(arrayBuffer) {
bstream.readNumber(4); // crc32 bstream.readNumber(4); // crc32
bstream.readNumber(4); // compressed size bstream.readNumber(4); // compressed size
bstream.readNumber(4); // uncompressed size bstream.readNumber(4); // uncompressed size
var fileNameLength = bstream.readNumber(2); // file name length const fileNameLength = bstream.readNumber(2); // file name length
var extraFieldLength = bstream.readNumber(2); // extra field length const extraFieldLength = bstream.readNumber(2); // extra field length
var fileCommentLength = bstream.readNumber(2); // file comment length const fileCommentLength = bstream.readNumber(2); // file comment length
bstream.readNumber(2); // disk number start bstream.readNumber(2); // disk number start
bstream.readNumber(2); // internal file attributes bstream.readNumber(2); // internal file attributes
bstream.readNumber(4); // external file attributes bstream.readNumber(4); // external file attributes
@ -233,7 +210,7 @@ var unzip = function(arrayBuffer) {
info(" Found a Digital Signature"); info(" Found a Digital Signature");
bstream.readNumber(4); bstream.readNumber(4);
var sizeOfSignature = bstream.readNumber(2); const sizeOfSignature = bstream.readNumber(2);
bstream.readString(sizeOfSignature); // digital signature data bstream.readString(sizeOfSignature); // digital signature data
} }
@ -243,8 +220,8 @@ var unzip = function(arrayBuffer) {
} }
// now do the unzipping of each file // now do the unzipping of each file
for (var i = 0; i < localFiles.length; ++i) { for (let i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i]; const localfile = localFiles[i];
// update progress // update progress
currentFilename = localfile.filename; currentFilename = localfile.filename;
@ -275,13 +252,13 @@ function getHuffmanCodes(bitLengths) {
} }
// Reference: http://tools.ietf.org/html/rfc1951#page-8 // Reference: http://tools.ietf.org/html/rfc1951#page-8
var numLengths = bitLengths.length, const numLengths = bitLengths.length;
bl_count = [], const bl_count = [];
MAX_BITS = 1; let MAX_BITS = 1;
// Step 1: count up how many codes of each length we have // Step 1: count up how many codes of each length we have
for (var i = 0; i < numLengths; ++i) { for (let i = 0; i < numLengths; ++i) {
var length = bitLengths[i]; const length = bitLengths[i];
// test to ensure each bit length is a positive, non-zero number // test to ensure each bit length is a positive, non-zero number
if (typeof length != typeof 1 || length < 0) { if (typeof length != typeof 1 || length < 0) {
err("bitLengths contained an invalid number in getHuffmanCodes(): " + length + " of type " + (typeof length)); err("bitLengths contained an invalid number in getHuffmanCodes(): " + length + " of type " + (typeof length));
@ -296,10 +273,10 @@ function getHuffmanCodes(bitLengths) {
} }
// Step 2: Find the numerical value of the smallest code for each code length // Step 2: Find the numerical value of the smallest code for each code length
var next_code = [], const next_code = [];
code = 0; let code = 0;
for (var bits = 1; bits <= MAX_BITS; ++bits) { for (let bits = 1; bits <= MAX_BITS; ++bits) {
var length = bits-1; const length = bits-1;
// ensure undefined lengths are zero // ensure undefined lengths are zero
if (bl_count[length] == undefined) bl_count[length] = 0; if (bl_count[length] == undefined) bl_count[length] = 0;
code = (code + bl_count[bits-1]) << 1; code = (code + bl_count[bits-1]) << 1;
@ -307,9 +284,10 @@ function getHuffmanCodes(bitLengths) {
} }
// Step 3: Assign numerical values to all codes // Step 3: Assign numerical values to all codes
var table = {}, tableLength = 0; const table = {};
for (var n = 0; n < numLengths; ++n) { let tableLength = 0;
var len = bitLengths[n]; for (let n = 0; n < numLengths; ++n) {
const len = bitLengths[n];
if (len != 0) { if (len != 0) {
table[next_code[len]] = { length: len, symbol: n }; //, bitstring: binaryValueToString(next_code[len],len) }; table[next_code[len]] = { length: len, symbol: n }; //, bitstring: binaryValueToString(next_code[len],len) };
tableLength++; tableLength++;
@ -338,16 +316,16 @@ function getHuffmanCodes(bitLengths) {
11000111 11000111
*/ */
// fixed Huffman codes go from 7-9 bits, so we need an array whose index can hold up to 9 bits // fixed Huffman codes go from 7-9 bits, so we need an array whose index can hold up to 9 bits
var fixedHCtoLiteral = null; let fixedHCtoLiteral = null;
var fixedHCtoDistance = null; let fixedHCtoDistance = null;
function getFixedLiteralTable() { function getFixedLiteralTable() {
// create once // create once
if (!fixedHCtoLiteral) { if (!fixedHCtoLiteral) {
var bitlengths = new Array(288); const bitlengths = new Array(288);
for (var i = 0; i <= 143; ++i) bitlengths[i] = 8; for (let i = 0; i <= 143; ++i) bitlengths[i] = 8;
for (i = 144; i <= 255; ++i) bitlengths[i] = 9; for (let i = 144; i <= 255; ++i) bitlengths[i] = 9;
for (i = 256; i <= 279; ++i) bitlengths[i] = 7; for (let i = 256; i <= 279; ++i) bitlengths[i] = 7;
for (i = 280; i <= 287; ++i) bitlengths[i] = 8; for (let i = 280; i <= 287; ++i) bitlengths[i] = 8;
// get huffman code table // get huffman code table
fixedHCtoLiteral = getHuffmanCodes(bitlengths); fixedHCtoLiteral = getHuffmanCodes(bitlengths);
@ -358,8 +336,8 @@ function getFixedLiteralTable() {
function getFixedDistanceTable() { function getFixedDistanceTable() {
// create once // create once
if (!fixedHCtoDistance) { if (!fixedHCtoDistance) {
var bitlengths = new Array(32); const bitlengths = new Array(32);
for (var i = 0; i < 32; ++i) { bitlengths[i] = 5; } for (let i = 0; i < 32; ++i) { bitlengths[i] = 5; }
// get huffman code table // get huffman code table
fixedHCtoDistance = getHuffmanCodes(bitlengths); fixedHCtoDistance = getHuffmanCodes(bitlengths);
@ -370,13 +348,14 @@ function getFixedDistanceTable() {
// extract one bit at a time until we find a matching Huffman Code // extract one bit at a time until we find a matching Huffman Code
// then return that symbol // then return that symbol
function decodeSymbol(bstream, hcTable) { function decodeSymbol(bstream, hcTable) {
var code = 0, len = 0; let code = 0;
var match = false; let len = 0;
let match = false;
// loop until we match // loop until we match
for (;;) { for (;;) {
// read in next bit // read in next bit
var bit = bstream.readBits(1); const bit = bstream.readBits(1);
code = (code<<1) | bit; code = (code<<1) | bit;
++len; ++len;
@ -394,7 +373,7 @@ function decodeSymbol(bstream, hcTable) {
} }
var CodeLengthCodeOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; const CodeLengthCodeOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
/* /*
Extra Extra Extra Extra Extra Extra
Code Bits Length(s) Code Bits Lengths Code Bits Length(s) Code Bits Length(s) Code Bits Lengths Code Bits Length(s)
@ -410,7 +389,7 @@ var CodeLengthCodeOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2
265 1 11,12 275 3 51-58 285 0 258 265 1 11,12 275 3 51-58 285 0 258
266 1 13,14 276 3 59-66 266 1 13,14 276 3 59-66
*/ */
var LengthLookupTable = [ const LengthLookupTable = [
[0,3], [0,4], [0,5], [0,6], [0,3], [0,4], [0,5], [0,6],
[0,7], [0,8], [0,9], [0,10], [0,7], [0,8], [0,9], [0,10],
[1,11], [1,13], [1,15], [1,17], [1,11], [1,13], [1,15], [1,17],
@ -435,7 +414,7 @@ var LengthLookupTable = [
8 3 17-24 18 8 513-768 28 13 16385-24576 8 3 17-24 18 8 513-768 28 13 16385-24576
9 3 25-32 19 8 769-1024 29 13 24577-32768 9 3 25-32 19 8 769-1024 29 13 24577-32768
*/ */
var DistLookupTable = [ const DistLookupTable = [
[0,1], [0,2], [0,3], [0,4], [0,1], [0,2], [0,3], [0,4],
[1,5], [1,7], [1,5], [1,7],
[2,9], [2,13], [2,9], [2,13],
@ -468,9 +447,10 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
stream, and copy length bytes from this stream, and copy length bytes from this
position to the output stream. position to the output stream.
*/ */
var numSymbols = 0, blockSize = 0; let numSymbols = 0;
let blockSize = 0;
for (;;) { for (;;) {
var symbol = decodeSymbol(bstream, hcLiteralTable); const symbol = decodeSymbol(bstream, hcLiteralTable);
++numSymbols; ++numSymbols;
if (symbol < 256) { if (symbol < 256) {
// copy literal byte to output // copy literal byte to output
@ -483,10 +463,10 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
break; break;
} }
else { else {
var lengthLookup = LengthLookupTable[symbol-257], const lengthLookup = LengthLookupTable[symbol - 257];
length = lengthLookup[1] + bstream.readBits(lengthLookup[0]), let length = lengthLookup[1] + bstream.readBits(lengthLookup[0]);
distLookup = DistLookupTable[decodeSymbol(bstream, hcDistanceTable)], const distLookup = DistLookupTable[decodeSymbol(bstream, hcDistanceTable)];
distance = distLookup[1] + bstream.readBits(distLookup[0]); let distance = distLookup[1] + bstream.readBits(distLookup[0]);
// now apply length and distance appropriately and copy to output // now apply length and distance appropriately and copy to output
@ -499,10 +479,10 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
// adds X,Y,X,Y,X to the output stream." // adds X,Y,X,Y,X to the output stream."
// //
// loop for each character // loop for each character
var ch = buffer.ptr - distance; let ch = buffer.ptr - distance;
blockSize += length; blockSize += length;
if(length > distance) { if(length > distance) {
var data = buffer.data; const data = buffer.data;
while (length--) { while (length--) {
buffer.insertByte(data[ch++]); buffer.insertByte(data[ch++]);
} }
@ -520,27 +500,29 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
// deflate: http://tools.ietf.org/html/rfc1951 // deflate: http://tools.ietf.org/html/rfc1951
function inflate(compressedData, numDecompressedBytes) { function inflate(compressedData, numDecompressedBytes) {
// Bit stream representing the compressed data. // Bit stream representing the compressed data.
var bstream = new bitjs.io.BitStream(compressedData.buffer, const bstream = new bitjs.io.BitStream(compressedData.buffer,
false /* rtl */, false /* rtl */,
compressedData.byteOffset, compressedData.byteOffset,
compressedData.byteLength); compressedData.byteLength);
var buffer = new bitjs.io.ByteBuffer(numDecompressedBytes); const buffer = new bitjs.io.ByteBuffer(numDecompressedBytes);
var numBlocks = 0, blockSize = 0; let numBlocks = 0;
let blockSize = 0;
// block format: http://tools.ietf.org/html/rfc1951#page-9 // block format: http://tools.ietf.org/html/rfc1951#page-9
let bFinal = 0;
do { do {
var bFinal = bstream.readBits(1), bFinal = bstream.readBits(1);
bType = bstream.readBits(2); let bType = bstream.readBits(2);
blockSize = 0; blockSize = 0;
++numBlocks; ++numBlocks;
// no compression // no compression
if (bType == 0) { if (bType == 0) {
// skip remaining bits in this byte // skip remaining bits in this byte
while (bstream.bitPtr != 0) bstream.readBits(1); while (bstream.bitPtr != 0) bstream.readBits(1);
var len = bstream.readBits(16), const len = bstream.readBits(16);
nlen = bstream.readBits(16); const nlen = bstream.readBits(16);
// TODO: check if nlen is the ones-complement of len? // TODO: check if nlen is the ones-complement of len?
if(len > 0) buffer.insertBytes(bstream.readBytes(len)); if (len > 0) buffer.insertBytes(bstream.readBytes(len));
blockSize = len; blockSize = len;
} }
// fixed Huffman codes // fixed Huffman codes
@ -549,18 +531,18 @@ function inflate(compressedData, numDecompressedBytes) {
} }
// dynamic Huffman codes // dynamic Huffman codes
else if(bType == 2) { else if(bType == 2) {
var numLiteralLengthCodes = bstream.readBits(5) + 257; const numLiteralLengthCodes = bstream.readBits(5) + 257;
var numDistanceCodes = bstream.readBits(5) + 1, const numDistanceCodes = bstream.readBits(5) + 1;
numCodeLengthCodes = bstream.readBits(4) + 4; const numCodeLengthCodes = bstream.readBits(4) + 4;
// populate the array of code length codes (first de-compaction) // populate the array of code length codes (first de-compaction)
var codeLengthsCodeLengths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; const codeLengthsCodeLengths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
for (var i = 0; i < numCodeLengthCodes; ++i) { for (let i = 0; i < numCodeLengthCodes; ++i) {
codeLengthsCodeLengths[ CodeLengthCodeOrder[i] ] = bstream.readBits(3); codeLengthsCodeLengths[ CodeLengthCodeOrder[i] ] = bstream.readBits(3);
} }
// get the Huffman Codes for the code lengths // get the Huffman Codes for the code lengths
var codeLengthsCodes = getHuffmanCodes(codeLengthsCodeLengths); const codeLengthsCodes = getHuffmanCodes(codeLengthsCodeLengths);
// now follow this mapping // now follow this mapping
/* /*
@ -578,28 +560,28 @@ function inflate(compressedData, numDecompressedBytes) {
*/ */
// to generate the true code lengths of the Huffman Codes for the literal // to generate the true code lengths of the Huffman Codes for the literal
// and distance tables together // and distance tables together
var literalCodeLengths = []; const literalCodeLengths = [];
var prevCodeLength = 0; let prevCodeLength = 0;
while (literalCodeLengths.length < numLiteralLengthCodes + numDistanceCodes) { while (literalCodeLengths.length < numLiteralLengthCodes + numDistanceCodes) {
var symbol = decodeSymbol(bstream, codeLengthsCodes); const symbol = decodeSymbol(bstream, codeLengthsCodes);
if (symbol <= 15) { if (symbol <= 15) {
literalCodeLengths.push(symbol); literalCodeLengths.push(symbol);
prevCodeLength = symbol; prevCodeLength = symbol;
} }
else if (symbol == 16) { else if (symbol == 16) {
var repeat = bstream.readBits(2) + 3; let repeat = bstream.readBits(2) + 3;
while (repeat--) { while (repeat--) {
literalCodeLengths.push(prevCodeLength); literalCodeLengths.push(prevCodeLength);
} }
} }
else if (symbol == 17) { else if (symbol == 17) {
var repeat = bstream.readBits(3) + 3; let repeat = bstream.readBits(3) + 3;
while (repeat--) { while (repeat--) {
literalCodeLengths.push(0); literalCodeLengths.push(0);
} }
} }
else if (symbol == 18) { else if (symbol == 18) {
var repeat = bstream.readBits(7) + 11; let repeat = bstream.readBits(7) + 11;
while (repeat--) { while (repeat--) {
literalCodeLengths.push(0); literalCodeLengths.push(0);
} }
@ -607,11 +589,11 @@ function inflate(compressedData, numDecompressedBytes) {
} }
// now split the distance code lengths out of the literal code array // now split the distance code lengths out of the literal code array
var distanceCodeLengths = literalCodeLengths.splice(numLiteralLengthCodes, numDistanceCodes); const distanceCodeLengths = literalCodeLengths.splice(numLiteralLengthCodes, numDistanceCodes);
// now generate the true Huffman Code tables using these code lengths // now generate the true Huffman Code tables using these code lengths
var hcLiteralTable = getHuffmanCodes(literalCodeLengths), const hcLiteralTable = getHuffmanCodes(literalCodeLengths);
hcDistanceTable = getHuffmanCodes(distanceCodeLengths); const hcDistanceTable = getHuffmanCodes(distanceCodeLengths);
blockSize = inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer); blockSize = inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer);
} }
// error // error

View file

@ -21,7 +21,7 @@ bitjs.BIT = [ 0x01, 0x02, 0x04, 0x08,
0x1000, 0x2000, 0x4000, 0x8000]; 0x1000, 0x2000, 0x4000, 0x8000];
// mask for getting N number of bits (0-8) // mask for getting N number of bits (0-8)
var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ]; const BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
/** /**
@ -38,8 +38,8 @@ bitjs.io.BitStream = function(ab, rtl, opt_offset, opt_length) {
throw "Error! BitArray constructed with an invalid ArrayBuffer object"; throw "Error! BitArray constructed with an invalid ArrayBuffer object";
} }
var offset = opt_offset || 0; const offset = opt_offset || 0;
var length = opt_length || ab.byteLength; const length = opt_length || ab.byteLength;
this.bytes = new Uint8Array(ab, offset, length); this.bytes = new Uint8Array(ab, offset, length);
this.bytePtr = 0; // tracks which byte we are on this.bytePtr = 0; // tracks which byte we are on
this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7) this.bitPtr = 0; // tracks which bit we are on (can have values 0 through 7)
@ -57,17 +57,17 @@ bitjs.io.BitStream = function(ab, rtl, opt_offset, opt_length) {
* @param {boolean=} movePointers Whether to move the pointer, defaults false. * @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {number} The peeked bits, as an unsigned number. * @return {number} The peeked bits, as an unsigned number.
*/ */
bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) { bitjs.io.BitStream.prototype.peekBits_ltr = function(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
var movePointers = movePointers || false, const movePointers = opt_movePointers || false;
bytePtr = this.bytePtr, const bytes = this.bytes;
bitPtr = this.bitPtr, let bytePtr = this.bytePtr;
result = 0, let bitPtr = this.bitPtr;
bitsIn = 0, let result = 0;
bytes = this.bytes; let bitsIn = 0;
// keep going until we have no more bits left to peek at // keep going until we have no more bits left to peek at
// TODO: Consider putting all bits from bytes we will need into a variable and then // TODO: Consider putting all bits from bytes we will need into a variable and then
@ -80,9 +80,9 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) {
return -1; return -1;
} }
var numBitsLeftInThisByte = (8 - bitPtr); const numBitsLeftInThisByte = (8 - bitPtr);
if (n >= numBitsLeftInThisByte) { if (n >= numBitsLeftInThisByte) {
var mask = (BITMASK[numBitsLeftInThisByte] << bitPtr); const mask = (BITMASK[numBitsLeftInThisByte] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn); result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bytePtr++; bytePtr++;
@ -91,7 +91,7 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) {
n -= numBitsLeftInThisByte; n -= numBitsLeftInThisByte;
} }
else { else {
var mask = (BITMASK[n] << bitPtr); const mask = (BITMASK[n] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn); result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bitPtr += n; bitPtr += n;
@ -119,16 +119,16 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) {
* @param {boolean=} movePointers Whether to move the pointer, defaults false. * @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {number} The peeked bits, as an unsigned number. * @return {number} The peeked bits, as an unsigned number.
*/ */
bitjs.io.BitStream.prototype.peekBits_rtl = function(n, movePointers) { bitjs.io.BitStream.prototype.peekBits_rtl = function(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
var movePointers = movePointers || false, const movePointers = opt_movePointers || false;
bytePtr = this.bytePtr, const bytes = this.bytes;
bitPtr = this.bitPtr, let bytePtr = this.bytePtr;
result = 0, let bitPtr = this.bitPtr;
bytes = this.bytes; let result = 0;
// keep going until we have no more bits left to peek at // keep going until we have no more bits left to peek at
// TODO: Consider putting all bits from bytes we will need into a variable and then // TODO: Consider putting all bits from bytes we will need into a variable and then
@ -142,7 +142,7 @@ bitjs.io.BitStream.prototype.peekBits_rtl = function(n, movePointers) {
return -1; return -1;
} }
var numBitsLeftInThisByte = (8 - bitPtr); const numBitsLeftInThisByte = (8 - bitPtr);
if (n >= numBitsLeftInThisByte) { if (n >= numBitsLeftInThisByte) {
result <<= numBitsLeftInThisByte; result <<= numBitsLeftInThisByte;
result |= (BITMASK[numBitsLeftInThisByte] & bytes[bytePtr]); result |= (BITMASK[numBitsLeftInThisByte] & bytes[bytePtr]);
@ -199,7 +199,7 @@ bitjs.io.BitStream.prototype.readBits = function(n) {
* @param {boolean=} movePointers Whether to move the pointer, defaults false. * @param {boolean=} movePointers Whether to move the pointer, defaults false.
* @return {Uint8Array} The subarray. * @return {Uint8Array} The subarray.
*/ */
bitjs.io.BitStream.prototype.peekBytes = function(n, movePointers) { bitjs.io.BitStream.prototype.peekBytes = function(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -210,11 +210,11 @@ bitjs.io.BitStream.prototype.peekBytes = function(n, movePointers) {
this.readBits(1); this.readBits(1);
} }
var movePointers = movePointers || false; const movePointers = opt_movePointers || false;
var bytePtr = this.bytePtr, let bytePtr = this.bytePtr;
bitPtr = this.bitPtr; let bitPtr = this.bitPtr;
var result = this.bytes.subarray(bytePtr, bytePtr + n); const result = this.bytes.subarray(bytePtr, bytePtr + n);
if (movePointers) { if (movePointers) {
this.bytePtr += n; this.bytePtr += n;

View file

@ -67,9 +67,9 @@ bitjs.io.ByteBuffer.prototype.writeNumber = function(num, numBytes) {
} }
// Roll 8-bits at a time into an array of bytes. // Roll 8-bits at a time into an array of bytes.
var bytes = []; const bytes = [];
while (numBytes-- > 0) { while (numBytes-- > 0) {
var eightBits = num & 255; const eightBits = num & 255;
bytes.push(eightBits); bytes.push(eightBits);
num >>= 8; num >>= 8;
} }
@ -89,15 +89,15 @@ bitjs.io.ByteBuffer.prototype.writeSignedNumber = function(num, numBytes) {
throw 'Trying to write into too few bytes: ' + numBytes; throw 'Trying to write into too few bytes: ' + numBytes;
} }
var HALF = Math.pow(2, (numBytes * 8) - 1); const HALF = Math.pow(2, (numBytes * 8) - 1);
if (num >= HALF || num < -HALF) { if (num >= HALF || num < -HALF) {
throw 'Trying to write ' + num + ' into only ' + numBytes + ' bytes'; throw 'Trying to write ' + num + ' into only ' + numBytes + ' bytes';
} }
// Roll 8-bits at a time into an array of bytes. // Roll 8-bits at a time into an array of bytes.
var bytes = []; const bytes = [];
while (numBytes-- > 0) { while (numBytes-- > 0) {
var eightBits = num & 255; const eightBits = num & 255;
bytes.push(eightBits); bytes.push(eightBits);
num >>= 8; num >>= 8;
} }
@ -110,8 +110,8 @@ bitjs.io.ByteBuffer.prototype.writeSignedNumber = function(num, numBytes) {
* @param {string} str The ASCII string to write. * @param {string} str The ASCII string to write.
*/ */
bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) { bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) {
for (var i = 0; i < str.length; ++i) { for (let i = 0; i < str.length; ++i) {
var curByte = str.charCodeAt(i); const curByte = str.charCodeAt(i);
if (curByte < 0 || curByte > 255) { if (curByte < 0 || curByte > 255) {
throw 'Trying to write a non-ASCII string!'; throw 'Trying to write a non-ASCII string!';
} }

View file

@ -25,8 +25,8 @@ bitjs.io = bitjs.io || {};
* @constructor * @constructor
*/ */
bitjs.io.ByteStream = function(ab, opt_offset, opt_length) { bitjs.io.ByteStream = function(ab, opt_offset, opt_length) {
var offset = opt_offset || 0; const offset = opt_offset || 0;
var length = opt_length || ab.byteLength; const length = opt_length || ab.byteLength;
this.bytes = new Uint8Array(ab, offset, length); this.bytes = new Uint8Array(ab, offset, length);
this.ptr = 0; this.ptr = 0;
}; };
@ -44,9 +44,9 @@ bitjs.io.ByteStream.prototype.peekNumber = function(n) {
if (n <= 0 || typeof n != typeof 1) if (n <= 0 || typeof n != typeof 1)
return -1; return -1;
var result = 0; let result = 0;
// read from last byte to first byte and roll them in // read from last byte to first byte and roll them in
var curByte = this.ptr + n - 1; let curByte = this.ptr + n - 1;
while (curByte >= this.ptr) { while (curByte >= this.ptr) {
result <<= 8; result <<= 8;
result |= this.bytes[curByte]; result |= this.bytes[curByte];
@ -63,7 +63,7 @@ bitjs.io.ByteStream.prototype.peekNumber = function(n) {
* @return {number} The n bytes interpreted as an unsigned number. * @return {number} The n bytes interpreted as an unsigned number.
*/ */
bitjs.io.ByteStream.prototype.readNumber = function(n) { bitjs.io.ByteStream.prototype.readNumber = function(n) {
var num = this.peekNumber( n ); const num = this.peekNumber( n );
this.ptr += n; this.ptr += n;
return num; return num;
}; };
@ -76,9 +76,9 @@ bitjs.io.ByteStream.prototype.readNumber = function(n) {
* @return {number} The bytes interpreted as a signed number. * @return {number} The bytes interpreted as a signed number.
*/ */
bitjs.io.ByteStream.prototype.peekSignedNumber = function(n) { bitjs.io.ByteStream.prototype.peekSignedNumber = function(n) {
var num = this.peekNumber(n); let num = this.peekNumber(n);
var HALF = Math.pow(2, (n * 8) - 1); const HALF = Math.pow(2, (n * 8) - 1);
var FULL = HALF * 2; const FULL = HALF * 2;
if (num >= HALF) num -= FULL; if (num >= HALF) num -= FULL;
@ -92,7 +92,7 @@ bitjs.io.ByteStream.prototype.peekSignedNumber = function(n) {
* @return {number} The bytes interpreted as a signed number. * @return {number} The bytes interpreted as a signed number.
*/ */
bitjs.io.ByteStream.prototype.readSignedNumber = function(n) { bitjs.io.ByteStream.prototype.readSignedNumber = function(n) {
var num = this.peekSignedNumber(n); const num = this.peekSignedNumber(n);
this.ptr += n; this.ptr += n;
return num; return num;
}; };
@ -110,7 +110,7 @@ bitjs.io.ByteStream.prototype.peekBytes = function(n, movePointers) {
return null; return null;
} }
var result = this.bytes.subarray(this.ptr, this.ptr + n); const result = this.bytes.subarray(this.ptr, this.ptr + n);
if (movePointers) { if (movePointers) {
this.ptr += n; this.ptr += n;
@ -140,8 +140,8 @@ bitjs.io.ByteStream.prototype.peekString = function(n) {
return ""; return "";
} }
var result = ""; let result = "";
for (var p = this.ptr, end = this.ptr + n; p < end; ++p) { for (let p = this.ptr, end = this.ptr + n; p < end; ++p) {
result += String.fromCharCode(this.bytes[p]); result += String.fromCharCode(this.bytes[p]);
} }
return result; return result;
@ -155,7 +155,7 @@ bitjs.io.ByteStream.prototype.peekString = function(n) {
* @return {string} The next n bytes as a string. * @return {string} The next n bytes as a string.
*/ */
bitjs.io.ByteStream.prototype.readString = function(n) { bitjs.io.ByteStream.prototype.readString = function(n) {
var strToReturn = this.peekString(n); const strToReturn = this.peekString(n);
this.ptr += n; this.ptr += n;
return strToReturn; return strToReturn;
}; };

View file

@ -6,8 +6,8 @@
* Copyright(c) 2017 Google Inc. * Copyright(c) 2017 Google Inc.
*/ */
var assertEquals = muther.assertEquals; const assertEquals = muther.assertEquals;
var testInputs = { const testInputs = {
'testUnzipDeflate': 'archive-testfiles/test-unzip-deflate.json', 'testUnzipDeflate': 'archive-testfiles/test-unzip-deflate.json',
'testUnzipStore': 'archive-testfiles/test-unzip-store.json', 'testUnzipStore': 'archive-testfiles/test-unzip-store.json',
'testUnrarM1': 'archive-testfiles/test-unrar-m1.json', 'testUnrarM1': 'archive-testfiles/test-unrar-m1.json',
@ -18,33 +18,33 @@ var testInputs = {
'testUnrarMA4': 'archive-testfiles/test-unrar-ma4.json', 'testUnrarMA4': 'archive-testfiles/test-unrar-ma4.json',
}; };
var testSuite = {tests: {}}; const testSuite = {tests: {}};
for (var testName in testInputs) { for (let testName in testInputs) {
var testInputFilename = testInputs[testName]; const testInputFilename = testInputs[testName];
testSuite.tests[testName] = new Promise(function(resolve, reject) { testSuite.tests[testName] = new Promise(function(resolve, reject) {
var scriptEl = document.createElement('script'); const scriptEl = document.createElement('script');
scriptEl.setAttribute('src', testInputFilename); scriptEl.setAttribute('src', testInputFilename);
scriptEl.addEventListener('load', function(evt) { scriptEl.addEventListener('load', function(evt) {
// document.body.removeChild(scriptEl); // document.body.removeChild(scriptEl);
var testFile = window.archiveTestFile; const testFile = window.archiveTestFile;
var archivedFile = new Uint8Array( const archivedFile = new Uint8Array(
atob(testFile.archivedFile) atob(testFile.archivedFile)
.split(',') .split(',')
.map(function(str) { return parseInt(str); }) .map(function(str) { return parseInt(str); })
); );
var unarchivedFile = new Uint8Array( const unarchivedFile = new Uint8Array(
atob(testFile.unarchivedFile) atob(testFile.unarchivedFile)
.split(',') .split(',')
.map(function(str) { return parseInt(str); }) .map(function(str) { return parseInt(str); })
); );
var unarchiver = bitjs.archive.GetUnarchiver(archivedFile.buffer, '../archive/'); const unarchiver = bitjs.archive.GetUnarchiver(archivedFile.buffer, '../');
unarchiver.addEventListener(bitjs.archive.UnarchiveEvent.Type.EXTRACT, function(evt) { unarchiver.addEventListener(bitjs.archive.UnarchiveEvent.Type.EXTRACT, function(evt) {
var theUnarchivedFile = evt.unarchivedFile.fileData; const theUnarchivedFile = evt.unarchivedFile.fileData;
try { try {
assertEquals(theUnarchivedFile.length, unarchivedFile.length, assertEquals(theUnarchivedFile.length, unarchivedFile.length,
'The unarchived buffer was not the right length'); 'The unarchived buffer was not the right length');
for (var i = 0; i < theUnarchivedFile.length; ++i) { for (let i = 0; i < theUnarchivedFile.length; ++i) {
assertEquals(theUnarchivedFile[i], unarchivedFile[i], assertEquals(theUnarchivedFile[i], unarchivedFile[i],
'Byte #' + i + ' did not match'); 'Byte #' + i + ' did not match');
} }

View file

@ -18,18 +18,17 @@ muther.set_ = function(id, style, innerHTML) {
muther.go = function(spec) { muther.go = function(spec) {
Object.keys(spec['tests']).forEach(function(testName) { Object.keys(spec['tests']).forEach(function(testName) {
var test = spec['tests'][testName]; const test = spec['tests'][testName];
if (test instanceof Promise) { if (test instanceof Promise) {
muther.set_(testName, 'color:#F90', 'RUNNING: ' + testName); muther.set_(testName, 'color:#F90', 'RUNNING: ' + testName);
// TODO: What if we want setup() and tearDown()?
test.then(function() { test.then(function() {
muther.set_(testName, 'color:#090', 'PASS: ' + testName); muther.set_(testName, 'color:#090', 'PASS: ' + testName);
}, function(err) { }, function(err) {
muther.set_(testName, 'color:#900', 'FAIL: ' + testName + ': ' + err); muther.set_(testName, 'color:#900', 'FAIL: ' + testName + ': ' + err);
}); });
} else if (test instanceof Function) { } else if (test instanceof Function) {
var setup = spec['setUp'] || function(){}; const setup = spec['setUp'] || function(){};
var tearDown = spec['tearDown'] || function(){}; const tearDown = spec['tearDown'] || function(){};
try { try {
setup(); test(); tearDown(); setup(); test(); tearDown();
muther.set_(testName, 'color:#090', 'PASS: ' + testName); muther.set_(testName, 'color:#090', 'PASS: ' + testName);

View file

@ -20,10 +20,10 @@
} }
*/ */
var archiveUploaderEl = null; let archiveUploaderEl = null;
var archivedFileAsText = null; let archivedFileAsText = null;
var unarchiveUploaderEl = null; let unarchiveUploaderEl = null;
var unarchivedFileAsText = null; let unarchivedFileAsText = null;
function init() { function init() {
archiveUploaderEl = document.querySelector('#archive-uploader'); archiveUploaderEl = document.querySelector('#archive-uploader');
@ -34,10 +34,10 @@ function init() {
} }
function getArchivedFile(evt) { function getArchivedFile(evt) {
var filelist = evt.target.files; const filelist = evt.target.files;
var fr = new FileReader(); const fr = new FileReader();
fr.onload = function() { fr.onload = function() {
var arr = new Uint8Array(fr.result); const arr = new Uint8Array(fr.result);
archivedFileAsText = btoa(arr); archivedFileAsText = btoa(arr);
archiveUploaderEl.setAttribute('disabled', 'true'); archiveUploaderEl.setAttribute('disabled', 'true');
unarchiveUploaderEl.removeAttribute('disabled'); unarchiveUploaderEl.removeAttribute('disabled');
@ -46,10 +46,10 @@ function getArchivedFile(evt) {
} }
function getUnarchivedFile(evt) { function getUnarchivedFile(evt) {
var filelist = evt.target.files; const filelist = evt.target.files;
var fr = new FileReader(); const fr = new FileReader();
fr.onload = function() { fr.onload = function() {
var arr = new Uint8Array(fr.result); const arr = new Uint8Array(fr.result);
unarchivedFileAsText = btoa(arr); unarchivedFileAsText = btoa(arr);
unarchiveUploaderEl.setAttribute('disabled', 'true'); unarchiveUploaderEl.setAttribute('disabled', 'true');
output(); output();
@ -58,7 +58,7 @@ function getUnarchivedFile(evt) {
} }
function output() { function output() {
var json = 'window.archiveTestFile = {\n'; let json = 'window.archiveTestFile = {\n';
json += ' "archivedFile": "' + archivedFileAsText + '",\n'; json += ' "archivedFile": "' + archivedFileAsText + '",\n';
json += ' "unarchivedFile": "' + unarchivedFileAsText + '"\n'; json += ' "unarchivedFile": "' + unarchivedFileAsText + '"\n';
json += '}'; json += '}';