diff --git a/lib/remote-bitfield.js b/lib/remote-bitfield.js index b90a8191..6fefd3d9 100644 --- a/lib/remote-bitfield.js +++ b/lib/remote-bitfield.js @@ -149,6 +149,7 @@ module.exports = class RemoteBitfield { constructor () { this._pages = new BigSparseArray() this._segments = new BigSparseArray() + this._maxSegments = 0 } getBitfield (index) { @@ -177,6 +178,7 @@ module.exports = class RemoteBitfield { if (!p && val) { const k = Math.floor(i / PAGES_PER_SEGMENT) const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k)) + if (this._maxSegments <= k) this._maxSegments = k + 1 p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s)) } @@ -194,6 +196,7 @@ module.exports = class RemoteBitfield { if (!p && val) { const k = Math.floor(i / PAGES_PER_SEGMENT) const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k)) + if (this._maxSegments <= k) this._maxSegments = k + 1 p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s)) } @@ -213,7 +216,7 @@ module.exports = class RemoteBitfield { let j = position & (BITS_PER_SEGMENT - 1) let i = (position - j) / BITS_PER_SEGMENT - while (i < this._segments.maxLength) { + while (i < this._maxSegments) { const s = this._segments.get(i) let index = -1 @@ -281,6 +284,7 @@ module.exports = class RemoteBitfield { if (!p) { const k = Math.floor(i / PAGES_PER_SEGMENT) const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k)) + if (this._maxSegments <= k) this._maxSegments = k + 1 p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s)) } @@ -314,6 +318,7 @@ module.exports = class RemoteBitfield { if (!p) { const k = Math.floor(i / PAGES_PER_SEGMENT) const s = this._segments.get(k) || this._segments.set(k, new RemoteBitfieldSegment(k)) + if (this._maxSegments <= k) this._maxSegments = k + 1 p = this._pages.set(i, new RemoteBitfieldPage(i, new Uint32Array(WORDS_PER_PAGE), s)) }