-
Notifications
You must be signed in to change notification settings - Fork 16
/
memory.ts
51 lines (40 loc) · 1.31 KB
/
memory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { NotFoundError } from 'interface-store'
import { base32 } from 'multiformats/bases/base32'
import { CID } from 'multiformats/cid'
import * as raw from 'multiformats/codecs/raw'
import * as Digest from 'multiformats/hashes/digest'
import { BaseBlockstore } from './base.js'
import type { Pair } from 'interface-blockstore'
import type { Await, AwaitIterable } from 'interface-store'
export class MemoryBlockstore extends BaseBlockstore {
private readonly data: Map<string, Uint8Array>
constructor () {
super()
this.data = new Map()
}
put (key: CID, val: Uint8Array): Await<CID> { // eslint-disable-line require-await
this.data.set(base32.encode(key.multihash.bytes), val)
return key
}
get (key: CID): Await<Uint8Array> {
const buf = this.data.get(base32.encode(key.multihash.bytes))
if (buf == null) {
throw new NotFoundError()
}
return buf
}
has (key: CID): Await<boolean> {
return this.data.has(base32.encode(key.multihash.bytes))
}
async delete (key: CID): Promise<void> {
this.data.delete(base32.encode(key.multihash.bytes))
}
async * getAll (): AwaitIterable<Pair> {
for (const [key, value] of this.data.entries()) {
yield {
cid: CID.createV1(raw.code, Digest.decode(base32.decode(key))),
block: value
}
}
}
}