From 053d4bc1272804529c1c3f3b5b4becc3c3cdd518 Mon Sep 17 00:00:00 2001 From: Jeff Schiller Date: Wed, 10 Jan 2024 21:22:53 +0900 Subject: [PATCH] Fix bug with tee() so that endianness is also copied to teed stream. --- io/bytestream.js | 12 ++++++++++++ tests/io-bytestream.spec.js | 3 +++ 2 files changed, 15 insertions(+) diff --git a/io/bytestream.js b/io/bytestream.js index b7b4e29..e39ae23 100644 --- a/io/bytestream.js +++ b/io/bytestream.js @@ -66,6 +66,11 @@ export class ByteStream { this.littleEndian_ = true; } + /** @returns {boolean} Whether the stream is little-endian. */ + isLittleEndian() { + return this.littleEndian_; + } + /** Big-Endian is sometimes called Motorola-style. */ setBigEndian() { this.littleEndian_ = false; @@ -78,6 +83,7 @@ export class ByteStream { /** * Returns how many bytes have been read in the stream since the beginning of time. + * @returns {number} */ getNumBytesRead() { return this.bytesRead_; @@ -85,6 +91,7 @@ export class ByteStream { /** * Returns how many bytes are currently in the stream left to be read. + * @returns {number} */ getNumBytesLeft() { const bytesInCurrentPage = (this.bytes.byteLength - this.ptr); @@ -334,6 +341,10 @@ export class ByteStream { /** * Creates a new ByteStream from this ByteStream that can be read / peeked. + * Note that the teed stream is a disconnected copy. If you push more bytes to the original + * stream, the copy does not get them. + * TODO: Assess whether the above causes more bugs than it avoids. (It would feel weird to me if + * the teed stream shared some state with the original stream.) * @returns {ByteStream} A clone of this ByteStream. */ tee() { @@ -342,6 +353,7 @@ export class ByteStream { clone.ptr = this.ptr; clone.pages_ = this.pages_.slice(); clone.bytesRead_ = this.bytesRead_; + clone.littleEndian_ = this.littleEndian_; return clone; } } diff --git a/tests/io-bytestream.spec.js b/tests/io-bytestream.spec.js index 658ca40..2a0bb1c 100644 --- a/tests/io-bytestream.spec.js +++ b/tests/io-bytestream.spec.js @@ -255,6 +255,8 @@ describe('bitjs.io.ByteStream', () => { it('Tee', () => { for (let i = 0; i < 4; ++i) array[i] = 65 + i; const stream = new ByteStream(array.buffer); + // Set non-default endianness. + stream.setBigEndian(true); const anotherArray = new Uint8Array(4); for (let i = 0; i < 4; ++i) anotherArray[i] = 69 + i; @@ -265,5 +267,6 @@ describe('bitjs.io.ByteStream', () => { teed.readBytes(5); expect(stream.getNumBytesLeft()).equals(8); expect(teed.getNumBytesLeft()).equals(3); + expect(teed.isLittleEndian()).equals(stream.isLittleEndian()); }); });