blockstore.go 894 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package blockstore

import (
	"errors"

	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

	blocks "github.com/jbenet/go-ipfs/blocks"
	u "github.com/jbenet/go-ipfs/util"
)

var ValueTypeMismatch = errors.New("The retrieved value is not a Block")

type Blockstore interface {
	Get(u.Key) (*blocks.Block, error)
16
	Put(*blocks.Block) error
17 18 19 20 21 22 23 24 25 26 27 28 29
}

func NewBlockstore(d ds.Datastore) Blockstore {
	return &blockstore{
		datastore: d,
	}
}

type blockstore struct {
	datastore ds.Datastore
}

func (bs *blockstore) Get(k u.Key) (*blocks.Block, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
	maybeData, err := bs.datastore.Get(k.DsKey())
31 32 33 34 35 36 37
	if err != nil {
		return nil, err
	}
	bdata, ok := maybeData.([]byte)
	if !ok {
		return nil, ValueTypeMismatch
	}
38
	return blocks.NewBlock(bdata), nil
39 40
}

41
func (bs *blockstore) Put(block *blocks.Block) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	return bs.datastore.Put(block.Key().DsKey(), block.Data)
43
}