github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/swarm/storage/memstore.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:45</date> 10 //</624450120301154304> 11 12 13 //包块哈希的内存存储层 14 15 package storage 16 17 import ( 18 "context" 19 20 lru "github.com/hashicorp/golang-lru" 21 ) 22 23 type MemStore struct { 24 cache *lru.Cache 25 disabled bool 26 } 27 28 //newmemstore正在实例化memstore缓存,以保留所有经常请求的缓存 29 //“cache”lru缓存中的块。 30 func NewMemStore(params *StoreParams, _ *LDBStore) (m *MemStore) { 31 if params.CacheCapacity == 0 { 32 return &MemStore{ 33 disabled: true, 34 } 35 } 36 37 c, err := lru.New(int(params.CacheCapacity)) 38 if err != nil { 39 panic(err) 40 } 41 42 return &MemStore{ 43 cache: c, 44 } 45 } 46 47 func (m *MemStore) Get(_ context.Context, addr Address) (Chunk, error) { 48 if m.disabled { 49 return nil, ErrChunkNotFound 50 } 51 52 c, ok := m.cache.Get(string(addr)) 53 if !ok { 54 return nil, ErrChunkNotFound 55 } 56 return c.(Chunk), nil 57 } 58 59 func (m *MemStore) Put(_ context.Context, c Chunk) error { 60 if m.disabled { 61 return nil 62 } 63 64 m.cache.Add(string(c.Address()), c) 65 return nil 66 } 67 68 func (m *MemStore) setCapacity(n int) { 69 if n <= 0 { 70 m.disabled = true 71 } else { 72 c, err := lru.New(n) 73 if err != nil { 74 panic(err) 75 } 76 77 *m = MemStore{ 78 cache: c, 79 } 80 } 81 } 82 83 func (s *MemStore) Close() {} 84