-
Notifications
You must be signed in to change notification settings - Fork 38
/
storeutil.go
67 lines (60 loc) · 1.61 KB
/
storeutil.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package storeutil
import (
"bytes"
"fmt"
"io"
blocks "github.com/ipfs/go-block-format"
bstore "github.com/ipfs/go-ipfs-blockstore"
"github.com/ipfs/go-unixfsnode"
ipld "github.com/ipld/go-ipld-prime"
cidlink "github.com/ipld/go-ipld-prime/linking/cid"
)
// LinkSystemForBlockstore constructs an IPLD LinkSystem for a blockstore
func LinkSystemForBlockstore(bs bstore.Blockstore) ipld.LinkSystem {
lsys := cidlink.DefaultLinkSystem()
lsys.TrustedStorage = true
lsys.StorageReadOpener = func(lnkCtx ipld.LinkContext, lnk ipld.Link) (io.Reader, error) {
asCidLink, ok := lnk.(cidlink.Link)
if !ok {
return nil, fmt.Errorf("unsupported link type")
}
block, err := bs.Get(lnkCtx.Ctx, asCidLink.Cid)
if err != nil {
return nil, err
}
return bytes.NewBuffer(block.RawData()), nil
}
lsys.StorageWriteOpener = func(lnkCtx ipld.LinkContext) (io.Writer, ipld.BlockWriteCommitter, error) {
var buffer settableBuffer
committer := func(lnk ipld.Link) error {
asCidLink, ok := lnk.(cidlink.Link)
if !ok {
return fmt.Errorf("unsupported link type")
}
block, err := blocks.NewBlockWithCid(buffer.Bytes(), asCidLink.Cid)
if err != nil {
return err
}
return bs.Put(lnkCtx.Ctx, block)
}
return &buffer, committer, nil
}
unixfsnode.AddUnixFSReificationToLinkSystem(&lsys)
return lsys
}
type settableBuffer struct {
bytes.Buffer
didSetData bool
data []byte
}
func (sb *settableBuffer) SetBytes(data []byte) error {
sb.didSetData = true
sb.data = data
return nil
}
func (sb *settableBuffer) Bytes() []byte {
if sb.didSetData {
return sb.data
}
return sb.Buffer.Bytes()
}