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

Convert to ES6 classes

This commit is contained in:
codedread 2017-02-20 14:36:48 -08:00
parent 639a23e69b
commit 14abef20d6
8 changed files with 1385 additions and 1415 deletions

View file

@ -11,65 +11,22 @@
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.archive = bitjs.archive || {}; bitjs.archive = bitjs.archive || {};
(function() {
// ===========================================================================
// Stolen from Closure because it's the best way to do Java-like inheritance.
bitjs.base = function(me, opt_methodName, var_args) {
const caller = arguments.callee.caller;
if (caller.superClass_) {
// This is a constructor. Call the superclass constructor.
return caller.superClass_.constructor.apply(
me, Array.prototype.slice.call(arguments, 1));
}
const args = Array.prototype.slice.call(arguments, 2);
let foundCaller = false;
for (let ctor = me.constructor;
ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
if (ctor.prototype[opt_methodName] === caller) {
foundCaller = true;
} else if (foundCaller) {
return ctor.prototype[opt_methodName].apply(me, args);
}
}
// If we did not find the caller in the prototype chain,
// then one of two things happened:
// 1) The caller is an instance method.
// 2) This method was not called by the right caller.
if (me[opt_methodName] === caller) {
return me.constructor.prototype[opt_methodName].apply(me, args);
} else {
throw Error(
'goog.base called from a method of one name ' +
'to a method of a different name');
}
};
bitjs.inherits = function(childCtor, parentCtor) {
/** @constructor */
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
// ===========================================================================
/** /**
* An unarchive event. * An unarchive event.
*
* @param {string} type The event type.
* @constructor
*/ */
bitjs.archive.UnarchiveEvent = function(type) { bitjs.archive.UnarchiveEvent = class {
/**
* @param {string} type The event type.
*/
constructor(type) {
/** /**
* The event type. * The event type.
* *
* @type {string} * @type {string}
*/ */
this.type = type; this.type = type;
}; }
}
/** /**
* The UnarchiveEvent types. * The UnarchiveEvent types.
@ -85,11 +42,13 @@ bitjs.archive.UnarchiveEvent.Type = {
/** /**
* Useful for passing info up to the client (for debugging). * Useful for passing info up to the client (for debugging).
* */
bitjs.archive.UnarchiveInfoEvent = class extends bitjs.archive.UnarchiveEvent {
/**
* @param {string} msg The info message. * @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveInfoEvent = function(msg) { constructor(msg) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.INFO); super(bitjs.archive.UnarchiveEvent.Type.INFO);
/** /**
* The information message. * The information message.
@ -97,16 +56,18 @@ bitjs.archive.UnarchiveInfoEvent = function(msg) {
* @type {string} * @type {string}
*/ */
this.msg = msg; this.msg = msg;
}; }
bitjs.inherits(bitjs.archive.UnarchiveInfoEvent, bitjs.archive.UnarchiveEvent); }
/** /**
* An unrecoverable error has occured. * An unrecoverable error has occured.
* */
bitjs.archive.UnarchiveErrorEvent = class extends bitjs.archive.UnarchiveEvent {
/**
* @param {string} msg The error message. * @param {string} msg The error message.
*/ */
bitjs.archive.UnarchiveErrorEvent = function(msg) { constructor(msg) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.ERROR); super(bitjs.archive.UnarchiveEvent.Type.ERROR);
/** /**
* The information message. * The information message.
@ -114,40 +75,42 @@ bitjs.archive.UnarchiveErrorEvent = function(msg) {
* @type {string} * @type {string}
*/ */
this.msg = msg; this.msg = msg;
}; }
bitjs.inherits(bitjs.archive.UnarchiveErrorEvent, bitjs.archive.UnarchiveEvent); }
/** /**
* Start event. * Start event.
*
* @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveStartEvent = function() { bitjs.archive.UnarchiveStartEvent = class extends bitjs.archive.UnarchiveEvent {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.START); constructor() {
}; super(bitjs.archive.UnarchiveEvent.Type.START);
bitjs.inherits(bitjs.archive.UnarchiveStartEvent, bitjs.archive.UnarchiveEvent); }
}
/** /**
* Finish event. * Finish event.
*
* @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveFinishEvent = function() { bitjs.archive.UnarchiveFinishEvent = class extends bitjs.archive.UnarchiveEvent {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.FINISH); constructor() {
}; super(bitjs.archive.UnarchiveEvent.Type.FINISH);
bitjs.inherits(bitjs.archive.UnarchiveFinishEvent, bitjs.archive.UnarchiveEvent); }
}
/** /**
* Progress event. * Progress event.
*/ */
bitjs.archive.UnarchiveProgressEvent = function( bitjs.archive.UnarchiveProgressEvent = class extends bitjs.archive.UnarchiveEvent {
currentFilename, /**
currentFileNumber, * @param {string} currentFilename
currentBytesUnarchivedInFile, * @param {number} currentFileNumber
currentBytesUnarchived, * @param {number} currentBytesUnarchivedInFile
totalUncompressedBytesInArchive, * @param {number} currentBytesUnarchived
totalFilesInArchive) { * @param {number} totalUncompressedBytesInArchive
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.PROGRESS); * @param {number} totalFilesInArchive
*/
constructor(currentFilename, currentFileNumber, currentBytesUnarchivedInFile,
currentBytesUnarchived, totalUncompressedBytesInArchive, totalFilesInArchive) {
super(bitjs.archive.UnarchiveEvent.Type.PROGRESS);
this.currentFilename = currentFilename; this.currentFilename = currentFilename;
this.currentFileNumber = currentFileNumber; this.currentFileNumber = currentFileNumber;
@ -155,8 +118,25 @@ bitjs.archive.UnarchiveProgressEvent = function(
this.totalFilesInArchive = totalFilesInArchive; this.totalFilesInArchive = totalFilesInArchive;
this.currentBytesUnarchived = currentBytesUnarchived; this.currentBytesUnarchived = currentBytesUnarchived;
this.totalUncompressedBytesInArchive = totalUncompressedBytesInArchive; this.totalUncompressedBytesInArchive = totalUncompressedBytesInArchive;
}; }
bitjs.inherits(bitjs.archive.UnarchiveProgressEvent, bitjs.archive.UnarchiveEvent); }
/**
* Extract event.
*/
bitjs.archive.UnarchiveExtractEvent = class extends bitjs.archive.UnarchiveEvent {
/**
* @param {UnarchivedFile} unarchivedFile
*/
constructor(unarchivedFile) {
super(bitjs.archive.UnarchiveEvent.Type.EXTRACT);
/**
* @type {UnarchivedFile}
*/
this.unarchivedFile = unarchivedFile;
}
}
/** /**
* All extracted files returned by an Unarchiver will implement * All extracted files returned by an Unarchiver will implement
@ -169,28 +149,15 @@ bitjs.inherits(bitjs.archive.UnarchiveProgressEvent, bitjs.archive.UnarchiveEven
* *
*/ */
/**
* Extract event.
*/
bitjs.archive.UnarchiveExtractEvent = function(unarchivedFile) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.EXTRACT);
/**
* @type {UnarchivedFile}
*/
this.unarchivedFile = unarchivedFile;
};
bitjs.inherits(bitjs.archive.UnarchiveExtractEvent, bitjs.archive.UnarchiveEvent);
/** /**
* Base class for all Unarchivers. * Base class for all Unarchivers.
* */
bitjs.archive.Unarchiver = class {
/**
* @param {ArrayBuffer} arrayBuffer The Array Buffer. * @param {ArrayBuffer} arrayBuffer The Array Buffer.
* @param {string} opt_pathToBitJS Optional string for where the BitJS files are located. * @param {string} opt_pathToBitJS Optional string for where the BitJS files are located.
* @constructor
*/ */
bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) { constructor(arrayBuffer, opt_pathToBitJS) {
/** /**
* The ArrayBuffer object. * The ArrayBuffer object.
* @type {ArrayBuffer} * @type {ArrayBuffer}
@ -213,60 +180,60 @@ bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) {
for (let 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]] = [];
} }
};
/** /**
* Private web worker initialized during start(). * Private web worker initialized during start().
* @type {Worker} * @type {Worker}
* @private * @private
*/ */
bitjs.archive.Unarchiver.prototype.worker_ = null; this.worker_ = null;
}
/** /**
* This method must be overridden by the subclass to return the script filename. * This method must be overridden by the subclass to return the script filename.
* @return {string} The script filename. * @return {string} The script filename.
* @protected. * @protected.
*/ */
bitjs.archive.Unarchiver.prototype.getScriptFileName = function() { getScriptFileName() {
throw 'Subclasses of AbstractUnarchiver must overload getScriptFileName()'; throw 'Subclasses of AbstractUnarchiver must overload getScriptFileName()';
}; }
/** /**
* Adds an event listener for UnarchiveEvents. * Adds an event listener for UnarchiveEvents.
* *
* @param {string} Event type. * @param {string} Event type.
* @param {function} An event handler function. * @param {function} An event handler function.
*/ */
bitjs.archive.Unarchiver.prototype.addEventListener = function(type, listener) { addEventListener(type, listener) {
if (type in this.listeners_) { if (type in this.listeners_) {
if (this.listeners_[type].indexOf(listener) == -1) { if (this.listeners_[type].indexOf(listener) == -1) {
this.listeners_[type].push(listener); this.listeners_[type].push(listener);
} }
} }
}; }
/** /**
* Removes an event listener. * Removes an event listener.
* *
* @param {string} Event type. * @param {string} Event type.
* @param {EventListener|function} An event listener or handler function. * @param {EventListener|function} An event listener or handler function.
*/ */
bitjs.archive.Unarchiver.prototype.removeEventListener = function(type, listener) { removeEventListener(type, listener) {
if (type in this.listeners_) { if (type in this.listeners_) {
const 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);
} }
} }
}; }
/** /**
* Receive an event and pass it to the listener functions. * Receive an event and pass it to the listener functions.
* *
* @param {bitjs.archive.UnarchiveEvent} e * @param {bitjs.archive.UnarchiveEvent} e
* @private * @private
*/ */
bitjs.archive.Unarchiver.prototype.handleWorkerEvent_ = function(e) { handleWorkerEvent_(e) {
if ((e instanceof bitjs.archive.UnarchiveEvent || e.type) && if ((e instanceof bitjs.archive.UnarchiveEvent || e.type) &&
this.listeners_[e.type] instanceof Array) { this.listeners_[e.type] instanceof Array) {
this.listeners_[e.type].forEach(function (listener) { listener(e) }); this.listeners_[e.type].forEach(function (listener) { listener(e) });
@ -276,12 +243,12 @@ bitjs.archive.Unarchiver.prototype.handleWorkerEvent_ = function(e) {
} else { } else {
console.log(e); console.log(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() { start() {
const me = this; const me = this;
const scriptFileName = this.pathToBitJS_ + this.getScriptFileName(); const scriptFileName = this.pathToBitJS_ + this.getScriptFileName();
if (scriptFileName) { if (scriptFileName) {
@ -305,50 +272,54 @@ bitjs.archive.Unarchiver.prototype.handleWorkerEvent_ = function(e) {
this.worker_.postMessage({file: this.ab}); this.worker_.postMessage({file: this.ab});
} }
}; }
/** /**
* Terminates the Web Worker for this Unarchiver and returns immediately. * Terminates the Web Worker for this Unarchiver and returns immediately.
*/ */
bitjs.archive.Unarchiver.prototype.stop = function() { stop() {
if (this.worker_) { if (this.worker_) {
this.worker_.terminate(); this.worker_.terminate();
} }
}; }
}
/** /**
* Unzipper * Unzipper
* @extends {bitjs.archive.Unarchiver}
* @constructor
*/ */
bitjs.archive.Unzipper = function(arrayBuffer, opt_pathToBitJS) { bitjs.archive.Unzipper = class extends bitjs.archive.Unarchiver {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); constructor(arrayBuffer, opt_pathToBitJS) {
}; super(arrayBuffer, opt_pathToBitJS);
bitjs.inherits(bitjs.archive.Unzipper, bitjs.archive.Unarchiver); }
bitjs.archive.Unzipper.prototype.getScriptFileName = function() { return 'archive/unzip.js' };
getScriptFileName() { return 'archive/unzip.js'; }
}
/** /**
* Unrarrer * Unrarrer
* @extends {bitjs.archive.Unarchiver}
* @constructor
*/ */
bitjs.archive.Unrarrer = function(arrayBuffer, opt_pathToBitJS) { bitjs.archive.Unrarrer = class extends bitjs.archive.Unarchiver {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); constructor(arrayBuffer, opt_pathToBitJS) {
}; super(arrayBuffer, opt_pathToBitJS);
bitjs.inherits(bitjs.archive.Unrarrer, bitjs.archive.Unarchiver); }
bitjs.archive.Unrarrer.prototype.getScriptFileName = function() { return 'archive/unrar.js' };
getScriptFileName() { return 'archive/unrar.js'; }
}
/** /**
* Untarrer * Untarrer
* @extends {bitjs.archive.Unarchiver} * @extends {bitjs.archive.Unarchiver}
* @constructor * @constructor
*/ */
bitjs.archive.Untarrer = function(arrayBuffer, opt_pathToBitJS) { bitjs.archive.Untarrer = class extends bitjs.archive.Unarchiver {
bitjs.base(this, arrayBuffer, opt_pathToBitJS); constructor(arrayBuffer, opt_pathToBitJS) {
}; super(arrayBuffer, opt_pathToBitJS);
bitjs.inherits(bitjs.archive.Untarrer, bitjs.archive.Unarchiver); }
bitjs.archive.Untarrer.prototype.getScriptFileName = function() { return 'archive/untar.js' };
getScriptFileName() { 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
@ -371,5 +342,3 @@ bitjs.archive.GetUnarchiver = function(ab, opt_pathToBitJS) {
} }
return unarchiver; return unarchiver;
}; };
})();

View file

@ -201,10 +201,9 @@ function getDebugString(obj, val) {
} }
/** /**
* @struct
* @constructor
*/ */
const VM_PreparedOperand = function() { class VM_PreparedOperand {
constructor() {
/** @type {VM_OpType} */ /** @type {VM_OpType} */
this.Type; this.Type;
@ -217,10 +216,10 @@ const VM_PreparedOperand = function() {
// TODO: In C++ this is a uint* // TODO: In C++ this is a uint*
/** @type {Array<number>} */ /** @type {Array<number>} */
this.Addr = null; this.Addr = null;
}; };
/** @return {string} */ /** @return {string} */
VM_PreparedOperand.prototype.toString = function() { toString() {
if (this.Type === null) { if (this.Type === null) {
return 'Error: Type was null in VM_PreparedOperand'; return 'Error: Type was null in VM_PreparedOperand';
} }
@ -229,13 +228,13 @@ VM_PreparedOperand.prototype.toString = function() {
+ ', Data: ' + this.Data + ', Data: ' + this.Data
+ ', Base: ' + this.Base + ', Base: ' + this.Base
+ ' }'; + ' }';
}; }
}
/** /**
* @struct
* @constructor
*/ */
const VM_PreparedCommand = function() { class VM_PreparedCommand {
constructor() {
/** @type {VM_Commands} */ /** @type {VM_Commands} */
this.OpCode; this.OpCode;
@ -247,10 +246,10 @@ const VM_PreparedCommand = function() {
/** @type {VM_PreparedOperand} */ /** @type {VM_PreparedOperand} */
this.Op2 = new VM_PreparedOperand(); this.Op2 = new VM_PreparedOperand();
}; }
/** @return {string} */ /** @return {string} */
VM_PreparedCommand.prototype.toString = function(indent) { toString(indent) {
if (this.OpCode === null) { if (this.OpCode === null) {
return 'Error: OpCode was null in VM_PreparedCommand'; return 'Error: OpCode was null in VM_PreparedCommand';
} }
@ -261,13 +260,13 @@ VM_PreparedCommand.prototype.toString = function(indent) {
+ indent + ' Op1: ' + this.Op1.toString() + ',\n' + indent + ' Op1: ' + this.Op1.toString() + ',\n'
+ indent + ' Op2: ' + this.Op2.toString() + ',\n' + indent + ' Op2: ' + this.Op2.toString() + ',\n'
+ indent + '}'; + indent + '}';
}; }
}
/** /**
* @struct
* @constructor
*/ */
const VM_PreparedProgram = function() { class VM_PreparedProgram {
constructor() {
/** @type {Array<VM_PreparedCommand>} */ /** @type {Array<VM_PreparedCommand>} */
this.Cmd = []; this.Cmd = [];
@ -288,10 +287,10 @@ const VM_PreparedProgram = function() {
* @type {Uint8Array} * @type {Uint8Array}
*/ */
this.FilteredData = null; this.FilteredData = null;
}; }
/** @return {string} */ /** @return {string} */
VM_PreparedProgram.prototype.toString = function() { toString() {
let s = '{\n Cmd: [\n'; let s = '{\n Cmd: [\n';
for (let 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';
@ -300,13 +299,13 @@ VM_PreparedProgram.prototype.toString = function() {
// TODO: Dump GlobalData, StaticData, InitR? // TODO: Dump GlobalData, StaticData, InitR?
s += ' }\n'; s += ' }\n';
return s; return s;
}; }
}
/** /**
* @struct
* @constructor
*/ */
const UnpackFilter = function() { class UnpackFilter {
constructor() {
/** @type {number} */ /** @type {number} */
this.BlockStart = 0; this.BlockStart = 0;
@ -326,7 +325,8 @@ const UnpackFilter = function() {
/** @type {VM_PreparedProgram} */ /** @type {VM_PreparedProgram} */
this.Prg = new VM_PreparedProgram(); this.Prg = new VM_PreparedProgram();
}; }
}
const VMCF_OP0 = 0; const VMCF_OP0 = 0;
const VMCF_OP1 = 1; const VMCF_OP1 = 1;
@ -383,13 +383,14 @@ const VM_CmdFlags = [
/** /**
*/
class StandardFilterSignature {
/**
* @param {number} length * @param {number} length
* @param {number} crc * @param {number} crc
* @param {VM_StandardFilters} type * @param {VM_StandardFilters} type
* @struct
* @constructor
*/ */
const StandardFilterSignature = function(length, crc, type) { constructor(length, crc, type) {
/** @type {number} */ /** @type {number} */
this.Length = length; this.Length = length;
@ -398,7 +399,8 @@ const StandardFilterSignature = function(length, crc, type) {
/** @type {VM_StandardFilters} */ /** @type {VM_StandardFilters} */
this.Type = type; this.Type = type;
}; }
}
/** /**
* @type {Array<StandardFilterSignature>} * @type {Array<StandardFilterSignature>}
@ -416,7 +418,8 @@ const StdList = [
/** /**
* @constructor * @constructor
*/ */
const RarVM = function() { class RarVM {
constructor() {
/** @private {Uint8Array} */ /** @private {Uint8Array} */
this.mem_ = null; this.mem_ = null;
@ -425,22 +428,22 @@ const RarVM = function() {
/** @private {number} */ /** @private {number} */
this.flags_ = 0; this.flags_ = 0;
}; }
/** /**
* Initializes the memory of the VM. * Initializes the memory of the VM.
*/ */
RarVM.prototype.init = function() { init() {
if (!this.mem_) { if (!this.mem_) {
this.mem_ = new Uint8Array(VM_MEMSIZE); this.mem_ = new Uint8Array(VM_MEMSIZE);
} }
}; }
/** /**
* @param {Uint8Array} code * @param {Uint8Array} code
* @return {VM_StandardFilters} * @return {VM_StandardFilters}
*/ */
RarVM.prototype.isStandardFilter = function(code) { isStandardFilter(code) {
const codeCRC = (CRC(0xffffffff, code, code.length) ^ 0xffffffff) >>> 0; const codeCRC = (CRC(0xffffffff, code, code.length) ^ 0xffffffff) >>> 0;
for (let 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)
@ -448,14 +451,14 @@ RarVM.prototype.isStandardFilter = function(code) {
} }
return VM_StandardFilters.VMSF_NONE; return VM_StandardFilters.VMSF_NONE;
}; }
/** /**
* @param {VM_PreparedOperand} op * @param {VM_PreparedOperand} op
* @param {boolean} byteMode * @param {boolean} byteMode
* @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) { decodeArg(op, byteMode, bstream) {
const 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])
@ -494,12 +497,12 @@ RarVM.prototype.decodeArg = function(op, byteMode, bstream) {
} }
} }
} }
}; }
/** /**
* @param {VM_PreparedProgram} prg * @param {VM_PreparedProgram} prg
*/ */
RarVM.prototype.execute = function(prg) { execute(prg) {
this.R_.set(prg.InitR); this.R_.set(prg.InitR);
const globalSize = Math.min(prg.GlobalData.length, VM_GLOBALMEMSIZE); const globalSize = Math.min(prg.GlobalData.length, VM_GLOBALMEMSIZE);
@ -537,13 +540,13 @@ RarVM.prototype.execute = function(prg) {
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));
} }
}; }
/** /**
* @param {Array<VM_PreparedCommand>} preparedCodes * @param {Array<VM_PreparedCommand>} preparedCodes
* @return {boolean} * @return {boolean}
*/ */
RarVM.prototype.executeCode = function(preparedCodes) { executeCode(preparedCodes) {
let codeIndex = 0; let codeIndex = 0;
let 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
@ -569,12 +572,12 @@ RarVM.prototype.executeCode = function(preparedCodes) {
codeIndex++; codeIndex++;
cmd = preparedCodes[codeIndex]; cmd = preparedCodes[codeIndex];
} }
}; }
/** /**
* @param {number} filterType * @param {number} filterType
*/ */
RarVM.prototype.executeStandardFilter = function(filterType) { executeStandardFilter(filterType) {
switch (filterType) { switch (filterType) {
case VM_StandardFilters.VMSF_DELTA: case VM_StandardFilters.VMSF_DELTA:
const dataSize = this.R_[4]; const dataSize = this.R_[4];
@ -606,13 +609,13 @@ RarVM.prototype.executeStandardFilter = function(filterType) {
console.error('RarVM Standard Filter not supported: ' + getDebugString(VM_StandardFilters, filterType)); console.error('RarVM Standard Filter not supported: ' + getDebugString(VM_StandardFilters, filterType));
break; break;
} }
}; }
/** /**
* @param {Uint8Array} code * @param {Uint8Array} code
* @param {VM_PreparedProgram} prg * @param {VM_PreparedProgram} prg
*/ */
RarVM.prototype.prepare = function(code, prg) { prepare(code, prg) {
let codeSize = code.length; let codeSize = code.length;
//InitBitInput(); //InitBitInput();
@ -739,50 +742,50 @@ RarVM.prototype.prepare = function(code, prg) {
} }
} }
/* /*
#ifdef VM_OPTIMIZE #ifdef VM_OPTIMIZE
if (CodeSize!=0) if (CodeSize!=0)
Optimize(Prg); Optimize(Prg);
#endif #endif
*/ */
}; }
/** /**
* @param {Uint8Array} arr The byte array to set a value in. * @param {Uint8Array} arr The byte array to set a value in.
* @param {number} value The unsigned 32-bit value to set. * @param {number} value The unsigned 32-bit value to set.
* @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) { setLowEndianValue(arr, value, offset) {
const 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;
arr[i + 3] = (value >>> 24) & 0xff; arr[i + 3] = (value >>> 24) & 0xff;
}; }
/** /**
* Sets a number of bytes of the VM memory at the given position from a * Sets a number of bytes of the VM memory at the given position from a
* source buffer of bytes. * source buffer of bytes.
* @param {number} pos The position in the VM memory to start writing to. * @param {number} pos The position in the VM memory to start writing to.
* @param {Uint8Array} buffer The source buffer of bytes. * @param {Uint8Array} buffer The source buffer of bytes.
* @param {number} dataSize The number of bytes to set. * @param {number} dataSize The number of bytes to set.
*/ */
RarVM.prototype.setMemory = function(pos, buffer, dataSize) { setMemory(pos, buffer, dataSize) {
if (pos < VM_MEMSIZE) { if (pos < VM_MEMSIZE) {
const numBytes = Math.min(dataSize, VM_MEMSIZE - pos); const numBytes = Math.min(dataSize, VM_MEMSIZE - pos);
for (let i = 0; i < numBytes; ++i) { for (let i = 0; i < numBytes; ++i) {
this.mem_[pos + i] = buffer[i]; this.mem_[pos + i] = buffer[i];
} }
} }
}; }
/** /**
* Static function that reads in the next set of bits for the VM * Static function that reads in the next set of bits for the VM
* (might return 4, 8, 16 or 32 bits). * (might return 4, 8, 16 or 32 bits).
* @param {bitjs.io.BitStream} bstream A RTL bit stream. * @param {bitjs.io.BitStream} bstream A RTL bit stream.
* @return {number} The value of the bits read. * @return {number} The value of the bits read.
*/ */
RarVM.readData = function(bstream) { static readData(bstream) {
// Read in the first 2 bits. // Read in the first 2 bits.
const flags = bstream.readBits(2); const flags = bstream.readBits(2);
switch (flags) { // Data&0xc000 switch (flags) { // Data&0xc000
@ -812,6 +815,7 @@ RarVM.readData = function(bstream) {
default: default:
return (bstream.readBits(16) << 16) | bstream.readBits(16); return (bstream.readBits(16) << 16) | bstream.readBits(16);
} }
}; }
}
// ============================================================================================== // // ============================================================================================== //

View file

@ -63,10 +63,12 @@ const ENDARC_HEAD = 0x7b;
// ============================================================================================== // // ============================================================================================== //
/** /**
* @param {bitjs.io.BitStream} bstream
* @constructor
*/ */
const RarVolumeHeader = function(bstream) { class RarVolumeHeader {
/**
* @param {bitjs.io.BitStream} bstream
*/
constructor(bstream) {
const headPos = bstream.bytePtr; const headPos = bstream.bytePtr;
// byte 1,2 // byte 1,2
info("Rar Volume Header @"+bstream.bytePtr); info("Rar Volume Header @"+bstream.bytePtr);
@ -198,7 +200,6 @@ const RarVolumeHeader = function(bstream) {
info("Found a LHD_COMMENT"); info("Found a LHD_COMMENT");
} }
while (headPos + this.headSize > bstream.bytePtr) { while (headPos + this.headSize > bstream.bytePtr) {
bstream.readBits(1); bstream.readBits(1);
} }
@ -212,7 +213,8 @@ const RarVolumeHeader = function(bstream) {
bstream.readBytes(this.headSize - 7); bstream.readBytes(this.headSize - 7);
break; break;
} }
}; }
}
const BLOCK_LZ = 0; const BLOCK_LZ = 0;
const BLOCK_PPM = 1; const BLOCK_PPM = 1;
@ -1237,8 +1239,13 @@ function unpack(v) {
return rBuffer.data; return rBuffer.data;
} }
// bstream is a bit stream /**
const RarLocalFile = function(bstream) { */
class RarLocalFile {
/**
* @param {bitjs.io.BitStream} bstream
*/
constructor(bstream) {
this.header = new RarVolumeHeader(bstream); this.header = new RarVolumeHeader(bstream);
this.filename = this.header.filename; this.filename = this.header.filename;
@ -1254,9 +1261,9 @@ const RarLocalFile = function(bstream) {
this.isValid = true; this.isValid = true;
} }
} }
}; }
RarLocalFile.prototype.unrar = function() { unrar() {
if (!this.header.flags.LHD_SPLIT_BEFORE) { if (!this.header.flags.LHD_SPLIT_BEFORE) {
// unstore file // unstore file
if (this.header.method == 0x30) { if (this.header.method == 0x30) {
@ -1276,6 +1283,7 @@ RarLocalFile.prototype.unrar = function() {
this.fileData = unpack(this); this.fileData = unpack(this);
} }
} }
}
} }
const unrar = function(arrayBuffer) { const unrar = function(arrayBuffer) {

View file

@ -46,8 +46,9 @@ const readCleanString = function(bstr, numBytes) {
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 class TarLocalFile {
const TarLocalFile = function(bstream) { // takes a ByteStream and parses out the local file information
constructor(bstream) {
this.isValid = false; this.isValid = false;
// Read in the header block // Read in the header block
@ -105,7 +106,8 @@ const TarLocalFile = function(bstream) {
} else if (this.typeflag == 5) { } else if (this.typeflag == 5) {
info(" This is a directory.") info(" This is a directory.")
} }
}; }
}
// Takes an ArrayBuffer of a tar file in // Takes an ArrayBuffer of a tar file in
// returns null on error // returns null on error

View file

@ -50,8 +50,16 @@ const zDigitalSignatureSignature = 0x05054b50;
const zEndOfCentralDirSignature = 0x06064b50; const zEndOfCentralDirSignature = 0x06064b50;
const zEndOfCentralDirLocatorSignature = 0x07064b50; const zEndOfCentralDirLocatorSignature = 0x07064b50;
// takes a ByteStream and parses out the local file information // mask for getting the Nth bit (zero-based)
const ZipLocalFile = function(bstream) { const BIT = [ 0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000];
class ZipLocalFile {
// takes a ByteStream and parses out the local file information
constructor(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;
} }
@ -103,15 +111,15 @@ const ZipLocalFile = function(bstream) {
// "This descriptor exists only if bit 3 of the general purpose bit flag is set" // "This descriptor exists only if bit 3 of the general purpose bit flag is set"
// But how do you figure out how big the file data is if you don't know the compressedSize // But how do you figure out how big the file data is if you don't know the compressedSize
// from the header?!? // from the header?!?
if ((this.generalPurpose & bitjs.BIT[3]) != 0) { if ((this.generalPurpose & BIT[3]) != 0) {
this.crc32 = bstream.readNumber(4); this.crc32 = bstream.readNumber(4);
this.compressedSize = bstream.readNumber(4); this.compressedSize = bstream.readNumber(4);
this.uncompressedSize = bstream.readNumber(4); this.uncompressedSize = bstream.readNumber(4);
} }
}; }
// determine what kind of compressed data we have and decompress // determine what kind of compressed data we have and decompress
ZipLocalFile.prototype.unzip = function() { unzip() {
// 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)");
@ -127,8 +135,8 @@ ZipLocalFile.prototype.unzip = function() {
err("UNSUPPORTED VERSION/FORMAT: ZIP v" + this.version + ", compression method=" + this.compressionMethod + ": " + this.filename + " (" + this.compressedSize + " bytes)"); err("UNSUPPORTED VERSION/FORMAT: ZIP v" + this.version + ", compression method=" + this.compressionMethod + ": " + this.filename + " (" + this.compressedSize + " bytes)");
this.fileData = null; this.fileData = null;
} }
}; }
}
// Takes an ArrayBuffer of a zip file in // Takes an ArrayBuffer of a zip file in
// returns null on error // returns null on error
@ -374,10 +382,11 @@ function decodeSymbol(bstream, hcTable) {
const 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)
---- ---- ------ ---- ---- ------- ---- ---- ------- ---- ---- ------ ---- ---- ------- ---- ---- -------
257 0 3 267 1 15,16 277 4 67-82 257 0 3 267 1 15,16 277 4 67-82
258 0 4 268 1 17,18 278 4 83-98 258 0 4 268 1 17,18 278 4 83-98
259 0 5 269 2 19-22 279 4 99-114 259 0 5 269 2 19-22 279 4 99-114
@ -388,7 +397,7 @@ const CodeLengthCodeOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13,
264 0 10 274 3 43-50 284 5 227-257 264 0 10 274 3 43-50 284 5 227-257
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
*/ */
const 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],
@ -399,7 +408,8 @@ const LengthLookupTable = [
[5,131], [5,163], [5,195], [5,227], [5,131], [5,163], [5,195], [5,227],
[0,258] [0,258]
]; ];
/*
/*
Extra Extra Extra Extra Extra Extra
Code Bits Dist Code Bits Dist Code Bits Distance Code Bits Dist Code Bits Dist Code Bits Distance
---- ---- ---- ---- ---- ------ ---- ---- -------- ---- ---- ---- ---- ---- ------ ---- ---- --------
@ -413,7 +423,7 @@ const LengthLookupTable = [
7 2 13-16 17 7 385-512 27 12 12289-16384 7 2 13-16 17 7 385-512 27 12 12289-16384
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
*/ */
const 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],

