@cryptotaxi247 / kubo / commits / 42514f2ed

feat(blockstore): implement blockstore

Brian Tiger Chow committed Sep 16, 2014 at 03:31 UTC 42514f2ed77eb9523b560c9d96ed0d493c69b2ee
2 files changed +102
bitswap/blockstore/blockstore.go new
+47
@@ -0,0 +1,47 @@
1 +package blockstore
2 +
3 +import (
4 + "errors"
5 +
6 + ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
7 +
8 + blocks "github.com/jbenet/go-ipfs/blocks"
9 + u "github.com/jbenet/go-ipfs/util"
10 +)
11 +
12 +var ValueTypeMismatch = errors.New("The retrieved value is not a Block")
13 +
14 +type Blockstore interface {
15 + Get(u.Key) (*blocks.Block, error)
16 + Put(blocks.Block) error
17 +}
18 +
19 +func NewBlockstore(d ds.Datastore) Blockstore {
20 + return &blockstore{
21 + datastore: d,
22 + }
23 +}
24 +
25 +type blockstore struct {
26 + datastore ds.Datastore
27 +}
28 +
29 +func (bs *blockstore) Get(k u.Key) (*blocks.Block, error) {
30 + maybeData, err := bs.datastore.Get(toDatastoreKey(k))
31 + if err != nil {
32 + return nil, err
33 + }
34 + bdata, ok := maybeData.([]byte)
35 + if !ok {
36 + return nil, ValueTypeMismatch
37 + }
38 + return blocks.NewBlock(bdata)
39 +}
40 +
41 +func (bs *blockstore) Put(block blocks.Block) error {
42 + return bs.datastore.Put(toDatastoreKey(block.Key()), block.Data)
43 +}
44 +
45 +func toDatastoreKey(k u.Key) ds.Key {
46 + return ds.NewKey(string(k))
47 +}
bitswap/blockstore/blockstore_test.go new
+55
@@ -0,0 +1,55 @@
1 +package blockstore
2 +
3 +import (
4 + "bytes"
5 + "testing"
6 +
7 + ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
8 + u "github.com/jbenet/go-ipfs/util"
9 + testutil "github.com/jbenet/go-ipfs/util/testutil"
10 +)
11 +
12 +// TODO(brian): TestGetReturnsNil
13 +
14 +func TestGetWhenKeyNotPresent(t *testing.T) {
15 + bs := NewBlockstore(ds.NewMapDatastore())
16 + _, err := bs.Get(u.Key("not present"))
17 +
18 + if err != nil {
19 + t.Log("As expected, block is not present")
20 + return
21 + }
22 + t.Fail()
23 +}
24 +
25 +func TestPutThenGetBlock(t *testing.T) {
26 + bs := NewBlockstore(ds.NewMapDatastore())
27 + block := testutil.NewBlockOrFail(t, "some data")
28 +
29 + err := bs.Put(block)
30 + if err != nil {
31 + t.Fatal(err)
32 + }
33 +
34 + blockFromBlockstore, err := bs.Get(block.Key())
35 + if err != nil {
36 + t.Fatal(err)
37 + }
38 + if !bytes.Equal(block.Data, blockFromBlockstore.Data) {
39 + t.Fail()
40 + }
41 +}
42 +
43 +func TestValueTypeMismatch(t *testing.T) {
44 + block := testutil.NewBlockOrFail(t, "some data")
45 +
46 + datastore := ds.NewMapDatastore()
47 + datastore.Put(toDatastoreKey(block.Key()), "data that isn't a block!")
48 +
49 + blockstore := NewBlockstore(datastore)
50 +
51 + _, err := blockstore.Get(block.Key())
52 + if err != ValueTypeMismatch {
53 + t.Fatal(err)
54 + }
55 +}