github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/swarm/state/inmemorystore.go (about)

     1  
     2  //此源码被清华学神尹成大魔王专业翻译分析并修改
     3  //尹成QQ77025077
     4  //尹成微信18510341407
     5  //尹成所在QQ群721929980
     6  //尹成邮箱 yinc13@mails.tsinghua.edu.cn
     7  //尹成毕业于清华大学,微软区块链领域全球最有价值专家
     8  //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
     9  //
    10  //
    11  //
    12  //
    13  //
    14  //
    15  //
    16  //
    17  //
    18  //
    19  //
    20  //
    21  //
    22  //
    23  //
    24  
    25  package state
    26  
    27  import (
    28  	"encoding"
    29  	"encoding/json"
    30  	"sync"
    31  )
    32  
    33  //
    34  //
    35  type InmemoryStore struct {
    36  	db map[string][]byte
    37  	mu sync.RWMutex
    38  }
    39  
    40  //
    41  func NewInmemoryStore() *InmemoryStore {
    42  	return &InmemoryStore{
    43  		db: make(map[string][]byte),
    44  	}
    45  }
    46  
    47  //
    48  //
    49  func (s *InmemoryStore) Get(key string, i interface{}) (err error) {
    50  	s.mu.RLock()
    51  	defer s.mu.RUnlock()
    52  
    53  	bytes, ok := s.db[key]
    54  	if !ok {
    55  		return ErrNotFound
    56  	}
    57  
    58  	unmarshaler, ok := i.(encoding.BinaryUnmarshaler)
    59  	if !ok {
    60  		return json.Unmarshal(bytes, i)
    61  	}
    62  
    63  	return unmarshaler.UnmarshalBinary(bytes)
    64  }
    65  
    66  //
    67  func (s *InmemoryStore) Put(key string, i interface{}) (err error) {
    68  	s.mu.Lock()
    69  	defer s.mu.Unlock()
    70  	bytes := []byte{}
    71  
    72  	marshaler, ok := i.(encoding.BinaryMarshaler)
    73  	if !ok {
    74  		if bytes, err = json.Marshal(i); err != nil {
    75  			return err
    76  		}
    77  	} else {
    78  		if bytes, err = marshaler.MarshalBinary(); err != nil {
    79  			return err
    80  		}
    81  	}
    82  
    83  	s.db[key] = bytes
    84  	return nil
    85  }
    86  
    87  //
    88  func (s *InmemoryStore) Delete(key string) (err error) {
    89  	s.mu.Lock()
    90  	defer s.mu.Unlock()
    91  
    92  	if _, ok := s.db[key]; !ok {
    93  		return ErrNotFound
    94  	}
    95  	delete(s.db, key)
    96  	return nil
    97  }
    98  
    99  //
   100  func (s *InmemoryStore) Close() error {
   101  	return nil
   102  }