github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/blocks/blockstore/write_cache.go (about) 1 package blockstore 2 3 import ( 4 "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/hashicorp/golang-lru" 5 context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" 6 "github.com/ipfs/go-ipfs/blocks" 7 key "github.com/ipfs/go-ipfs/blocks/key" 8 ) 9 10 // WriteCached returns a blockstore that caches up to |size| unique writes (bs.Put). 11 func WriteCached(bs Blockstore, size int) (Blockstore, error) { 12 c, err := lru.New(size) 13 if err != nil { 14 return nil, err 15 } 16 return &writecache{blockstore: bs, cache: c}, nil 17 } 18 19 type writecache struct { 20 cache *lru.Cache // pointer b/c Cache contains a Mutex as value (complicates copying) 21 blockstore Blockstore 22 } 23 24 func (w *writecache) DeleteBlock(k key.Key) error { 25 w.cache.Remove(k) 26 return w.blockstore.DeleteBlock(k) 27 } 28 29 func (w *writecache) Has(k key.Key) (bool, error) { 30 if _, ok := w.cache.Get(k); ok { 31 return true, nil 32 } 33 return w.blockstore.Has(k) 34 } 35 36 func (w *writecache) Get(k key.Key) (*blocks.Block, error) { 37 return w.blockstore.Get(k) 38 } 39 40 func (w *writecache) Put(b *blocks.Block) error { 41 if _, ok := w.cache.Get(b.Key()); ok { 42 return nil 43 } 44 w.cache.Add(b.Key(), struct{}{}) 45 return w.blockstore.Put(b) 46 } 47 48 func (w *writecache) PutMany(bs []*blocks.Block) error { 49 var good []*blocks.Block 50 for _, b := range bs { 51 if _, ok := w.cache.Get(b.Key()); !ok { 52 good = append(good, b) 53 } 54 } 55 return w.blockstore.PutMany(good) 56 } 57 58 func (w *writecache) AllKeysChan(ctx context.Context) (<-chan key.Key, error) { 59 return w.blockstore.AllKeysChan(ctx) 60 }