github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/blockstore/blockstore.go (about) 1 // package blockstore implements a thin wrapper over a datastore, giving a 2 // clean interface for Getting and Putting block objects. 3 package blockstore 4 5 import ( 6 "errors" 7 8 ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore" 9 10 mh "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multihash" 11 blocks "github.com/jbenet/go-ipfs/blocks" 12 u "github.com/jbenet/go-ipfs/util" 13 ) 14 15 var ValueTypeMismatch = errors.New("The retrieved value is not a Block") 16 17 type Blockstore interface { 18 Get(u.Key) (*blocks.Block, error) 19 Put(*blocks.Block) error 20 } 21 22 func NewBlockstore(d ds.ThreadSafeDatastore) Blockstore { 23 return &blockstore{ 24 datastore: d, 25 } 26 } 27 28 type blockstore struct { 29 datastore ds.ThreadSafeDatastore 30 } 31 32 func (bs *blockstore) Get(k u.Key) (*blocks.Block, error) { 33 maybeData, err := bs.datastore.Get(k.DsKey()) 34 if err != nil { 35 return nil, err 36 } 37 bdata, ok := maybeData.([]byte) 38 if !ok { 39 return nil, ValueTypeMismatch 40 } 41 42 return blocks.NewBlockWithHash(bdata, mh.Multihash(k)) 43 } 44 45 func (bs *blockstore) Put(block *blocks.Block) error { 46 return bs.datastore.Put(block.Key().DsKey(), block.Data) 47 }