github.com/hdt3213/godis@v1.2.9/datastruct/dict/simple.go (about) 1 package dict 2 3 // SimpleDict wraps a map, it is not thread safe 4 type SimpleDict struct { 5 m map[string]interface{} 6 } 7 8 // MakeSimple makes a new map 9 func MakeSimple() *SimpleDict { 10 return &SimpleDict{ 11 m: make(map[string]interface{}), 12 } 13 } 14 15 // Get returns the binding value and whether the key is exist 16 func (dict *SimpleDict) Get(key string) (val interface{}, exists bool) { 17 val, ok := dict.m[key] 18 return val, ok 19 } 20 21 // Len returns the number of dict 22 func (dict *SimpleDict) Len() int { 23 if dict.m == nil { 24 panic("m is nil") 25 } 26 return len(dict.m) 27 } 28 29 // Put puts key value into dict and returns the number of new inserted key-value 30 func (dict *SimpleDict) Put(key string, val interface{}) (result int) { 31 _, existed := dict.m[key] 32 dict.m[key] = val 33 if existed { 34 return 0 35 } 36 return 1 37 } 38 39 // PutIfAbsent puts value if the key is not exists and returns the number of updated key-value 40 func (dict *SimpleDict) PutIfAbsent(key string, val interface{}) (result int) { 41 _, existed := dict.m[key] 42 if existed { 43 return 0 44 } 45 dict.m[key] = val 46 return 1 47 } 48 49 // PutIfExists puts value if the key is exist and returns the number of inserted key-value 50 func (dict *SimpleDict) PutIfExists(key string, val interface{}) (result int) { 51 _, existed := dict.m[key] 52 if existed { 53 dict.m[key] = val 54 return 1 55 } 56 return 0 57 } 58 59 // Remove removes the key and return the number of deleted key-value 60 func (dict *SimpleDict) Remove(key string) (result int) { 61 _, existed := dict.m[key] 62 delete(dict.m, key) 63 if existed { 64 return 1 65 } 66 return 0 67 } 68 69 // Keys returns all keys in dict 70 func (dict *SimpleDict) Keys() []string { 71 result := make([]string, len(dict.m)) 72 i := 0 73 for k := range dict.m { 74 result[i] = k 75 i++ 76 } 77 return result 78 } 79 80 // ForEach traversal the dict 81 func (dict *SimpleDict) ForEach(consumer Consumer) { 82 for k, v := range dict.m { 83 if !consumer(k, v) { 84 break 85 } 86 } 87 } 88 89 // RandomKeys randomly returns keys of the given number, may contain duplicated key 90 func (dict *SimpleDict) RandomKeys(limit int) []string { 91 result := make([]string, limit) 92 for i := 0; i < limit; i++ { 93 for k := range dict.m { 94 result[i] = k 95 break 96 } 97 } 98 return result 99 } 100 101 // RandomDistinctKeys randomly returns keys of the given number, won't contain duplicated key 102 func (dict *SimpleDict) RandomDistinctKeys(limit int) []string { 103 size := limit 104 if size > len(dict.m) { 105 size = len(dict.m) 106 } 107 result := make([]string, size) 108 i := 0 109 for k := range dict.m { 110 if i == size { 111 break 112 } 113 result[i] = k 114 i++ 115 } 116 return result 117 } 118 119 // Clear removes all keys in dict 120 func (dict *SimpleDict) Clear() { 121 *dict = *MakeSimple() 122 }