Beautify bitjs

pull/911/head
subdiox 6 years ago
parent 7982ed877c
commit 867aa2f0bd

@ -7,15 +7,14 @@
* *
* Copyright(c) 2011 Google Inc. * Copyright(c) 2011 Google Inc.
*/ */
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.archive = bitjs.archive || {}; bitjs.archive = bitjs.archive || {};
(function() { (function() {
// =========================================================================== // ===========================================================================
// 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; var 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.
@ -25,8 +24,7 @@ bitjs.base = function(me, opt_methodName, var_args) {
var args = Array.prototype.slice.call(arguments, 2); var args = Array.prototype.slice.call(arguments, 2);
var foundCaller = false; var foundCaller = false;
for (var ctor = me.constructor; for (var 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;
} else if (foundCaller) { } else if (foundCaller) {
@ -45,50 +43,50 @@ bitjs.base = function(me, opt_methodName, var_args) {
'goog.base called from a method of one name ' + 'goog.base called from a method of one name ' +
'to a method of a different name'); 'to a method of a different name');
} }
}; };
bitjs.inherits = function(childCtor, parentCtor) { bitjs.inherits = function(childCtor, parentCtor) {
/** @constructor */ /** @constructor */
function tempCtor() {}; function tempCtor() {};
tempCtor.prototype = parentCtor.prototype; tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor(); childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor; childCtor.prototype.constructor = childCtor;
}; };
// =========================================================================== // ===========================================================================
/** /**
* An unarchive event. * An unarchive event.
* *
* @param {string} type The event type. * @param {string} type The event type.
* @constructor * @constructor
*/ */
bitjs.archive.UnarchiveEvent = function(type) { bitjs.archive.UnarchiveEvent = function(type) {
/** /**
* The event type. * The event type.
* *
* @type {string} * @type {string}
*/ */
this.type = type; this.type = type;
}; };
/** /**
* The UnarchiveEvent types. * The UnarchiveEvent types.
*/ */
bitjs.archive.UnarchiveEvent.Type = { bitjs.archive.UnarchiveEvent.Type = {
START: 'start', START: 'start',
PROGRESS: 'progress', PROGRESS: 'progress',
EXTRACT: 'extract', EXTRACT: 'extract',
FINISH: 'finish', FINISH: 'finish',
INFO: 'info', INFO: 'info',
ERROR: 'error' ERROR: 'error'
}; };
/** /**
* Useful for passing info up to the client (for debugging). * Useful for passing info up to the client (for debugging).
* *
* @param {string} msg The info message. * @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveInfoEvent = function(msg) { bitjs.archive.UnarchiveInfoEvent = function(msg) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.INFO); bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.INFO);
/** /**
@ -97,15 +95,15 @@ bitjs.archive.UnarchiveInfoEvent = function(msg) {
* @type {string} * @type {string}
*/ */
this.msg = msg; this.msg = msg;
}; };
bitjs.inherits(bitjs.archive.UnarchiveInfoEvent, bitjs.archive.UnarchiveEvent); bitjs.inherits(bitjs.archive.UnarchiveInfoEvent, bitjs.archive.UnarchiveEvent);
/** /**
* An unrecoverable error has occured. * An unrecoverable error has occured.
* *
* @param {string} msg The error message. * @param {string} msg The error message.
*/ */
bitjs.archive.UnarchiveErrorEvent = function(msg) { bitjs.archive.UnarchiveErrorEvent = function(msg) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.ERROR); bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.ERROR);
/** /**
@ -114,33 +112,33 @@ bitjs.archive.UnarchiveErrorEvent = function(msg) {
* @type {string} * @type {string}
*/ */
this.msg = msg; this.msg = msg;
}; };
bitjs.inherits(bitjs.archive.UnarchiveErrorEvent, bitjs.archive.UnarchiveEvent); bitjs.inherits(bitjs.archive.UnarchiveErrorEvent, bitjs.archive.UnarchiveEvent);
/** /**
* Start event. * Start event.
* *
* @param {string} msg The info message. * @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveStartEvent = function() { bitjs.archive.UnarchiveStartEvent = function() {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.START); bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.START);
}; };
bitjs.inherits(bitjs.archive.UnarchiveStartEvent, bitjs.archive.UnarchiveEvent); bitjs.inherits(bitjs.archive.UnarchiveStartEvent, bitjs.archive.UnarchiveEvent);
/** /**
* Finish event. * Finish event.
* *
* @param {string} msg The info message. * @param {string} msg The info message.
*/ */
bitjs.archive.UnarchiveFinishEvent = function() { bitjs.archive.UnarchiveFinishEvent = function() {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.FINISH); bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.FINISH);
}; };
bitjs.inherits(bitjs.archive.UnarchiveFinishEvent, bitjs.archive.UnarchiveEvent); bitjs.inherits(bitjs.archive.UnarchiveFinishEvent, bitjs.archive.UnarchiveEvent);
/** /**
* Progress event. * Progress event.
*/ */
bitjs.archive.UnarchiveProgressEvent = function( bitjs.archive.UnarchiveProgressEvent = function(
currentFilename, currentFilename,
currentFileNumber, currentFileNumber,
currentBytesUnarchivedInFile, currentBytesUnarchivedInFile,
@ -155,10 +153,10 @@ 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); bitjs.inherits(bitjs.archive.UnarchiveProgressEvent, bitjs.archive.UnarchiveEvent);
/** /**
* All extracted files returned by an Unarchiver will implement * All extracted files returned by an Unarchiver will implement
* the following interface: * the following interface:
* *
@ -169,28 +167,28 @@ bitjs.inherits(bitjs.archive.UnarchiveProgressEvent, bitjs.archive.UnarchiveEven
* *
*/ */
/** /**
* Extract event. * Extract event.
*/ */
bitjs.archive.UnarchiveExtractEvent = function(unarchivedFile) { bitjs.archive.UnarchiveExtractEvent = function(unarchivedFile) {
bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.EXTRACT); bitjs.base(this, bitjs.archive.UnarchiveEvent.Type.EXTRACT);
/** /**
* @type {UnarchivedFile} * @type {UnarchivedFile}
*/ */
this.unarchivedFile = unarchivedFile; this.unarchivedFile = unarchivedFile;
}; };
bitjs.inherits(bitjs.archive.UnarchiveExtractEvent, bitjs.archive.UnarchiveEvent); bitjs.inherits(bitjs.archive.UnarchiveExtractEvent, bitjs.archive.UnarchiveEvent);
/** /**
* Base class for all Unarchivers. * Base class for all Unarchivers.
* *
* @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 * @constructor
*/ */
bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) { bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) {
/** /**
* The ArrayBuffer object. * The ArrayBuffer object.
* @type {ArrayBuffer} * @type {ArrayBuffer}
@ -213,72 +211,74 @@ bitjs.archive.Unarchiver = function(arrayBuffer, opt_pathToBitJS) {
for (var type in bitjs.archive.UnarchiveEvent.Type) { for (var 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; bitjs.archive.Unarchiver.prototype.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() { bitjs.archive.Unarchiver.prototype.getScriptFileName = function() {
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) { bitjs.archive.Unarchiver.prototype.addEventListener = function(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) { 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); var 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) { bitjs.archive.Unarchiver.prototype.handleWorkerEvent_ = function(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)
});
if (e.type == bitjs.archive.UnarchiveEvent.Type.FINISH) { if (e.type == bitjs.archive.UnarchiveEvent.Type.FINISH) {
this.worker_.terminate(); this.worker_.terminate();
} }
} 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() { bitjs.archive.Unarchiver.prototype.start = function() {
@ -303,61 +303,69 @@ 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() { bitjs.archive.Unarchiver.prototype.stop = function() {
if (this.worker_) { if (this.worker_) {
this.worker_.terminate(); this.worker_.terminate();
} }
}; };
/** /**
* Unzipper * Unzipper
* @extends {bitjs.archive.Unarchiver} * @extends {bitjs.archive.Unarchiver}
* @constructor * @constructor
*/ */
bitjs.archive.Unzipper = function(arrayBuffer, opt_pathToBitJS) { 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 'unzip.js'
};
/** /**
* Unrarrer * Unrarrer
* @extends {bitjs.archive.Unarchiver} * @extends {bitjs.archive.Unarchiver}
* @constructor * @constructor
*/ */
bitjs.archive.Unrarrer = function(arrayBuffer, opt_pathToBitJS) { 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 'unrar.js'
};
/** /**
* Untarrer * Untarrer
* @extends {bitjs.archive.Unarchiver} * @extends {bitjs.archive.Unarchiver}
* @constructor * @constructor
*/ */
bitjs.archive.Untarrer = function(arrayBuffer, opt_pathToBitJS) { 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 '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
* in the arrayBuffer. * in the arrayBuffer.
* @param {ArrayBuffer} ab * @param {ArrayBuffer} ab
* @param {string=} opt_pathToBitJS Path to the unarchiver script files. * @param {string=} opt_pathToBitJS Path to the unarchiver script files.
* @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; var unarchiver = null;
var pathToBitJS = opt_pathToBitJS || ''; var pathToBitJS = opt_pathToBitJS || '';
var h = new Uint8Array(ab, 0, 10); var h = new Uint8Array(ab, 0, 10);
@ -370,6 +378,6 @@ bitjs.archive.GetUnarchiver = function(ab, opt_pathToBitJS) {
unarchiver = new bitjs.archive.Untarrer(ab, pathToBitJS); unarchiver = new bitjs.archive.Untarrer(ab, pathToBitJS);
} }
return unarchiver; return unarchiver;
}; };
})(); })();

