github.com/KYVENetwork/cometbft/v38@v38.0.3/libs/cmap/cmap.go (about)

     1  package cmap
     2  
     3  import (
     4  	cmtsync "github.com/KYVENetwork/cometbft/v38/libs/sync"
     5  )
     6  
     7  // CMap is a goroutine-safe map
     8  type CMap struct {
     9  	m map[string]interface{}
    10  	l cmtsync.Mutex
    11  }
    12  
    13  func NewCMap() *CMap {
    14  	return &CMap{
    15  		m: make(map[string]interface{}),
    16  	}
    17  }
    18  
    19  func (cm *CMap) Set(key string, value interface{}) {
    20  	cm.l.Lock()
    21  	cm.m[key] = value
    22  	cm.l.Unlock()
    23  }
    24  
    25  func (cm *CMap) Get(key string) interface{} {
    26  	cm.l.Lock()
    27  	val := cm.m[key]
    28  	cm.l.Unlock()
    29  	return val
    30  }
    31  
    32  func (cm *CMap) Has(key string) bool {
    33  	cm.l.Lock()
    34  	_, ok := cm.m[key]
    35  	cm.l.Unlock()
    36  	return ok
    37  }
    38  
    39  func (cm *CMap) Delete(key string) {
    40  	cm.l.Lock()
    41  	delete(cm.m, key)
    42  	cm.l.Unlock()
    43  }
    44  
    45  func (cm *CMap) Size() int {
    46  	cm.l.Lock()
    47  	size := len(cm.m)
    48  	cm.l.Unlock()
    49  	return size
    50  }
    51  
    52  func (cm *CMap) Clear() {
    53  	cm.l.Lock()
    54  	cm.m = make(map[string]interface{})
    55  	cm.l.Unlock()
    56  }
    57  
    58  func (cm *CMap) Keys() []string {
    59  	cm.l.Lock()
    60  
    61  	keys := make([]string, 0, len(cm.m))
    62  	for k := range cm.m {
    63  		keys = append(keys, k)
    64  	}
    65  	cm.l.Unlock()
    66  	return keys
    67  }
    68  
    69  func (cm *CMap) Values() []interface{} {
    70  	cm.l.Lock()
    71  	items := make([]interface{}, 0, len(cm.m))
    72  	for _, v := range cm.m {
    73  		items = append(items, v)
    74  	}
    75  	cm.l.Unlock()
    76  	return items
    77  }