github.com/codingfuture/orig-energi3@v0.8.4/swarm/storage/memstore.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2016 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 // memory storage layer for the package blockhash 19 20 package storage 21 22 import ( 23 "context" 24 25 lru "github.com/hashicorp/golang-lru" 26 ) 27 28 type MemStore struct { 29 cache *lru.Cache 30 disabled bool 31 } 32 33 //NewMemStore is instantiating a MemStore cache keeping all frequently requested 34 //chunks in the `cache` LRU cache. 35 func NewMemStore(params *StoreParams, _ *LDBStore) (m *MemStore) { 36 if params.CacheCapacity == 0 { 37 return &MemStore{ 38 disabled: true, 39 } 40 } 41 42 c, err := lru.New(int(params.CacheCapacity)) 43 if err != nil { 44 panic(err) 45 } 46 47 return &MemStore{ 48 cache: c, 49 } 50 } 51 52 // Has needed to implement SyncChunkStore 53 func (m *MemStore) Has(_ context.Context, addr Address) bool { 54 return m.cache.Contains(addr) 55 } 56 57 func (m *MemStore) Get(_ context.Context, addr Address) (Chunk, error) { 58 if m.disabled { 59 return nil, ErrChunkNotFound 60 } 61 62 c, ok := m.cache.Get(string(addr)) 63 if !ok { 64 return nil, ErrChunkNotFound 65 } 66 return c.(Chunk), nil 67 } 68 69 func (m *MemStore) Put(_ context.Context, c Chunk) error { 70 if m.disabled { 71 return nil 72 } 73 74 m.cache.Add(string(c.Address()), c) 75 return nil 76 } 77 78 func (m *MemStore) setCapacity(n int) { 79 if n <= 0 { 80 m.disabled = true 81 } else { 82 c, err := lru.New(n) 83 if err != nil { 84 panic(err) 85 } 86 87 *m = MemStore{ 88 cache: c, 89 } 90 } 91 } 92 93 func (s *MemStore) Close() {}