forked from ipfs/go-graphsync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
teststore.go
39 lines (35 loc) · 992 Bytes
/
teststore.go
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
package testutil
import (
"bytes"
"fmt"
"io"
"sync"
ipld "github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
)
// NewTestStore provides a loader and storer for the given in memory link -> byte data map
func NewTestStore(blocksWritten map[ipld.Link][]byte) ipld.LinkSystem {
var storeLk sync.RWMutex
lsys := cidlink.DefaultLinkSystem()
lsys.TrustedStorage = true
lsys.StorageWriteOpener = func(lnkCtx ipld.LinkContext) (io.Writer, ipld.BlockWriteCommitter, error) {
var buffer bytes.Buffer
committer := func(lnk ipld.Link) error {
storeLk.Lock()
blocksWritten[lnk] = buffer.Bytes()
storeLk.Unlock()
return nil
}
return &buffer, committer, nil
}
lsys.StorageReadOpener = func(lnkCtx ipld.LinkContext, lnk ipld.Link) (io.Reader, error) {
storeLk.RLock()
data, ok := blocksWritten[lnk]
storeLk.RUnlock()
if ok {
return bytes.NewReader(data), nil
}
return nil, fmt.Errorf("unable to load block")
}
return lsys
}