diff --git a/io/bytestream.js b/io/bytestream.js index 87dc582..54c16cb 100644 --- a/io/bytestream.js +++ b/io/bytestream.js @@ -66,10 +66,12 @@ export class ByteStream { this.littleEndian_ = true; } + /** Big-Endian is sometimes called Motorola-style. */ setBigEndian() { this.littleEndian_ = false; } + /** Little-Endian is sometimes called Intel-style. */ setLittleEndian() { this.littleEndian_ = true; } @@ -292,6 +294,27 @@ export class ByteStream { return strToReturn; } + /** + * Skips n bytes in the stream. + * @param {number} n The number of bytes to skip. Must be a positive integer. + */ + skip(n) { + const num = parseInt(n, 10); + if (n !== num || num < 0) { + throw 'Error! Called skip() with a non-positive integer'; + } else if (num === 0) { + return; + } + + const totalBytesLeft = this.getNumBytesLeft(); + if (num > totalBytesLeft) { + throw 'Error! Overflowed the byte stream while skip()! n=' + num + + ', ptr=' + this.ptr + ', bytes.length=' + this.getNumBytesLeft(); + } + + this.movePointer_(n); + } + /** * Feeds more bytes into the back of the stream. * @param {ArrayBuffer} ab diff --git a/tests/io-bytestream.spec.js b/tests/io-bytestream.spec.js index f7afa7e..6d74f7f 100644 --- a/tests/io-bytestream.spec.js +++ b/tests/io-bytestream.spec.js @@ -202,6 +202,51 @@ describe('bitjs.io.ByteStream', () => { expect(str).equals('ABCDEFGHIJKL'); }); + describe('skip()', () => { + /** @type {ByteStream} */ + let stream; + + beforeEach(() => { + for (let i = 0; i < 4; ++i) array[i] = i; + stream = new ByteStream(array.buffer); + }); + + it('skips bytes', () => { + stream.skip(2); + expect(stream.getNumBytesRead()).equals(2); + expect(stream.getNumBytesLeft()).equals(2); + expect(stream.readNumber(1)).equals(2); + expect(stream.readNumber(1)).equals(3); + }); + + it('skip(0) has no effect', () => { + stream.skip(0); + expect(stream.getNumBytesRead()).equals(0); + expect(stream.getNumBytesLeft()).equals(4); + expect(stream.readNumber(1)).equals(0); + }); + + it('skip() with negative throws an error', () => { + expect(() => stream.skip(-1)).throws(); + expect(stream.getNumBytesLeft()).equals(4); + }); + + it('skip() past the end throws an error', () => { + expect(() => stream.skip(4)).does.not.throw(); + expect(stream.getNumBytesLeft()).equals(0); + expect(() => stream.skip(1)).throws(); + }); + + it('skip() works correct across pages of bytes', () => { + const extraArr = new Uint8Array(4); + for (let i = 0; i < 4; ++i) extraArr[i] = i + 4; + stream.push(extraArr.buffer); + expect(stream.readNumber(1)).equals(0); + stream.skip(5); + expect(stream.readNumber(1)).equals(6); + }); + }); + it('Tee', () => { for (let i = 0; i < 4; ++i) array[i] = 65 + i; const stream = new ByteStream(array.buffer);