81 lines
1.9 KiB
Go
81 lines
1.9 KiB
Go
|
package blockstore
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
|
||
|
blocks "github.com/ipfs/go-block-format"
|
||
|
"github.com/ipfs/go-cid"
|
||
|
blockstore "github.com/ipfs/go-ipfs-blockstore"
|
||
|
)
|
||
|
|
||
|
type MemStore map[cid.Cid]blocks.Block
|
||
|
|
||
|
func (m MemStore) DeleteBlock(k cid.Cid) error {
|
||
|
delete(m, k)
|
||
|
return nil
|
||
|
}
|
||
|
func (m MemStore) Has(k cid.Cid) (bool, error) {
|
||
|
_, ok := m[k]
|
||
|
return ok, nil
|
||
|
}
|
||
|
func (m MemStore) Get(k cid.Cid) (blocks.Block, error) {
|
||
|
b, ok := m[k]
|
||
|
if !ok {
|
||
|
return nil, blockstore.ErrNotFound
|
||
|
}
|
||
|
return b, nil
|
||
|
}
|
||
|
|
||
|
// GetSize returns the CIDs mapped BlockSize
|
||
|
func (m MemStore) GetSize(k cid.Cid) (int, error) {
|
||
|
b, ok := m[k]
|
||
|
if !ok {
|
||
|
return 0, blockstore.ErrNotFound
|
||
|
}
|
||
|
return len(b.RawData()), nil
|
||
|
}
|
||
|
|
||
|
// Put puts a given block to the underlying datastore
|
||
|
func (m MemStore) Put(b blocks.Block) error {
|
||
|
// Convert to a basic block for safety, but try to reuse the existing
|
||
|
// block if it's already a basic block.
|
||
|
k := b.Cid()
|
||
|
if _, ok := b.(*blocks.BasicBlock); !ok {
|
||
|
// If we already have the block, abort.
|
||
|
if _, ok := m[k]; ok {
|
||
|
return nil
|
||
|
}
|
||
|
// the error is only for debugging.
|
||
|
b, _ = blocks.NewBlockWithCid(b.RawData(), b.Cid())
|
||
|
}
|
||
|
m[b.Cid()] = b
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// PutMany puts a slice of blocks at the same time using batching
|
||
|
// capabilities of the underlying datastore whenever possible.
|
||
|
func (m MemStore) PutMany(bs []blocks.Block) error {
|
||
|
for _, b := range bs {
|
||
|
_ = m.Put(b) // can't fail
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
// AllKeysChan returns a channel from which
|
||
|
// the CIDs in the Blockstore can be read. It should respect
|
||
|
// the given context, closing the channel if it becomes Done.
|
||
|
func (m MemStore) AllKeysChan(ctx context.Context) (<-chan cid.Cid, error) {
|
||
|
ch := make(chan cid.Cid, len(m))
|
||
|
for k := range m {
|
||
|
ch <- k
|
||
|
}
|
||
|
close(ch)
|
||
|
return ch, nil
|
||
|
}
|
||
|
|
||
|
// HashOnRead specifies if every read block should be
|
||
|
// rehashed to make sure it matches its CID.
|
||
|
func (m MemStore) HashOnRead(enabled bool) {
|
||
|
// no-op
|
||
|
}
|