@ -34,8 +34,8 @@ function CRC(startCRC, arr) {
InitCRC(); InitCRC();
} }
/* /*
#if defined(LITTLE_ENDIAN) && defined(PRESENT_INT32) && defined(ALLOW_NOT_ALIGNED_INT) #if defined(LITTLE_ENDIAN) && defined(PRESENT_INT32) && defined(ALLOW_NOT_ALIGNED_INT)
while (Size>0 && ((long)Data & 7)) while (Size>0 && ((long)Data & 7))
{ {
StartCRC=CRCTab[(byte)(StartCRC^Data[0])]^(StartCRC>>8); StartCRC=CRCTab[(byte)(StartCRC^Data[0])]^(StartCRC>>8);
@ -57,8 +57,8 @@ function CRC(startCRC, arr) {
Data+=8; Data+=8;
Size-=8; Size-=8;
} }
#endif #endif
*/ */
for (var i = 0; i < arr.length; ++i) { for (var i = 0; i < arr.length; ++i) {
var byte = ((startCRC ^ arr[i]) >>> 0) & 0xff; var byte = ((startCRC ^ arr[i]) >>> 0) & 0xff;
@ -126,14 +126,14 @@ var VM_Commands = {
VM_SBB: 38, VM_SBB: 38,
VM_PRINT: 39, VM_PRINT: 39,
/* /*
#ifdef VM_OPTIMIZE #ifdef VM_OPTIMIZE
VM_MOVB, VM_MOVD, VM_CMPB, VM_CMPD, VM_MOVB, VM_MOVD, VM_CMPB, VM_CMPD,
VM_ADDB, VM_ADDD, VM_SUBB, VM_SUBD, VM_INCB, VM_INCD, VM_DECB, VM_DECD, VM_ADDB, VM_ADDD, VM_SUBB, VM_SUBD, VM_INCB, VM_INCD, VM_DECB, VM_DECD,
VM_NEGB, VM_NEGD, VM_NEGB, VM_NEGD,
#endif #endif
*/ */
// TODO: This enum value would be much larger if VM_OPTIMIZE. // TODO: This enum value would be much larger if VM_OPTIMIZE.
VM_STANDARD: 40, VM_STANDARD: 40,
@ -224,11 +224,11 @@ VM_PreparedOperand.prototype.toString = function() {
if (this.Type === null) { if (this.Type === null) {
return 'Error: Type was null in VM_PreparedOperand'; return 'Error: Type was null in VM_PreparedOperand';
} }
return '{ ' return '{ ' +
+ 'Type: ' + getDebugString(VM_OpType, this.Type) 'Type: ' + getDebugString(VM_OpType, this.Type) +
+ ', Data: ' + this.Data ', Data: ' + this.Data +
+ ', Base: ' + this.Base ', Base: ' + this.Base +
+ ' }'; ' }';
}; };
/** /**
@ -255,12 +255,12 @@ VM_PreparedCommand.prototype.toString = function(indent) {
return 'Error: OpCode was null in VM_PreparedCommand'; return 'Error: OpCode was null in VM_PreparedCommand';
} }
indent = indent || ''; indent = indent || '';
return indent + '{\n' return indent + '{\n' +
+ indent + ' OpCode: ' + getDebugString(VM_Commands, this.OpCode) + ',\n' indent + ' OpCode: ' + getDebugString(VM_Commands, this.OpCode) + ',\n' +
+ indent + ' ByteMode: ' + this.ByteMode + ',\n' indent + ' ByteMode: ' + this.ByteMode + ',\n' +
+ 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 + '}';
}; };
/** /**
@ -339,46 +339,86 @@ var VMCF_USEFLAGS = 32;
var VMCF_CHFLAGS = 64; var VMCF_CHFLAGS = 64;
var VM_CmdFlags = [ var VM_CmdFlags = [
/* VM_MOV */ VMCF_OP2 | VMCF_BYTEMODE , /* VM_MOV */
/* VM_CMP */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP2 | VMCF_BYTEMODE,
/* VM_ADD */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_CMP */
/* VM_SUB */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_JZ */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , /* VM_ADD */
/* VM_JNZ */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_INC */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_SUB */
/* VM_DEC */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_JMP */ VMCF_OP1 | VMCF_JUMP , /* VM_JZ */
/* VM_XOR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_AND */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_JNZ */
/* VM_OR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_TEST */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_INC */
/* VM_JS */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_JNS */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , /* VM_DEC */
/* VM_JB */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_JBE */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , /* VM_JMP */
/* VM_JA */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , VMCF_OP1 | VMCF_JUMP,
/* VM_JAE */ VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS , /* VM_XOR */
/* VM_PUSH */ VMCF_OP1 , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_POP */ VMCF_OP1 , /* VM_AND */
/* VM_CALL */ VMCF_OP1 | VMCF_PROC , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_RET */ VMCF_OP0 | VMCF_PROC , /* VM_OR */
/* VM_NOT */ VMCF_OP1 | VMCF_BYTEMODE , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_SHL */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_TEST */
/* VM_SHR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_SAR */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS , /* VM_JS */
/* VM_NEG */ VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_PUSHA */ VMCF_OP0 , /* VM_JNS */
/* VM_POPA */ VMCF_OP0 , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_PUSHF */ VMCF_OP0 | VMCF_USEFLAGS , /* VM_JB */
/* VM_POPF */ VMCF_OP0 | VMCF_CHFLAGS , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_MOVZX */ VMCF_OP2 , /* VM_JBE */
/* VM_MOVSX */ VMCF_OP2 , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_XCHG */ VMCF_OP2 | VMCF_BYTEMODE , /* VM_JA */
/* VM_MUL */ VMCF_OP2 | VMCF_BYTEMODE , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_DIV */ VMCF_OP2 | VMCF_BYTEMODE , /* VM_JAE */
/* VM_ADC */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS , VMCF_OP1 | VMCF_JUMP | VMCF_USEFLAGS,
/* VM_SBB */ VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS , /* VM_PUSH */
/* VM_PRINT */ VMCF_OP0 , VMCF_OP1,
/* VM_POP */
VMCF_OP1,
/* VM_CALL */
VMCF_OP1 | VMCF_PROC,
/* VM_RET */
VMCF_OP0 | VMCF_PROC,
/* VM_NOT */
VMCF_OP1 | VMCF_BYTEMODE,
/* VM_SHL */
VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_SHR */
VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_SAR */
VMCF_OP2 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_NEG */
VMCF_OP1 | VMCF_BYTEMODE | VMCF_CHFLAGS,
/* VM_PUSHA */
VMCF_OP0,
/* VM_POPA */
VMCF_OP0,
/* VM_PUSHF */
VMCF_OP0 | VMCF_USEFLAGS,
/* VM_POPF */
VMCF_OP0 | VMCF_CHFLAGS,
/* VM_MOVZX */
VMCF_OP2,
/* VM_MOVSX */
VMCF_OP2,
/* VM_XCHG */
VMCF_OP2 | VMCF_BYTEMODE,
/* VM_MUL */
VMCF_OP2 | VMCF_BYTEMODE,
/* VM_DIV */
VMCF_OP2 | VMCF_BYTEMODE,
/* VM_ADC */
VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS,
/* VM_SBB */
VMCF_OP2 | VMCF_BYTEMODE | VMCF_USEFLAGS | VMCF_CHFLAGS,
/* VM_PRINT */
VMCF_OP0,
]; ];
@ -522,8 +562,8 @@ RarVM.prototype.execute = function(prg) {
} }
var dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR); var dataView = new DataView(this.mem_.buffer, VM_GLOBALMEMADDR);
var newBlockPos = dataView.getUint32(0x20, true /* little endian */) & VM_MEMMASK; var newBlockPos = dataView.getUint32(0x20, true /* little endian */ ) & VM_MEMMASK;
var newBlockSize = dataView.getUint32(0x1c, true /* little endian */) & VM_MEMMASK; var 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;
} }
@ -585,7 +625,7 @@ RarVM.prototype.executeStandardFilter = function(filterType) {
//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); var 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) {
break; break;
@ -618,10 +658,10 @@ RarVM.prototype.prepare = function(code, prg) {
//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 */); var 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; var xorSum = 0;
for (var i = 1; i < codeSize; ++i) { for (var i = 1; i < codeSize; ++i) {
xorSum ^= code[i]; xorSum ^= code[i];
} }
@ -690,7 +730,7 @@ RarVM.prototype.prepare = function(code, prg) {
if (opNum == 2) { if (opNum == 2) {
this.decodeArg(curCmd.Op2, curCmd.ByteMode, bstream); // reading the second operand this.decodeArg(curCmd.Op2, curCmd.ByteMode, bstream); // reading the second operand
} 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; var distance = curCmd.Op1.Data;
if (distance >= 256) { if (distance >= 256) {
@ -740,11 +780,11 @@ RarVM.prototype.prepare = function(code, prg) {
} }
} }
/* /*
#ifdef VM_OPTIMIZE #ifdef VM_OPTIMIZE
if (CodeSize!=0) if (CodeSize!=0)
Optimize(Prg); Optimize(Prg);
#endif #endif
*/ */
}; };

@ -41,10 +41,10 @@ var postProgress = function() {
// shows a byte value as its hex representation // shows a byte value as its hex representation
var nibble = "0123456789ABCDEF"; var nibble = "0123456789ABCDEF";
var byteValueToHexString = function(num) { var byteValueToHexString = function(num) {
return nibble[num>>4] + nibble[num&0xF]; return nibble[num >> 4] + nibble[num & 0xF];
}; };
var twoByteValueToHexString = function(num) { var twoByteValueToHexString = function(num) {
return nibble[(num>>12)&0xF] + nibble[(num>>8)&0xF] + nibble[(num>>4)&0xF] + nibble[num&0xF]; return nibble[(num >> 12) & 0xF] + nibble[(num >> 8) & 0xF] + nibble[(num >> 4) & 0xF] + nibble[num & 0xF];
}; };
@ -69,7 +69,7 @@ var MARK_HEAD = 0x72,
var RarVolumeHeader = function(bstream) { var RarVolumeHeader = function(bstream) {
var headPos = bstream.bytePtr; var headPos = bstream.bytePtr;
// byte 1,2 // byte 1,2
info("Rar Volume Header @"+bstream.bytePtr); info("Rar Volume Header @" + bstream.bytePtr);
this.crc = bstream.readBits(16); this.crc = bstream.readBits(16);
info(" crc=" + this.crc); info(" crc=" + this.crc);
@ -180,13 +180,13 @@ var RarVolumeHeader = function(bstream) {
// this is adapted straight out of arcread.cpp, Archive::ReadHeader() // this is adapted straight out of arcread.cpp, Archive::ReadHeader()
for (var I = 0; I < 4; ++I) { for (var I = 0; I < 4; ++I) {
var rmode = extTimeFlags >> ((3-I)*4); var rmode = extTimeFlags >> ((3 - I) * 4);
if ((rmode & 8)==0) { if ((rmode & 8) == 0) {
continue; continue;
} }
if (I!=0) if (I != 0)
bstream.readBits(16); bstream.readBits(16);
var count = (rmode&3); var count = (rmode & 3);
for (var J = 0; J < count; ++J) { for (var J = 0; J < count; ++J) {
bstream.readBits(8); bstream.readBits(8);
} }
@ -208,7 +208,7 @@ var RarVolumeHeader = function(bstream) {
default: default:
info("Found a header of type 0x" + byteValueToHexString(this.headType)); info("Found a header of type 0x" + byteValueToHexString(this.headType));
// skip the rest of the header bytes (for now) // skip the rest of the header bytes (for now)
bstream.readBytes( this.headSize - 7 ); bstream.readBytes(this.headSize - 7);
break; break;
} }
}; };
@ -216,21 +216,23 @@ var RarVolumeHeader = function(bstream) {
var BLOCK_LZ = 0, var BLOCK_LZ = 0,
BLOCK_PPM = 1; BLOCK_PPM = 1;
var rLDecode = [0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224], var rLDecode = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224],
rLBits = [0,0,0,0,0,0,0,0,1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], rLBits = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5],
rDBitLengthCounts = [4,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,14,0,12], rDBitLengthCounts = [4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 0, 12],
rSDDecode = [0,4,8,16,32,64,128,192], rSDDecode = [0, 4, 8, 16, 32, 64, 128, 192],
rSDBits = [2,2,3, 4, 5, 6, 6, 6]; rSDBits = [2, 2, 3, 4, 5, 6, 6, 6];
var rDDecode = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, var rDDecode = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32,
48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072,
4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304, 4096, 6144, 8192, 12288, 16384, 24576, 32768, 49152, 65536, 98304,
131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824, 131072, 196608, 262144, 327680, 393216, 458752, 524288, 589824,
655360, 720896, 786432, 851968, 917504, 983040]; 655360, 720896, 786432, 851968, 917504, 983040
];
var rDBits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, var rDBits = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5,
5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14,
15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]; 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16
];
var rLOW_DIST_REP_COUNT = 16; var rLOW_DIST_REP_COUNT = 16;
@ -239,7 +241,7 @@ var rNC = 299,
rLDC = 17, rLDC = 17,
rRC = 28, rRC = 28,
rBC = 20, rBC = 20,
rHUFF_TABLE_SIZE = (rNC+rDC+rRC+rLDC); rHUFF_TABLE_SIZE = (rNC + rDC + rRC + rLDC);
var UnpBlockType = BLOCK_LZ; var UnpBlockType = BLOCK_LZ;
var UnpOldTable = new Array(rHUFF_TABLE_SIZE); var UnpOldTable = new Array(rHUFF_TABLE_SIZE);
@ -308,7 +310,7 @@ function RarReadTables(bstream) {
var Table = new Array(rHUFF_TABLE_SIZE); var Table = new Array(rHUFF_TABLE_SIZE);
// before we start anything we need to get byte-aligned // before we start anything we need to get byte-aligned
bstream.readBits( (8 - bstream.bitPtr) & 0x7 ); bstream.readBits((8 - bstream.bitPtr) & 0x7);
if (bstream.readBits(1)) { if (bstream.readBits(1)) {
info("Error! PPM not implemented yet"); info("Error! PPM not implemented yet");
@ -328,15 +330,13 @@ function RarReadTables(bstream) {
var ZeroCount = bstream.readBits(4); var ZeroCount = bstream.readBits(4);
if (ZeroCount == 0) { if (ZeroCount == 0) {
BitLength[I] = 15; BitLength[I] = 15;
} } else {
else {
ZeroCount += 2; ZeroCount += 2;
while (ZeroCount-- > 0 && I < rBC) while (ZeroCount-- > 0 && I < rBC)
BitLength[I++] = 0; BitLength[I++] = 0;
--I; --I;
} }
} } else {
else {
BitLength[I] = Length; BitLength[I] = Length;
} }
} }
@ -381,26 +381,28 @@ function RarReadTables(bstream) {
function RarDecodeNumber(bstream, dec) { function RarDecodeNumber(bstream, dec) {
var DecodeLen = dec.DecodeLen, DecodePos = dec.DecodePos, DecodeNum = dec.DecodeNum; var DecodeLen = dec.DecodeLen,
DecodePos = dec.DecodePos,
DecodeNum = dec.DecodeNum;
var bitField = bstream.getBits() & 0xfffe; var bitField = bstream.getBits() & 0xfffe;
//some sort of rolled out binary search //some sort of rolled out binary search
var bits = ((bitField < DecodeLen[8])? var bits = ((bitField < DecodeLen[8]) ?
((bitField < DecodeLen[4])? ((bitField < DecodeLen[4]) ?
((bitField < DecodeLen[2])? ((bitField < DecodeLen[2]) ?
((bitField < DecodeLen[1])?1:2) ((bitField < DecodeLen[1]) ? 1 : 2) :
:((bitField < DecodeLen[3])?3:4)) ((bitField < DecodeLen[3]) ? 3 : 4)) :
:(bitField < DecodeLen[6])? (bitField < DecodeLen[6]) ?
((bitField < DecodeLen[5])?5:6) ((bitField < DecodeLen[5]) ? 5 : 6) :
:((bitField < DecodeLen[7])?7:8)) ((bitField < DecodeLen[7]) ? 7 : 8)) :
:((bitField < DecodeLen[12])? ((bitField < DecodeLen[12]) ?
((bitField < DecodeLen[10])? ((bitField < DecodeLen[10]) ?
((bitField < DecodeLen[9])?9:10) ((bitField < DecodeLen[9]) ? 9 : 10) :
:((bitField < DecodeLen[11])?11:12)) ((bitField < DecodeLen[11]) ? 11 : 12)) :
:(bitField < DecodeLen[14])? (bitField < DecodeLen[14]) ?
((bitField < DecodeLen[13])?13:14) ((bitField < DecodeLen[13]) ? 13 : 14) :
:15)); 15));
bstream.readBits(bits); bstream.readBits(bits);
var N = DecodePos[bits] + ((bitField - DecodeLen[bits -1]) >>> (16 - bits)); var N = DecodePos[bits] + ((bitField - DecodeLen[bits - 1]) >>> (16 - bits));
return DecodeNum[N]; return DecodeNum[N];
} }
@ -410,8 +412,8 @@ function RarMakeDecodeTables(BitLength, offset, dec, size) {
var DecodeLen = dec.DecodeLen; var DecodeLen = dec.DecodeLen;
var DecodePos = dec.DecodePos; var DecodePos = dec.DecodePos;
var DecodeNum = dec.DecodeNum; var DecodeNum = dec.DecodeNum;
var LenCount = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; var LenCount = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var TmpPos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; var TmpPos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var N = 0; var N = 0;
var M = 0; var M = 0;
@ -427,18 +429,18 @@ function RarMakeDecodeTables(BitLength, offset, dec, size) {
DecodeLen[0] = 0; DecodeLen[0] = 0;
for (var I = 1; I < 16; ++I) { for (var I = 1; I < 16; ++I) {
N = 2 * (N+LenCount[I]); N = 2 * (N + LenCount[I]);
M = (N << (15-I)); M = (N << (15 - I));
if (M > 0xFFFF) { if (M > 0xFFFF) {
M = 0xFFFF; M = 0xFFFF;
} }
DecodeLen[I] = M; DecodeLen[I] = M;
DecodePos[I] = DecodePos[I-1] + LenCount[I-1]; DecodePos[I] = DecodePos[I - 1] + LenCount[I - 1];
TmpPos[I] = DecodePos[I]; TmpPos[I] = DecodePos[I];
} }
for (I = 0; I < size; ++I) { for (I = 0; I < size; ++I) {
if (BitLength[I + offset] != 0) { if (BitLength[I + offset] != 0) {
DecodeNum[ TmpPos[ BitLength[offset + I] & 0xF ]++] = I; DecodeNum[TmpPos[BitLength[offset + I] & 0xF]++] = I;
} }
} }
@ -503,7 +505,7 @@ function Unpack20(bstream, Solid) {
if (num < 261) { if (num < 261) {
var Distance = rOldDist[(oldDistPtr - (num - 256)) & 3]; var Distance = rOldDist[(oldDistPtr - (num - 256)) & 3];
var LengthNumber = RarDecodeNumber(bstream, RD); var LengthNumber = RarDecodeNumber(bstream, RD);
var Length = rLDecode[LengthNumber] +2; var Length = rLDecode[LengthNumber] + 2;
if ((Bits = rLBits[LengthNumber]) > 0) { if ((Bits = rLBits[LengthNumber]) > 0) {
Length += bstream.readBits(Bits); Length += bstream.readBits(Bits);
} }
@ -600,7 +602,7 @@ function RarReadTables20(bstream) {
var lowDistRepCount = 0; var lowDistRepCount = 0;
var prevLowDist = 0; var prevLowDist = 0;
var rOldDist = [0,0,0,0]; var rOldDist = [0, 0, 0, 0];
var lastDist; var lastDist;
var lastLength; var lastLength;
@ -644,7 +646,7 @@ function InitFilters() {
*/ */
function RarAddVMCode(firstByte, vmCode) { function RarAddVMCode(firstByte, vmCode) {
VM.init(); VM.init();
var bstream = new bitjs.io.BitStream(vmCode.buffer, true /* rtl */); var bstream = new bitjs.io.BitStream(vmCode.buffer, true /* rtl */ );
var filtPos; var filtPos;
if (firstByte & 0x80) { if (firstByte & 0x80) {
@ -716,9 +718,9 @@ function RarAddVMCode(firstByte, vmCode) {
if (firstByte & 0x20) { if (firstByte & 0x20) {
stackFilter.BlockLength = RarVM.readData(bstream); stackFilter.BlockLength = RarVM.readData(bstream);
} else { } else {
stackFilter.BlockLength = filtPos < OldFilterLengths.length stackFilter.BlockLength = filtPos < OldFilterLengths.length ?
? OldFilterLengths[filtPos] OldFilterLengths[filtPos] :
: 0; 0;
} }
stackFilter.NextWindow = (wBuffer.ptr != rBuffer.ptr) && stackFilter.NextWindow = (wBuffer.ptr != rBuffer.ptr) &&
(((wBuffer.ptr - rBuffer.ptr) & MAXWINMASK) <= blockStart); (((wBuffer.ptr - rBuffer.ptr) & MAXWINMASK) <= blockStart);
@ -788,7 +790,7 @@ function RarAddVMCode(firstByte, vmCode) {
// return(false); // return(false);
var dataSize = RarVM.readData(bstream); var dataSize = RarVM.readData(bstream);
if (dataSize > (VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE)) { if (dataSize > (VM_GLOBALMEMSIZE - VM_FIXEDGLOBALSIZE)) {
return(false); return (false);
} }
var curSize = stackFilter.Prg.GlobalData.length; var curSize = stackFilter.Prg.GlobalData.length;
@ -849,17 +851,17 @@ function Unpack29(bstream, Solid) {
var BitLength = 0; var BitLength = 0;
var Slot = 0; var Slot = 0;
for (var I = 0; I < rDBitLengthCounts.length; I++,BitLength++) { for (var I = 0; I < rDBitLengthCounts.length; I++, BitLength++) {
for (var J = 0; J < rDBitLengthCounts[I]; J++,Slot++,Dist+=(1<<BitLength)) { for (var J = 0; J < rDBitLengthCounts[I]; J++, Slot++, Dist += (1 << BitLength)) {
DDecode[Slot]=Dist; DDecode[Slot] = Dist;
DBits[Slot]=BitLength; DBits[Slot] = BitLength;
} }
} }
var Bits; var Bits;
//tablesRead = false; //tablesRead = false;
rOldDist = [0,0,0,0] rOldDist = [0, 0, 0, 0]
lastDist = 0; lastDist = 0;
lastLength = 0; lastLength = 0;
@ -943,7 +945,7 @@ function Unpack29(bstream, Solid) {
var Distance = rOldDist[DistNum]; var Distance = rOldDist[DistNum];
for (var I = DistNum; I > 0; I--) { for (var I = DistNum; I > 0; I--) {
rOldDist[I] = rOldDist[I-1]; rOldDist[I] = rOldDist[I - 1];
} }
rOldDist[0] = Distance; rOldDist[0] = Distance;
@ -1109,8 +1111,8 @@ function RarWriteBuf() {
function RarWriteArea(startPtr, endPtr) { function RarWriteArea(startPtr, endPtr) {
if (endPtr < startPtr) { if (endPtr < startPtr) {
console.error('endPtr < startPtr, endPtr=' + endPtr + ', startPtr=' + startPtr); console.error('endPtr < startPtr, endPtr=' + endPtr + ', startPtr=' + startPtr);
// RarWriteData(startPtr, -(int)StartPtr & MAXWINMASK); // RarWriteData(startPtr, -(int)StartPtr & MAXWINMASK);
// RarWriteData(0, endPtr); // RarWriteData(0, endPtr);
return; return;
} else if (startPtr < endPtr) { } else if (startPtr < endPtr) {
RarWriteData(startPtr, endPtr - startPtr); RarWriteData(startPtr, endPtr - startPtr);
@ -1138,8 +1140,7 @@ function RarWriteData(offset, numBytes) {
/** /**
* @param {VM_PreparedProgram} prg * @param {VM_PreparedProgram} prg
*/ */
function RarExecuteCode(prg) function RarExecuteCode(prg) {
{
if (prg.GlobalData.length > 0) { if (prg.GlobalData.length > 0) {
var writtenFileSize = wBuffer.ptr; var writtenFileSize = wBuffer.ptr;
prg.InitR[6] = writtenFileSize; prg.InitR[6] = writtenFileSize;
@ -1152,7 +1153,8 @@ function RarExecuteCode(prg)
function RarReadEndOfBlock(bstream) { function RarReadEndOfBlock(bstream) {
RarUpdateProgress(); RarUpdateProgress();
var NewTable = false, NewFile = false; var NewTable = false,
NewFile = false;
if (bstream.readBits(1)) { if (bstream.readBits(1)) {
NewTable = true; NewTable = true;
} else { } else {
@ -1169,8 +1171,8 @@ function RarInsertLastMatch(length, distance) {
} }
function RarInsertOldDist(distance) { function RarInsertOldDist(distance) {
rOldDist.splice(3,1); rOldDist.splice(3, 1);
rOldDist.splice(0,0,distance); rOldDist.splice(0, 0, distance);
} }
/** /**
@ -1208,7 +1210,7 @@ function unpack(v) {
// TODO: implement what happens when unpVer is < 15 // TODO: implement what happens when unpVer is < 15
var Ver = v.header.unpVer <= 15 ? 15 : v.header.unpVer; var Ver = v.header.unpVer <= 15 ? 15 : v.header.unpVer;
var Solid = v.header.LHD_SOLID; var Solid = v.header.LHD_SOLID;
var bstream = new bitjs.io.BitStream(v.fileData.buffer, true /* rtl */, v.fileData.byteOffset, v.fileData.byteLength ); var bstream = new bitjs.io.BitStream(v.fileData.buffer, true /* rtl */ , v.fileData.byteOffset, v.fileData.byteLength);
rBuffer = new bitjs.io.ByteBuffer(v.header.unpackedSize); rBuffer = new bitjs.io.ByteBuffer(v.header.unpackedSize);
@ -1242,8 +1244,7 @@ var RarLocalFile = function(bstream) {
if (this.header.headType != FILE_HEAD && this.header.headType != ENDARC_HEAD) { if (this.header.headType != FILE_HEAD && this.header.headType != ENDARC_HEAD) {
this.isValid = false; this.isValid = false;
info("Error! RAR Volume did not include a FILE_HEAD header "); info("Error! RAR Volume did not include a FILE_HEAD header ");
} } else {
else {
// read in the compressed data // read in the compressed data
this.fileData = null; this.fileData = null;
if (this.header.packSize > 0) { if (this.header.packSize > 0) {
@ -1257,7 +1258,7 @@ RarLocalFile.prototype.unrar = function() {
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) {
info("Unstore "+this.filename); info("Unstore " + this.filename);
this.isValid = true; this.isValid = true;
currentBytesUnarchivedInFile += this.fileData.length; currentBytesUnarchivedInFile += this.fileData.length;
@ -1284,7 +1285,7 @@ var unrar = function(arrayBuffer) {
totalFilesInArchive = 0; totalFilesInArchive = 0;
postMessage(new bitjs.archive.UnarchiveStartEvent()); postMessage(new bitjs.archive.UnarchiveStartEvent());
var bstream = new bitjs.io.BitStream(arrayBuffer, false /* rtl */); var bstream = new bitjs.io.BitStream(arrayBuffer, false /* rtl */ );
var header = new RarVolumeHeader(bstream); var header = new RarVolumeHeader(bstream);
if (header.crc == 0x6152 && if (header.crc == 0x6152 &&
@ -1296,8 +1297,7 @@ var unrar = function(arrayBuffer) {
var mhead = new RarVolumeHeader(bstream); var mhead = new RarVolumeHeader(bstream);
if (mhead.headType != MAIN_HEAD) { if (mhead.headType != MAIN_HEAD) {
info("Error! RAR did not include a MAIN_HEAD header"); info("Error! RAR did not include a MAIN_HEAD header");
} } else {
else {
var localFiles = [], var localFiles = [],
localFile = null; localFile = null;
do { do {
@ -1310,7 +1310,7 @@ var unrar = function(arrayBuffer) {
} else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) { } else if (localFile.header.packSize == 0 && localFile.header.unpackedSize == 0) {
localFile.isValid = true; localFile.isValid = true;
} }
} catch(err) { } catch (err) {
break; break;
} }
//info("bstream" + bstream.bytePtr+"/"+bstream.bytes.length); //info("bstream" + bstream.bytePtr+"/"+bstream.bytes.length);
@ -1319,13 +1319,15 @@ var unrar = function(arrayBuffer) {
// now we have all information but things are unpacked // now we have all information but things are unpacked
// TODO: unpack // TODO: unpack
localFiles = localFiles.sort(function(a,b) { localFiles = localFiles.sort(function(a, b) {
var aname = a.filename.toLowerCase(); var aname = a.filename.toLowerCase();
var bname = b.filename.toLowerCase(); var bname = b.filename.toLowerCase();
return aname > bname ? 1 : -1; return aname > bname ? 1 : -1;
}); });
info(localFiles.map(function(a){return a.filename}).join(', ')); info(localFiles.map(function(a) {
return a.filename
}).join(', '));
for (var i = 0; i < localFiles.length; ++i) { for (var i = 0; i < localFiles.length; ++i) {
var localfile = localFiles[i]; var localfile = localFiles[i];
@ -1344,8 +1346,7 @@ var unrar = function(arrayBuffer) {
postProgress(); postProgress();
} }
} } else {
else {
err("Invalid RAR file"); err("Invalid RAR file");
} }
postMessage(new bitjs.archive.UnarchiveFinishEvent()); postMessage(new bitjs.archive.UnarchiveFinishEvent());

@ -133,7 +133,7 @@ var untar = function(arrayBuffer) {
totalFilesInArchive = localFiles.length; totalFilesInArchive = localFiles.length;
// 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; var aname = a.filename;
var bname = b.filename; var bname = b.filename;
return aname > bname ? 1 : -1; return aname > bname ? 1 : -1;

@ -52,7 +52,8 @@ var 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) { var 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;
} }
@ -114,8 +115,8 @@ var ZipLocalFile = function(bstream) {
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)");
currentBytesUnarchivedInFile = this.compressedSize; currentBytesUnarchivedInFile = this.compressedSize;
currentBytesUnarchived += this.compressedSize; currentBytesUnarchived += this.compressedSize;
} }
@ -123,8 +124,7 @@ ZipLocalFile.prototype.unzip = function() {
else if (this.compressionMethod == 8) { else if (this.compressionMethod == 8) {
info("ZIP v2.0, DEFLATE: " + this.filename + " (" + this.compressedSize + " bytes)"); info("ZIP v2.0, DEFLATE: " + this.filename + " (" + this.compressedSize + " bytes)");
this.fileData = inflate(this.fileData, this.uncompressedSize); this.fileData = inflate(this.fileData, this.uncompressedSize);
} } else {
else {
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;
} }
@ -161,7 +161,7 @@ var unzip = function(arrayBuffer) {
totalFilesInArchive = localFiles.length; totalFilesInArchive = localFiles.length;
// 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; var aname = a.filename;
var bname = b.filename; var bname = b.filename;
return aname > bname ? 1 : -1; return aname > bname ? 1 : -1;
@ -299,19 +299,23 @@ function getHuffmanCodes(bitLengths) {
var next_code = [], var next_code = [],
code = 0; code = 0;
for (var bits = 1; bits <= MAX_BITS; ++bits) { for (var bits = 1; bits <= MAX_BITS; ++bits) {
var length = bits-1; var 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;
next_code[bits] = code; next_code[bits] = code;
} }
// Step 3: Assign numerical values to all codes // Step 3: Assign numerical values to all codes
var table = {}, tableLength = 0; var table = {},
tableLength = 0;
for (var n = 0; n < numLengths; ++n) { for (var n = 0; n < numLengths; ++n) {
var len = bitLengths[n]; var 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++;
next_code[len]++; next_code[len]++;
} }
@ -340,6 +344,7 @@ function getHuffmanCodes(bitLengths) {
// 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; var fixedHCtoLiteral = null;
var fixedHCtoDistance = null; var fixedHCtoDistance = null;
function getFixedLiteralTable() { function getFixedLiteralTable() {
// create once // create once
if (!fixedHCtoLiteral) { if (!fixedHCtoLiteral) {
@ -359,7 +364,9 @@ function getFixedDistanceTable() {
// create once // create once
if (!fixedHCtoDistance) { if (!fixedHCtoDistance) {
var bitlengths = new Array(32); var bitlengths = new Array(32);
for (var i = 0; i < 32; ++i) { bitlengths[i] = 5; } for (var i = 0; i < 32; ++i) {
bitlengths[i] = 5;
}
// get huffman code table // get huffman code table
fixedHCtoDistance = getHuffmanCodes(bitlengths); fixedHCtoDistance = getHuffmanCodes(bitlengths);
@ -370,14 +377,15 @@ 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; var code = 0,
len = 0;
var match = false; var 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); var bit = bstream.readBits(1);
code = (code<<1) | bit; code = (code << 1) | bit;
++len; ++len;
// check against Huffman Code table and break if found // check against Huffman Code table and break if found
@ -395,10 +403,10 @@ 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]; var 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
@ -409,18 +417,39 @@ var CodeLengthCodeOrder = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2
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
*/ */
var LengthLookupTable = [ var LengthLookupTable = [
[0,3], [0,4], [0,5], [0,6], [0, 3],
[0,7], [0,8], [0,9], [0,10], [0, 4],
[1,11], [1,13], [1,15], [1,17], [0, 5],
[2,19], [2,23], [2,27], [2,31], [0, 6],
[3,35], [3,43], [3,51], [3,59], [0, 7],
[4,67], [4,83], [4,99], [4,115], [0, 8],
[5,131], [5,163], [5,195], [5,227], [0, 9],
[0,258] [0, 10],
[1, 11],
[1, 13],
[1, 15],
[1, 17],
[2, 19],
[2, 23],
[2, 27],
[2, 31],
[3, 35],
[3, 43],
[3, 51],
[3, 59],
[4, 67],
[4, 83],
[4, 99],
[4, 115],
[5, 131],
[5, 163],
[5, 195],
[5, 227],
[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
---- ---- ---- ---- ---- ------ ---- ---- -------- ---- ---- ---- ---- ---- ------ ---- ---- --------
@ -434,22 +463,38 @@ var 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
*/ */
var DistLookupTable = [ var DistLookupTable = [
[0,1], [0,2], [0,3], [0,4], [0, 1],
[1,5], [1,7], [0, 2],
[2,9], [2,13], [0, 3],
[3,17], [3,25], [0, 4],
[4,33], [4,49], [1, 5],
[5,65], [5,97], [1, 7],
[6,129], [6,193], [2, 9],
[7,257], [7,385], [2, 13],
[8,513], [8,769], [3, 17],
[9,1025], [9,1537], [3, 25],
[10,2049], [10,3073], [4, 33],
[11,4097], [11,6145], [4, 49],
[12,8193], [12,12289], [5, 65],
[13,16385], [13,24577] [5, 97],
[6, 129],
[6, 193],
[7, 257],
[7, 385],
[8, 513],
[8, 769],
[9, 1025],
[9, 1537],
[10, 2049],
[10, 3073],
[11, 4097],
[11, 6145],
[12, 8193],
[12, 12289],
[13, 16385],
[13, 24577]
]; ];
function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) { function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
@ -468,7 +513,8 @@ 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; var numSymbols = 0,
blockSize = 0;
for (;;) { for (;;) {
var symbol = decodeSymbol(bstream, hcLiteralTable); var symbol = decodeSymbol(bstream, hcLiteralTable);
++numSymbols; ++numSymbols;
@ -476,14 +522,12 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
// copy literal byte to output // copy literal byte to output
buffer.insertByte(symbol); buffer.insertByte(symbol);
blockSize++; blockSize++;
} } else {
else {
// end of block reached // end of block reached
if (symbol == 256) { if (symbol == 256) {
break; break;
} } else {
else { var lengthLookup = LengthLookupTable[symbol - 257],
var lengthLookup = LengthLookupTable[symbol-257],
length = lengthLookup[1] + bstream.readBits(lengthLookup[0]), length = lengthLookup[1] + bstream.readBits(lengthLookup[0]),
distLookup = DistLookupTable[decodeSymbol(bstream, hcDistanceTable)], distLookup = DistLookupTable[decodeSymbol(bstream, hcDistanceTable)],
distance = distLookup[1] + bstream.readBits(distLookup[0]); distance = distLookup[1] + bstream.readBits(distLookup[0]);
@ -501,7 +545,7 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
// loop for each character // loop for each character
var ch = buffer.ptr - distance; var ch = buffer.ptr - distance;
blockSize += length; blockSize += length;
if(length > distance) { if (length > distance) {
var data = buffer.data; var data = buffer.data;
while (length--) { while (length--) {
buffer.insertByte(data[ch++]); buffer.insertByte(data[ch++]);
@ -521,11 +565,12 @@ function inflateBlockData(bstream, hcLiteralTable, hcDistanceTable, buffer) {
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, var 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); var buffer = new bitjs.io.ByteBuffer(numDecompressedBytes);
var numBlocks = 0, blockSize = 0; var numBlocks = 0,
blockSize = 0;
// block format: http://tools.ietf.org/html/rfc1951#page-9 // block format: http://tools.ietf.org/html/rfc1951#page-9
do { do {
@ -540,23 +585,23 @@ function inflate(compressedData, numDecompressedBytes) {
var len = bstream.readBits(16), var len = bstream.readBits(16),
nlen = bstream.readBits(16); 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
else if(bType == 1) { else if (bType == 1) {
blockSize = inflateBlockData(bstream, getFixedLiteralTable(), getFixedDistanceTable(), buffer); blockSize = inflateBlockData(bstream, getFixedLiteralTable(), getFixedDistanceTable(), buffer);
} }
// dynamic Huffman codes // dynamic Huffman codes
else if(bType == 2) { else if (bType == 2) {
var numLiteralLengthCodes = bstream.readBits(5) + 257; var numLiteralLengthCodes = bstream.readBits(5) + 257;
var numDistanceCodes = bstream.readBits(5) + 1, var numDistanceCodes = bstream.readBits(5) + 1,
numCodeLengthCodes = bstream.readBits(4) + 4; 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]; var 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 (var 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
@ -585,20 +630,17 @@ function inflate(compressedData, numDecompressedBytes) {
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; var 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; var 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; var repeat = bstream.readBits(7) + 11;
while (repeat--) { while (repeat--) {
literalCodeLengths.push(0); literalCodeLengths.push(0);

@ -8,23 +8,23 @@
* Copyright(c) 2011 Google Inc. * Copyright(c) 2011 Google Inc.
* Copyright(c) 2011 antimatter15 * Copyright(c) 2011 antimatter15
*/ */
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() { (function() {
// mask for getting the Nth bit (zero-based) // mask for getting the Nth bit (zero-based)
bitjs.BIT = [ 0x01, 0x02, 0x04, 0x08, bitjs.BIT = [0x01, 0x02, 0x04, 0x08,
0x10, 0x20, 0x40, 0x80, 0x10, 0x20, 0x40, 0x80,
0x100, 0x200, 0x400, 0x800, 0x100, 0x200, 0x400, 0x800,
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 ]; var 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.
* *
* @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array. * @param {ArrayBuffer} ab An ArrayBuffer object or a Uint8Array.
@ -33,7 +33,7 @@ var BITMASK = [0, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF ];
* @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) { bitjs.io.BitStream = function(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 +44,10 @@ 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 +57,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, movePointers) { bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -89,8 +89,7 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, movePointers) {
bitPtr = 0; bitPtr = 0;
bitsIn += numBitsLeftInThisByte; bitsIn += numBitsLeftInThisByte;
n -= numBitsLeftInThisByte; n -= numBitsLeftInThisByte;
} } else {
else {
var mask = (BITMASK[n] << bitPtr); var mask = (BITMASK[n] << bitPtr);
result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn); result |= (((bytes[bytePtr] & mask) >> bitPtr) << bitsIn);
@ -106,10 +105,10 @@ bitjs.io.BitStream.prototype.peekBits_ltr = function(n, 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 +118,7 @@ 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, movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -149,8 +148,7 @@ bitjs.io.BitStream.prototype.peekBits_rtl = function(n, movePointers) {
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] & (BITMASK[n] << (8 - n - bitPtr))) >> (8 - n - bitPtr));
@ -165,33 +163,33 @@ bitjs.io.BitStream.prototype.peekBits_rtl = function(n, 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() { bitjs.io.BitStream.prototype.getBits = function() {
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) { bitjs.io.BitStream.prototype.readBits = function(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 +197,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, movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return 0; return 0;
} }
@ -221,15 +219,15 @@ bitjs.io.BitStream.prototype.peekBytes = function(n, 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) { bitjs.io.BitStream.prototype.readBytes = function(n) {
return this.peekBytes(n, true); return this.peekBytes(n, true);
}; };
})(); })();

@ -8,53 +8,52 @@
* Copyright(c) 2011 Google Inc. * Copyright(c) 2011 Google Inc.
* Copyright(c) 2011 antimatter15 * Copyright(c) 2011 antimatter15
*/ */
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() { (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. * @param {number} numBytes The number of bytes to allocate.
* @constructor * @constructor
*/ */
bitjs.io.ByteBuffer = function(numBytes) { bitjs.io.ByteBuffer = function(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) { bitjs.io.ByteBuffer.prototype.insertByte = function(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) { bitjs.io.ByteBuffer.prototype.insertBytes = function(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) { bitjs.io.ByteBuffer.prototype.writeNumber = function(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 +74,16 @@ 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) { bitjs.io.ByteBuffer.prototype.writeSignedNumber = function(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 +102,13 @@ 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) { bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) {
for (var i = 0; i < str.length; ++i) { for (var i = 0; i < str.length; ++i) {
var curByte = str.charCodeAt(i); var curByte = str.charCodeAt(i);
if (curByte < 0 || curByte > 255) { if (curByte < 0 || curByte > 255) {
@ -117,6 +116,6 @@ bitjs.io.ByteBuffer.prototype.writeASCIIString = function(str) {
} }
this.insertByte(curByte); this.insertByte(curByte);
} }
}; };
})(); })();

@ -8,14 +8,13 @@
* Copyright(c) 2011 Google Inc. * Copyright(c) 2011 Google Inc.
* Copyright(c) 2011 antimatter15 * Copyright(c) 2011 antimatter15
*/ */
var bitjs = bitjs || {}; var bitjs = bitjs || {};
bitjs.io = bitjs.io || {}; bitjs.io = bitjs.io || {};
(function() { (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.
* *
@ -24,22 +23,22 @@ bitjs.io = bitjs.io || {};
* @param {number=} opt_length The length of this BitStream * @param {number=} opt_length The length of this BitStream
* @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; var offset = opt_offset || 0;
var length = opt_length || ab.byteLength; var 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) { bitjs.io.ByteStream.prototype.peekNumber = function(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) { bitjs.io.ByteStream.prototype.readNumber = function(n) {
var num = this.peekNumber( n ); var 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) { bitjs.io.ByteStream.prototype.peekSignedNumber = function(n) {
var num = this.peekNumber(n); var num = this.peekNumber(n);
var HALF = Math.pow(2, (n * 8) - 1); var HALF = Math.pow(2, (n * 8) - 1);
var FULL = HALF * 2; var 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) { bitjs.io.ByteStream.prototype.readSignedNumber = function(n) {
var num = this.peekSignedNumber(n); var 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) { bitjs.io.ByteStream.prototype.peekBytes = function(n, movePointers) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return null; return null;
} }
@ -117,25 +116,25 @@ 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) { bitjs.io.ByteStream.prototype.readBytes = function(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) { bitjs.io.ByteStream.prototype.peekString = function(n) {
if (n <= 0 || typeof n != typeof 1) { if (n <= 0 || typeof n != typeof 1) {
return ""; return "";
} }
@ -145,20 +144,20 @@ 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) { bitjs.io.ByteStream.prototype.readString = function(n) {
var strToReturn = this.peekString(n); var strToReturn = this.peekString(n);
this.ptr += n; this.ptr += n;
return strToReturn; return strToReturn;
}; };
})(); })();
Loading…
Cancel
Save