View file

@ -12,28 +12,19 @@
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() {
// mask for getting the Nth bit (zero-based)
bitjs.BIT = [ 0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800,
0x1000, 0x2000, 0x4000, 0x8000];
// mask for getting N number of bits (0-8)
const BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
/** /**
* This bit stream peeks and consumes bits out of a binary stream. * This bit stream peeks and consumes bits out of a binary stream.
* */
bitjs.io.BitStream = class {
/**
* @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array. * @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array.
* @param {boolean} rtl Whether the stream reads bits from the byte starting * @param {boolean} rtl Whether the stream reads bits from the byte starting
* from bit 7 to 0 (true) or bit 0 to 7 (false). * from bit 7 to 0 (true) or bit 0 to 7 (false).
* @param {Number} opt_offset The offset into the ArrayBuffer * @param {Number} opt_offset The offset into the ArrayBuffer
* @param {Number} opt_length The length of this BitStream * @param {Number} opt_length The length of this BitStream
*/ */
bitjs.io.BitStream = function(ab, rtl, opt_offset, opt_length) { constructor(ab, rtl, opt_offset, opt_length) {
if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") { if (!ab || !ab.toString || ab.toString() !== "[object ArrayBuffer]") {
throw "Error! BitArray constructed with an invalid ArrayBuffer object"; throw "Error! BitArray constructed with an invalid ArrayBuffer object";
} }
@ -44,10 +35,9 @@ bitjs.io.BitStream = function(ab, rtl, opt_offset, opt_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)
this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr; this.peekBits = rtl ? this.peekBits_rtl : this.peekBits_ltr;
}; }
/**
/**
* byte0 byte1 byte2 byte3 * byte0 byte1 byte2 byte3
* 7......0 | 7......0 | 7......0 | 7......0 * 7......0 | 7......0 | 7......0 | 7......0
* *
@ -57,7 +47,7 @@ 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, opt_movePointers) { peekBits_ltr(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -82,7 +72,7 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, opt_movePointers) {
const numBitsLeftInThisByte = (8 - bitPtr); const numBitsLeftInThisByte = (8 - bitPtr);
if (n >= numBitsLeftInThisByte) { if (n >= numBitsLeftInThisByte) {
const mask = (BITMASK[numBitsLeftInThisByte] << bitPtr); const mask = (bitjs.io.BitStream.BITMASK[numBitsLeftInThisByte] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn); result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bytePtr++; bytePtr++;
@ -91,7 +81,7 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, opt_movePointers) {
n -= numBitsLeftInThisByte; n -= numBitsLeftInThisByte;
} }
else { else {
const mask = (BITMASK[n] << bitPtr); const mask = (bitjs.io.BitStream.BITMASK[n] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn); result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
bitPtr += n; bitPtr += n;
@ -106,10 +96,9 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, opt_movePointers) {
} }
return result; return result;
}; }
/**
/**
* byte0 byte1 byte2 byte3 * byte0 byte1 byte2 byte3
* 7......0 | 7......0 | 7......0 | 7......0 * 7......0 | 7......0 | 7......0 | 7......0
* *
@ -119,7 +108,7 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, opt_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, opt_movePointers) { peekBits_rtl(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -145,14 +134,14 @@ bitjs.io.BitStream.prototype.peekBits_rtl = function(n, opt_movePointers) {
const numBitsLeftInThisByte = (8 - bitPtr); const numBitsLeftInThisByte = (8 - bitPtr);
if (n >= numBitsLeftInThisByte) { if (n >= numBitsLeftInThisByte) {
result <<= numBitsLeftInThisByte; result <<= numBitsLeftInThisByte;
result |= (BITMASK[numBitsLeftInThisByte] & bytes[bytePtr]); result |= (bitjs.io.BitStream.BITMASK[numBitsLeftInThisByte] & bytes[bytePtr]);
bytePtr++; bytePtr++;
bitPtr = 0; bitPtr = 0;
n -= numBitsLeftInThisByte; n -= numBitsLeftInThisByte;
} }
else { else {
result <<= n; result <<= n;
result |= ((bytes[bytePtr] & (BITMASK[n] << (8 - n - bitPtr))) >> (8 - n - bitPtr)); result |= ((bytes[bytePtr] & (bitjs.io.BitStream.BITMASK[n] << (8 - n - bitPtr))) >> (8 - n - bitPtr));
bitPtr += n; bitPtr += n;
n = 0; n = 0;
@ -165,33 +154,30 @@ bitjs.io.BitStream.prototype.peekBits_rtl = function(n, opt_movePointers) {
} }
return result; return result;
}; }
/**
/**
* Peek at 16 bits from current position in the buffer. * Peek at 16 bits from current position in the buffer.
* Bit at (bytePtr,bitPtr) has the highest position in returning data. * Bit at (bytePtr,bitPtr) has the highest position in returning data.
* Taken from getbits.hpp in unrar. * Taken from getbits.hpp in unrar.
* TODO: Move this out of BitStream and into unrar. * TODO: Move this out of BitStream and into unrar.
*/ */
bitjs.io.BitStream.prototype.getBits = function() { getBits() {
return (((((this.bytes[this.bytePtr] & 0xff) << 16) + return (((((this.bytes[this.bytePtr] & 0xff) << 16) +
((this.bytes[this.bytePtr+1] & 0xff) << 8) + ((this.bytes[this.bytePtr+1] & 0xff) << 8) +
((this.bytes[this.bytePtr+2] & 0xff))) >>> (8-this.bitPtr)) & 0xffff); ((this.bytes[this.bytePtr+2] & 0xff))) >>> (8-this.bitPtr)) & 0xffff);
}; }
/**
/**
* Reads n bits out of the stream, consuming them (moving the bit pointer). * Reads n bits out of the stream, consuming them (moving the bit pointer).
* @param {number} n The number of bits to read. * @param {number} n The number of bits to read.
* @return {number} The read bits, as an unsigned number. * @return {number} The read bits, as an unsigned number.
*/ */
bitjs.io.BitStream.prototype.readBits = function(n) { readBits(n) {
return this.peekBits(n, true); return this.peekBits(n, true);
}; }
/**
/**
* This returns n bytes as a sub-array, advancing the pointer if movePointers * This returns n bytes as a sub-array, advancing the pointer if movePointers
* is true. Only use this for uncompressed blocks as this throws away remaining * is true. Only use this for uncompressed blocks as this throws away remaining
* bits in the current byte. * bits in the current byte.
@ -199,7 +185,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, opt_movePointers) { peekBytes(n, opt_movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -221,15 +207,17 @@ bitjs.io.BitStream.prototype.peekBytes = function(n, opt_movePointers) {
} }
return result; return result;
}; }
/**
/**
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @return {Uint8Array} The subarray. * @return {Uint8Array} The subarray.
*/ */
bitjs.io.BitStream.prototype.readBytes = function(n) { readBytes(n) {
return this.peekBytes(n, true); return this.peekBytes(n, true);
}; }
}
// mask for getting N number of bits (0-8)
bitjs.io.BitStream.BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
})();

