github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/xcontainer/maps/string_key_hash_map.go (about) 1 package maps 2 3 import ( 4 "hash/crc32" 5 "sync" 6 ) 7 8 type StringKeyHashMap struct { 9 shard uint32 10 mus []sync.RWMutex 11 ms []map[string]interface{} 12 hashFn func(key string) uint32 13 } 14 15 func NewStringKeyHashMap(shard uint32, fn func(key string) uint32) *StringKeyHashMap { 16 ms := make([]map[string]interface{}, shard) 17 for i := 0; i < int(shard); i++ { 18 ms[i] = make(map[string]interface{}) 19 } 20 if fn == nil { 21 fn = func(key string) uint32 { return crc32.ChecksumIEEE([]byte(key)) } 22 } 23 return &StringKeyHashMap{ 24 shard: shard, 25 mus: make([]sync.RWMutex, shard), 26 ms: ms, 27 hashFn: fn, 28 } 29 } 30 31 func (m *StringKeyHashMap) hashKey(key string) uint32 { 32 return m.hashFn(key) % m.shard 33 } 34 35 func (m *StringKeyHashMap) Set(key string, val interface{}) { 36 h := m.hashKey(key) 37 m.mus[h].Lock() 38 m.ms[h][key] = val 39 m.mus[h].Unlock() 40 } 41 42 func (m *StringKeyHashMap) GetOk(key string) (interface{}, bool) { 43 h := m.hashKey(key) 44 m.mus[h].RLock() 45 val, ok := m.ms[h][key] 46 m.mus[h].RUnlock() 47 return val, ok 48 } 49 50 func (m *StringKeyHashMap) Remove(key string) { 51 h := m.hashKey(key) 52 m.mus[h].Lock() 53 if _, ok := m.ms[h][key]; ok { 54 delete(m.ms[h], key) 55 } 56 m.mus[h].Unlock() 57 } 58 59 func (m *StringKeyHashMap) RemoveAll() { 60 newM := NewStringKeyHashMap(m.shard, m.hashFn) 61 *m = *newM 62 }