github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/performance/kvbench/mem_store.go (about)

     1  // Copyright 2021 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package kvbench
    16  
    17  import "sync"
    18  
    19  type keyValStore interface {
    20  	get(key []byte) (val []byte, ok bool)
    21  	put(key, val []byte)
    22  	putMany(keys, vals [][]byte)
    23  	delete(key []byte)
    24  }
    25  
    26  type flushingKeyValStore interface {
    27  	keyValStore
    28  	flush()
    29  }
    30  
    31  type orderedKeyValStore interface {
    32  	keyValStore
    33  	getRange(low, hi []byte) (vals [][]byte)
    34  	deleteRange(low, hi []byte)
    35  }
    36  
    37  func newMemStore() keyValStore {
    38  	return memStore{
    39  		store: make(map[string][]byte),
    40  		mu:    &sync.RWMutex{},
    41  	}
    42  }
    43  
    44  type memStore struct {
    45  	store map[string][]byte
    46  	mu    *sync.RWMutex
    47  }
    48  
    49  var _ keyValStore = memStore{}
    50  
    51  func (m memStore) get(key []byte) (val []byte, ok bool) {
    52  	m.mu.RLock()
    53  	defer m.mu.RUnlock()
    54  
    55  	val, ok = m.store[string(key)]
    56  	return val, ok
    57  }
    58  
    59  func (m memStore) put(key, val []byte) {
    60  	m.mu.Lock()
    61  	defer m.mu.Unlock()
    62  
    63  	m.store[string(key)] = val
    64  }
    65  
    66  func (m memStore) putMany(keys, vals [][]byte) {
    67  	m.mu.Lock()
    68  	defer m.mu.Unlock()
    69  
    70  	for i := range keys {
    71  		m.store[string(keys[i])] = vals[i]
    72  	}
    73  }
    74  
    75  func (m memStore) delete(key []byte) {
    76  	m.mu.Lock()
    77  	defer m.mu.Unlock()
    78  
    79  	delete(m.store, string(key))
    80  }