View file

@ -12,49 +12,47 @@
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() {
/** /**
* A write-only Byte buffer which uses a Uint8 Typed Array as a backing store. * A write-only Byte buffer which uses a Uint8 Typed Array as a backing store.
* @param {number} numBytes The number of bytes to allocate.
* @constructor
*/ */
bitjs.io.ByteBuffer = function(numBytes) { bitjs.io.ByteBuffer = class {
/**
* @param {number} numBytes The number of bytes to allocate.
*/
constructor(numBytes) {
if (typeof numBytes != typeof 1 || numBytes <= 0) { if (typeof numBytes != typeof 1 || numBytes <= 0) {
throw "Error! ByteBuffer initialized with '" + numBytes + "'"; throw "Error! ByteBuffer initialized with '" + numBytes + "'";
} }
this.data = new Uint8Array(numBytes); this.data = new Uint8Array(numBytes);
this.ptr = 0; this.ptr = 0;
}; }
/** /**
* @param {number} b The byte to insert. * @param {number} b The byte to insert.
*/ */
bitjs.io.ByteBuffer.prototype.insertByte = function(b) { insertByte(b) {
// TODO: throw if byte is invalid? // TODO: throw if byte is invalid?
this.data[this.ptr++] = b; this.data[this.ptr++] = b;
}; }
/**
/**
* @param {Array.<number>|Uint8Array|Int8Array} bytes The bytes to insert. * @param {Array.<number>|Uint8Array|Int8Array} bytes The bytes to insert.
*/ */
bitjs.io.ByteBuffer.prototype.insertBytes = function(bytes) { insertBytes(bytes) {
// TODO: throw if bytes is invalid? // TODO: throw if bytes is invalid?
this.data.set(bytes, this.ptr); this.data.set(bytes, this.ptr);
this.ptr += bytes.length; this.ptr += bytes.length;
}; }
/**
/**
* Writes an unsigned number into the next n bytes. If the number is too large * Writes an unsigned number into the next n bytes. If the number is too large
* to fit into n bytes or is negative, an error is thrown. * to fit into n bytes or is negative, an error is thrown.
* @param {number} num The unsigned number to write. * @param {number} num The unsigned number to write.
* @param {number} numBytes The number of bytes to write the number into. * @param {number} numBytes The number of bytes to write the number into.
*/ */
bitjs.io.ByteBuffer.prototype.writeNumber = function(num, numBytes) { writeNumber(num, numBytes) {
if (numBytes < 1) { if (numBytes < 1) {
throw 'Trying to write into too few bytes: ' + numBytes; throw 'Trying to write into too few bytes: ' + numBytes;
} }
@ -75,16 +73,15 @@ bitjs.io.ByteBuffer.prototype.writeNumber = function(num, numBytes) {
} }
this.insertBytes(bytes); this.insertBytes(bytes);
}; }
/**
/**
* Writes a signed number into the next n bytes. If the number is too large * Writes a signed number into the next n bytes. If the number is too large
* to fit into n bytes, an error is thrown. * to fit into n bytes, an error is thrown.
* @param {number} num The signed number to write. * @param {number} num The signed number to write.
* @param {number} numBytes The number of bytes to write the number into. * @param {number} numBytes The number of bytes to write the number into.
*/ */
bitjs.io.ByteBuffer.prototype.writeSignedNumber = function(num, numBytes) { writeSignedNumber(num, numBytes) {
if (numBytes < 1) { if (numBytes < 1) {
throw 'Trying to write into too few bytes: ' + numBytes; throw 'Trying to write into too few bytes: ' + numBytes;
} }
@ -103,13 +100,12 @@ bitjs.io.ByteBuffer.prototype.writeSignedNumber = function(num, numBytes) {
} }
this.insertBytes(bytes); this.insertBytes(bytes);
}; }
/**
/**
* @param {string} str The ASCII string to write. * @param {string} str The ASCII string to write.
*/ */
bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) { writeASCIIString(str) {
for (let i = 0; i < str.length; ++i) { for (let i = 0; i < str.length; ++i) {
const curByte = str.charCodeAt(i); const curByte = str.charCodeAt(i);
if (curByte < 0 || curByte > 255) { if (curByte < 0 || curByte > 255) {
@ -117,6 +113,5 @@ bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) {
} }
this.insertByte(curByte); this.insertByte(curByte);
} }
}; };
}
})();

