github.com/dotlike13/wemix30_go@v1.8.23/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  // Has needed to implement SyncChunkStore
    52  func (m *MemStore) Has(_ context.Context, addr Address) bool {
    53  	return m.cache.Contains(addr)
    54  }
    55  
    56  func (m *MemStore) Get(_ context.Context, addr Address) (Chunk, error) {
    57  	if m.disabled {
    58  		return nil, ErrChunkNotFound
    59  	}
    60  
    61  	c, ok := m.cache.Get(string(addr))
    62  	if !ok {
    63  		return nil, ErrChunkNotFound
    64  	}
    65  	return c.(Chunk), nil
    66  }
    67  
    68  func (m *MemStore) Put(_ context.Context, c Chunk) error {
    69  	if m.disabled {
    70  		return nil
    71  	}
    72  
    73  	m.cache.Add(string(c.Address()), c)
    74  	return nil
    75  }
    76  
    77  func (m *MemStore) setCapacity(n int) {
    78  	if n <= 0 {
    79  		m.disabled = true
    80  	} else {
    81  		c, err := lru.New(n)
    82  		if err != nil {
    83  			panic(err)
    84  		}
    85  
    86  		*m = MemStore{
    87  			cache: c,
    88  		}
    89  	}
    90  }
    91  
    92  func (s *MemStore) Close() {}