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