github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/container/slice_map.go (about)

     1  package container
     2  
     3  type mapNode[K comparable, V any] struct {
     4  	Key     K
     5  	Value   V
     6  	StoreOk bool
     7  }
     8  
     9  type SliceMap[K comparable, V any] struct {
    10  	nodes  []mapNode[K, V]
    11  	length int
    12  }
    13  
    14  func NewSliceMap[K comparable, V any](size int) *SliceMap[K, V] {
    15  	return &SliceMap[K, V]{
    16  		nodes: make([]mapNode[K, V], size),
    17  	}
    18  }
    19  
    20  func (m *SliceMap[K, V]) Reset() {
    21  	m.length = 0
    22  	m.nodes = m.nodes[:0]
    23  }
    24  
    25  func (m *SliceMap[K, V]) Store(key K, value V) {
    26  	for index, node := range m.nodes {
    27  		if !node.StoreOk {
    28  			node.Key = key
    29  			node.Value = value
    30  			node.StoreOk = true
    31  			m.nodes[index] = node
    32  			m.length++
    33  			return
    34  		} else if node.StoreOk && node.Key == key {
    35  			node.Value = value
    36  			m.nodes[index] = node
    37  			return
    38  		}
    39  	}
    40  	m.nodes = append(m.nodes, mapNode[K, V]{
    41  		Key:     key,
    42  		Value:   value,
    43  		StoreOk: true,
    44  	})
    45  	m.length++
    46  }
    47  
    48  func (m *SliceMap[K, V]) Load(key K) V {
    49  	v, _ := m.LoadOk(key)
    50  	return v
    51  }
    52  
    53  func (m *SliceMap[K, V]) LoadOk(key K) (V, bool) {
    54  	for _, node := range m.nodes {
    55  		if node.StoreOk && node.Key == key {
    56  			return node.Value, true
    57  		}
    58  	}
    59  	return *new(V), false
    60  }
    61  
    62  func (m *SliceMap[K, V]) Delete(key K) {
    63  	for index, node := range m.nodes {
    64  		if node.StoreOk && node.Key == key {
    65  			node.StoreOk = false
    66  			node.Key = *new(K)
    67  			node.Value = *new(V)
    68  			m.nodes[index] = node
    69  			m.length--
    70  			return
    71  		}
    72  	}
    73  }
    74  
    75  func (m *SliceMap[K, V]) Range(fn func(K, V) (next bool)) {
    76  	var count int
    77  	for _, node := range m.nodes {
    78  		if node.StoreOk && count <= m.length {
    79  			count++
    80  			if !fn(node.Key, node.Value) {
    81  				return
    82  			}
    83  		}
    84  	}
    85  }
    86  
    87  func (m *SliceMap[K, V]) Len() int {
    88  	return m.length
    89  }
    90  
    91  func (m *SliceMap[K, V]) Cap() int {
    92  	return len(m.nodes)
    93  }