♻ Allow 16-bit and 32-bit reads in ByteReader

This commit is contained in:
C-3PO 2018-06-24 02:06:49 +02:00
parent 590dc39f84
commit 2456eae91a
Signed by: c3po
GPG key ID: 62993C4BB4D86F24
2 changed files with 18 additions and 7 deletions

View file

@ -11,14 +11,14 @@ export default async function extractFile(file: ISsnFileEntry, dvArray: DataView
const byteReader = new ByteReader(dvArray, file.diskNumberStart, file.offset);
//Local file header signature must be 0x04034B50
if (byteReader.readByte() !== 0x50 || byteReader.readByte() !== 0x4B || byteReader.readByte() !== 0x03 || byteReader.readByte() !== 0x04) {
if (byteReader.readUint32() !== 0x04034B50) {
throw new Error('Local file header had wrong magic');
}
//All fields in the local file header are copies of the central file header, so we can skip them.
//FIXME: Maybe we should actually read these fields to verify that they are identical?
byteReader.seek(22);
const localFilenameSize = byteReader.readByte() + (byteReader.readByte() << 8);
const localExtraSize = byteReader.readByte() + (byteReader.readByte() << 8);
const localFilenameSize = byteReader.readUint16();
const localExtraSize = byteReader.readUint16();
byteReader.seek(localFilenameSize + localExtraSize);
//Extract actual file contents

View file

@ -7,7 +7,8 @@ export default class ByteReader {
this.dvIndex = startDvIndex;
this.pos = offset;
}
public readByte() {
/** Reads one byte and returns it. */
public readUint8() {
const curByte = this.dvArray[this.dvIndex].getUint8(this.pos);
this.pos += 1;
if (this.pos >= this.dvArray[this.dvIndex].byteLength) {
@ -17,18 +18,28 @@ export default class ByteReader {
}
return curByte;
}
public seek(num: number) {
this.pos += num;
/** Reads two bytes as an unsigned 16-bit integer and returns it. */
public readUint16() {
return this.readUint8() | (this.readUint8() << 8);
}
/** Reads four bytes as an unsigned 32-bit integer and returns it. */
public readUint32() {
return (this.readUint8() | (this.readUint8() << 8) | (this.readUint8() << 16) | (this.readUint8() << 24)) >>> 0;
}
/** Seeks the given number of bytes forward, without reading the bytes. */
public seek(numBytes: number) {
this.pos += numBytes;
if (this.pos >= this.dvArray[this.dvIndex].byteLength) {
this.pos -= this.dvArray[this.dvIndex].byteLength;
this.dvIndex += 1;
if (this.dvIndex >= this.dvArray.length) { throw new Error('Tried to read beyond DataView boundary in extractFile'); }
}
}
/** Reads the given amount of bytes, and returns it as a DataView. */
public extractDv(length: number) {
const dv = new DataView(new ArrayBuffer(length));
for (let i = 0; i < length; i += 1) {
dv.setUint8(i, this.readByte()); //TODO: refactor this so it is more optimized
dv.setUint8(i, this.readUint8()); //TODO: refactor this so it is more optimized
}
return dv;
}