diff --git a/README.md b/README.md index dec30b78..74052576 100644 --- a/README.md +++ b/README.md @@ -313,7 +313,7 @@ The core will also gossip to peers it is connected to, that is no longer has the ```js { - diff: false // Returned `cleared` bytes object is null unless you enable this + diff: false // Return a `cleared` object counting how many blocks were actually cleared, e.g. { blocks: 1 }. Null unless you enable this } ``` diff --git a/lib/session-state.js b/lib/session-state.js index f5bf31f1..dd2b6d1f 100644 --- a/lib/session-state.js +++ b/lib/session-state.js @@ -616,6 +616,28 @@ class SessionState { } } + if (cleared !== null) { + // Count the blocks that actually had data, so the caller can tell how + // much was cleared. + const clearEnd = Math.min(end, this.length) + + if (this.isDefault()) { + for (let i = start; i < clearEnd; i++) { + if (this.core.bitfield.get(i)) cleared.blocks++ + } + } else { + const rx = this.storage.read() + const hasPromises = [] + for (let i = start; i < clearEnd; i++) hasPromises.push(rx.getBlock(i)) + rx.tryFlush() + + const had = await Promise.all(hasPromises) + for (const block of had) { + if (block !== null) cleared.blocks++ + } + } + } + if (end - start === 1) tx.deleteBlock(start) else tx.deleteBlockRange(start, end) diff --git a/test/clear.js b/test/clear.js index 4c1767ba..ac9b5d6d 100644 --- a/test/clear.js +++ b/test/clear.js @@ -181,13 +181,11 @@ test('clear blocks with diff option', async function (t) { const cleared = await core.clear(1337) t.is(cleared, null) - // todo: reenable bytes use api + const cleared2 = await core.clear(0, { diff: true }) + t.is(cleared2.blocks, 1, 'the stored block was cleared') - // const cleared2 = await core.clear(0, { diff: true }) - // t.ok(cleared2.blocks > 0) - - // const cleared3 = await core.clear(0, { diff: true }) - // t.is(cleared3.blocks, 0) + const cleared3 = await core.clear(0, { diff: true }) + t.is(cleared3.blocks, 0, 'the block was already cleared') await core.close() })