View file

@ -12,34 +12,33 @@
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() {
/** /**
* This object allows you to peek and consume bytes as numbers and strings * This object allows you to peek and consume bytes as numbers and strings
* out of an ArrayBuffer. In this buffer, everything must be byte-aligned. * out of an ArrayBuffer. In this buffer, everything must be byte-aligned.
* */
bitjs.io.ByteStream = class {
/**
* @param {ArrayBuffer} ab The ArrayBuffer object. * @param {ArrayBuffer} ab The ArrayBuffer object.
* @param {number=} opt_offset The offset into the ArrayBuffer * @param {number=} opt_offset The offset into the ArrayBuffer
* @param {number=} opt_length The length of this BitStream * @param {number=} opt_length The length of this BitStream
* @constructor
*/ */
bitjs.io.ByteStream = function(ab, opt_offset, opt_length) { constructor(ab, opt_offset, opt_length) {
const offset = opt_offset || 0; const offset = opt_offset || 0;
const 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;
}; }
/** /**
* Peeks at the next n bytes as an unsigned number but does not advance the * Peeks at the next n bytes as an unsigned number but does not advance the
* pointer * pointer
* TODO: This apparently cannot read more than 4 bytes as a number? * TODO: This apparently cannot read more than 4 bytes as a number?
* @param {number} n The number of bytes to peek at. * @param {number} n The number of bytes to peek at.
* @return {number} The n bytes interpreted as an unsigned number. * @return {number} The n bytes interpreted as an unsigned number.
*/ */
bitjs.io.ByteStream.prototype.peekNumber = function(n) { peekNumber(n) {
// TODO: return error if n would go past the end of the stream? // TODO: return error if n would go past the end of the stream?
if (n <= 0 || typeof n != typeof 1) if (n <= 0 || typeof n != typeof 1)
return -1; return -1;
@ -53,29 +52,29 @@ bitjs.io.ByteStream.prototype.peekNumber = function(n) {
--curByte; --curByte;
} }
return result; return result;
}; }
/** /**
* Returns the next n bytes as an unsigned number (or -1 on error) * Returns the next n bytes as an unsigned number (or -1 on error)
* and advances the stream pointer n bytes. * and advances the stream pointer n bytes.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @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) { readNumber(n) {
const num = this.peekNumber( n ); const num = this.peekNumber( n );
this.ptr += n; this.ptr += n;
return num; return num;
}; }
/** /**
* Returns the next n bytes as a signed number but does not advance the * Returns the next n bytes as a signed number but does not advance the
* pointer. * pointer.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @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) { peekSignedNumber(n) {
let num = this.peekNumber(n); let num = this.peekNumber(n);
const HALF = Math.pow(2, (n * 8) - 1); const HALF = Math.pow(2, (n * 8) - 1);
const FULL = HALF * 2; const FULL = HALF * 2;
@ -83,29 +82,29 @@ bitjs.io.ByteStream.prototype.peekSignedNumber = function(n) {
if (num >= HALF) num -= FULL; if (num >= HALF) num -= FULL;
return num; return num;
}; }
/** /**
* Returns the next n bytes as a signed number and advances the stream pointer. * Returns the next n bytes as a signed number and advances the stream pointer.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @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) { readSignedNumber(n) {
const num = this.peekSignedNumber(n); const num = this.peekSignedNumber(n);
this.ptr += n; this.ptr += n;
return num; return num;
}; }
/** /**
* This returns n bytes as a sub-array, advancing the pointer if movePointers * This returns n bytes as a sub-array, advancing the pointer if movePointers
* is true. * is true.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @param {boolean} movePointers Whether to move the pointers. * @param {boolean} movePointers Whether to move the pointers.
* @return {Uint8Array} The subarray. * @return {Uint8Array} The subarray.
*/ */
bitjs.io.ByteStream.prototype.peekBytes = function(n, movePointers) { peekBytes(n, movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return null; return null;
} }
@ -117,25 +116,23 @@ bitjs.io.ByteStream.prototype.peekBytes = function(n, movePointers) {
} }
return result; return result;
}; }
/**
/**
* Reads the next n bytes as a sub-array. * Reads the next n bytes as a sub-array.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @return {Uint8Array} The subarray. * @return {Uint8Array} The subarray.
*/ */
bitjs.io.ByteStream.prototype.readBytes = function(n) { readBytes(n) {
return this.peekBytes(n, true); return this.peekBytes(n, true);
}; }
/**
/**
* Peeks at the next n bytes as a string but does not advance the pointer. * Peeks at the next n bytes as a string but does not advance the pointer.
* @param {number} n The number of bytes to peek at. * @param {number} n The number of bytes to peek at.
* @return {string} The next n bytes as a string. * @return {string} The next n bytes as a string.
*/ */
bitjs.io.ByteStream.prototype.peekString = function(n) { peekString(n) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return ""; return "";
} }
@ -145,20 +142,17 @@ bitjs.io.ByteStream.prototype.peekString = function(n) {
result += String.fromCharCode(this.bytes[p]); result += String.fromCharCode(this.bytes[p]);
} }
return result; return result;
}; }
/**
/**
* Returns the next n bytes as an ASCII string and advances the stream pointer * Returns the next n bytes as an ASCII string and advances the stream pointer
* n bytes. * n bytes.
* @param {number} n The number of bytes to read. * @param {number} n The number of bytes to read.
* @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) { readString(n) {
const strToReturn = this.peekString(n); const strToReturn = this.peekString(n);
this.ptr += n; this.ptr += n;
return strToReturn; return strToReturn;
}; }
}
})();