diff --git a/lib/block-dependency-stream.js b/lib/block-dependency-stream.js index ddfd05f..a2e5684 100644 --- a/lib/block-dependency-stream.js +++ b/lib/block-dependency-stream.js @@ -8,6 +8,7 @@ module.exports = class BlockStream extends Readable { this.core = core this.db = db this.updates = updates + this.start = start this.end = end this.reverse = reverse === true @@ -23,26 +24,18 @@ module.exports = class BlockStream extends Readable { _update () { if (this._consumed > this.core.dependencies.length) return - const index = this.reverse ? this.core.dependencies.length - this._consumed : this._consumed - const offset = index === 0 ? 0 : this.core.dependencies[index - 1].length + const deps = this.core.dependencies - let end = 0 - let ptr = 0 + const index = findDependencyIndex(deps, this.end, this._consumed++, this.reverse) - if (this._consumed < this.core.dependencies.length) { - const dep = this.core.dependencies[this._consumed] - end = this.end === -1 ? dep.length : Math.min(this.end, dep.length) - ptr = dep.dataPointer - } else { - end = this.end === -1 ? Infinity : this.end - ptr = this.core.dataPointer - } - - this._consumed++ + const curr = deps[index] + const prev = deps[index - 1] - if (end === offset) return + const start = prev && prev.length > this.start ? prev.length : this.start + const end = curr && curr.length < this.end ? curr.length : this.end + const ptr = curr ? curr.dataPointer : this.core.dataPointer - this._makeStream(core.block(ptr, offset), core.block(ptr, end)) + this._makeStream(core.block(ptr, start), core.block(ptr, end)) } _predestroy () { @@ -105,3 +98,13 @@ module.exports = class BlockStream extends Readable { } function noop () {} + +function findDependencyIndex (deps, end, offset, reverse) { + if (!reverse) return offset + + for (let i = deps.length - offset; i > 0; i--) { + if (deps[i - 1].length <= end) return i + } + + return 0 +}