package lock import ( "sync" ) type Dict[K comparable, V any] struct { dict map[K]V lock sync.RWMutex } func NewDict[K comparable, V any]() *Dict[K, V] { return &Dict[K, V]{ dict: make(map[K]V), } } // Count get dict key count func (d *Dict[K, V]) Count() int { d.lock.RLock() defer d.lock.RUnlock() return len(d.dict) } // Keys get dict keys func (d *Dict[K, V]) Keys() []K { d.lock.RLock() defer d.lock.RUnlock() keys := make([]K, 0, len(d.dict)) for k := range d.dict { keys = append(keys, k) } return keys } // Set set k v to dict, overwrite old value if exists func (d *Dict[K, V]) Set(key K, value V) { d.lock.Lock() defer d.lock.Unlock() d.dict[key] = value } // Has if exists, return true func (d *Dict[K, V]) Has(key K) bool { d.lock.RLock() defer d.lock.RUnlock() _, exists := d.dict[key] return exists } // Get if exists, return value and true func (d *Dict[K, V]) Get(key K) (V, bool) { d.lock.RLock() defer d.lock.RUnlock() value, exists := d.dict[key] return value, exists } // Del if exists and del success, return true func (d *Dict[K, V]) Del(key K) bool { d.lock.Lock() defer d.lock.Unlock() _, exists := d.dict[key] delete(d.dict, key) return exists } // Remove if exists and remove success, return old value and true func (d *Dict[K, V]) Remove(key K) (V, bool) { d.lock.Lock() defer d.lock.Unlock() value, exists := d.dict[key] delete(d.dict, key) return value, exists } // SetIfNotExists if not exists and set success, return true func (d *Dict[K, V]) SetIfNotExists(key K, value V) bool { d.lock.Lock() defer d.lock.Unlock() _, exists := d.dict[key] if !exists { d.dict[key] = value return true } return false } // GetOrSetIfNotExists if key exists return old:true, or, set new value, and return new:false func (d *Dict[K, V]) GetOrSetIfNotExists(key K, new V) (V, bool) { d.lock.Lock() defer d.lock.Unlock() old, exists := d.dict[key] if !exists { d.dict[key] = new return new, false } return old, true } // Travel travels all dict keys and values func (d *Dict[K, V]) Travel(travel func(key K, value V) bool) { d.lock.RLock() defer d.lock.RUnlock() for key, value := range d.dict { cont := travel(key, value) if !cont { break } } } // Clear dict directly func (d *Dict[K, V]) Clear() { d.lock.Lock() defer d.lock.Unlock() d.dict = map[K]V{} } // Update replace dict directly func (d *Dict[K, V]) Update(dict map[K]V) { d.lock.Lock() defer d.lock.Unlock() d.dict = dict } // Replace replace dict directly and return old dict func (d *Dict[K, V]) Replace(dict map[K]V) map[K]V { d.lock.Lock() defer d.lock.Unlock() old := d.dict d.dict = dict return old } // Append dict directly func (d *Dict[K, V]) Append(dict map[K]V) { d.lock.Lock() defer d.lock.Unlock() for k, v := range dict { d.dict[k] = v } }