Skip to content

Commit 39e91ef

Browse files
committed
batches
1 parent 3bbb004 commit 39e91ef

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

index.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,60 @@ const Monitor = require('./lib/monitor')
66

77
const DEFAULT_BLOCK_SIZE = 2 ** 16
88

9+
class HyperBlobsBatch {
10+
constructor (blobs) {
11+
this.blobs = blobs
12+
this.blocks = []
13+
this.bytes = 0
14+
}
15+
16+
async put (buffer) {
17+
if (!this.blobs.core.opened) await this.blobs.core.ready()
18+
19+
const blockSize = this.blobs.blockSize
20+
const result = {
21+
blockOffset: this.blobs.core.length + this.blocks.length,
22+
blockLength: 0,
23+
byteOffset: this.blobs.core.byteLength + this.bytes,
24+
byteLength: 0
25+
}
26+
27+
let offset = 0
28+
while (offset < buffer.byteLength) {
29+
const blk = buffer.subarray(offset, offset + blockSize)
30+
offset += blockSize
31+
32+
result.blockLength++
33+
result.byteLength += blk.byteLength
34+
this.bytes += blk.byteLength
35+
this.blocks.push(blk)
36+
}
37+
38+
return result
39+
}
40+
41+
async get (id) {
42+
if (id.blockOffset < this.blobs.core.length) {
43+
return this.blobs.get(id)
44+
}
45+
46+
const bufs = []
47+
48+
for (let i = id.blockOffset - this.blobs.core.length; i < id.blockOffset + id.blockLength; i++) {
49+
if (i >= this.blocks.length) return null
50+
bufs.push(this.blocks[i])
51+
}
52+
53+
return bufs.length === 1 ? bufs[0] : b4a.concat(bufs)
54+
}
55+
56+
async flush () {
57+
await this.core.append(this.blocks)
58+
this.blocks = []
59+
this.bytes = 0
60+
}
61+
}
62+
963
class Hyperblobs {
1064
constructor (core, opts = {}) {
1165
this.core = core
@@ -36,6 +90,10 @@ class Hyperblobs {
3690
return this.core.close()
3791
}
3892

93+
batch () {
94+
return new HyperBlobsBatch(this)
95+
}
96+
3997
snapshot () {
4098
return new Hyperblobs(this.core.snapshot())
4199
}

test/all.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,24 @@ test('monitor is removed from the Set on close', async (t) => {
376376
t.is(blobs._monitors.size, 0)
377377
})
378378

379+
test('basic batch', async (t) => {
380+
const core = new Hypercore(RAM)
381+
const blobs = new Hyperblobs(core)
382+
const batch = blobs.batch()
383+
384+
{
385+
const id = await batch.put(Buffer.from('hello world'))
386+
const buf = await batch.get(id)
387+
t.alike(buf, Buffer.from('hello world'))
388+
}
389+
390+
{
391+
const id = await batch.put(Buffer.from('hej verden'))
392+
const buf = await batch.get(id)
393+
t.alike(buf, Buffer.from('hej verden'))
394+
}
395+
})
396+
379397
async function createPair () {
380398
const a = new Hypercore(RAM)
381399
await a.ready()

0 commit comments

Comments
 (0)