Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a cidlink.Memory storage option #266

Merged
merged 2 commits into from
Oct 14, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions linking/cid/memorystorage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cidlink

import (
"bytes"
"fmt"
"io"
"os"

"github.com/ipld/go-ipld-prime/datamodel"
"github.com/ipld/go-ipld-prime/linking"
)

// Memory is a simple in-memory storage for cidlinks. It's the same as `storage.Memory`
// but uses typical multihash semantics used when reading/writing cidlinks.
willscott marked this conversation as resolved.
Show resolved Hide resolved
type Memory struct {
Bag map[string][]byte
}

func (store *Memory) beInitialized() {
if store.Bag != nil {
return
}
store.Bag = make(map[string][]byte)
}

func (store *Memory) OpenRead(lnkCtx linking.LinkContext, lnk datamodel.Link) (io.Reader, error) {
store.beInitialized()
cl, ok := lnk.(Link)
if !ok {
return nil, fmt.Errorf("incompatible link type: %T", lnk)
}
data, exists := store.Bag[string(cl.Hash())]
if !exists {
return nil, os.ErrNotExist
}
return bytes.NewReader(data), nil
}

func (store *Memory) OpenWrite(lnkCtx linking.LinkContext) (io.Writer, linking.BlockWriteCommitter, error) {
store.beInitialized()
buf := bytes.Buffer{}
return &buf, func(lnk datamodel.Link) error {
cl, ok := lnk.(Link)
if !ok {
return fmt.Errorf("incompatible link type: %T", lnk)
}

store.Bag[string(cl.Hash())] = buf.Bytes()
return nil
}, nil
}