github.com/saintwish/kv@v1.0.4/kv1s/shard.go (about)

     1  package kv1s
     2  
     3  // A key, value resizeable cache using a modified swiss map.
     4  
     5  import (
     6  	"sync"
     7  
     8  	"github.com/saintwish/kv/swiss"
     9  )
    10  
    11  //used internally
    12  type shard[K comparable, V any] struct {
    13  	Map *swiss.Map[K, V]
    14  	*sync.RWMutex //mutex
    15  }
    16  
    17  func newShard[K comparable, V any](size uint64, count uint64) shard[K, V] {
    18  	return shard[K, V] {
    19  		Map: swiss.NewMap[K, V]( uint32(size/count) ),
    20  		RWMutex: &sync.RWMutex{},
    21  	}
    22  }
    23  
    24  func (m shard[K, V]) has(key K) bool {
    25  	m.RLock()
    26  
    27  	ok := m.Map.Has(key)
    28  
    29  	m.RUnlock()
    30  
    31  	return ok
    32  }
    33  
    34  func (m shard[K, V]) getHas(key K) (val V, ok bool) {
    35  	m.RLock()
    36  
    37  	ok, val = m.Map.GetHas(key)
    38  
    39  	m.RUnlock()
    40  
    41  	return
    42  }
    43  
    44  func (m shard[K, V]) get(key K) V {
    45  	m.RLock()
    46  
    47  	val := m.Map.Get(key)
    48  
    49  	m.RUnlock()
    50  
    51  	return val
    52  }
    53  
    54  /*--------
    55  	Other functions
    56  ----------*/
    57  func (m shard[K, V]) set(key K, val V) {
    58  	m.Lock()
    59  
    60  	m.Map.Set(key, val)
    61  
    62  	m.Unlock()
    63  }
    64  
    65  func (m shard[K, V]) update(key K, val V) {
    66  	m.Lock()
    67  
    68  	if ok := m.Map.Has(key); ok {
    69  		m.Map.Set(key, val)
    70  	}
    71  
    72  	m.Unlock()
    73  }
    74  
    75  func (m shard[K, V]) delete(key K) bool {
    76  	m.Lock()
    77  
    78  	ok,_ := m.Map.Delete(key)
    79  
    80  	m.Unlock()
    81  
    82  	return ok
    83  }
    84  
    85  func (m shard[K, V]) deleteCallback(key K, callback func(K, V)) bool {
    86  	m.Lock()
    87  
    88  	ok, val := m.Map.Delete(key)
    89  	callback(key, val)
    90  
    91  	m.Unlock()
    92  
    93  	return ok
    94  }
    95  
    96  func (m shard[K, V]) clear() {
    97  	m.Map.Clear()
    98  }
    99  
   100  func (m shard[K, V]) flush(callback func(K, V)) {
   101  	m.Lock()
   102  
   103  	m.Map.Iter(func(key K, val V) (stop bool) {
   104  		callback(key, val)
   105  		m.Map.Delete(key)
   106  		
   107  		if stop {
   108  			m.Unlock()
   109  			return
   110  		}
   111  
   112  		return
   113  	})
   114  
   115  	m.Unlock()
   116  }