write_cache.go 1.27 KB
Newer Older
1 2 3
package blockstore

import (
4 5 6 7
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	"github.com/ipfs/go-ipfs/blocks"
	u "github.com/ipfs/go-ipfs/util"
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
)

// WriteCached returns a blockstore that caches up to |size| unique writes (bs.Put).
func WriteCached(bs Blockstore, size int) (Blockstore, error) {
	c, err := lru.New(size)
	if err != nil {
		return nil, err
	}
	return &writecache{blockstore: bs, cache: c}, nil
}

type writecache struct {
	cache      *lru.Cache // pointer b/c Cache contains a Mutex as value (complicates copying)
	blockstore Blockstore
}

func (w *writecache) DeleteBlock(k u.Key) error {
	w.cache.Remove(k)
	return w.blockstore.DeleteBlock(k)
}

func (w *writecache) Has(k u.Key) (bool, error) {
	if _, ok := w.cache.Get(k); ok {
		return true, nil
	}
	return w.blockstore.Has(k)
}

func (w *writecache) Get(k u.Key) (*blocks.Block, error) {
	return w.blockstore.Get(k)
}

func (w *writecache) Put(b *blocks.Block) error {
	if _, ok := w.cache.Get(b.Key()); ok {
		return nil
	}
	w.cache.Add(b.Key(), struct{}{})
	return w.blockstore.Put(b)
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47

48
func (w *writecache) AllKeysChan(ctx context.Context) (<-chan u.Key, error) {
49
	return w.blockstore.AllKeysChan(ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
50
}