github.com/quantosnetwork/Quantos@v0.0.0-20220306172517-e20b28c5a29a/hashtable/htable.go (about) 1 package hashtable 2 3 import ( 4 "fmt" 5 "github.com/davecgh/go-spew/spew" 6 "github.com/quantosnetwork/Quantos/protocol" 7 "sync" 8 ) 9 10 type Key interface{} 11 type Value interface{} 12 13 type HashTable struct { 14 items map[int]Value 15 lock sync.RWMutex 16 } 17 18 func _hash(k Key) int { 19 key := fmt.Sprintf("%s", k) 20 h := 0 21 for i := 0; i < len(key); i++ { 22 h = 31*h + int(key[i]) 23 } 24 return h 25 } 26 27 func (ht *HashTable) Put(k Key, v Value) { 28 ht.lock.Lock() 29 defer ht.lock.Unlock() 30 i := _hash(k) 31 if ht.items == nil { 32 ht.items = make(map[int]Value) 33 } 34 ht.items[i] = v 35 36 } 37 38 func (ht *HashTable) Get(k Key) Value { 39 ht.lock.RLock() 40 defer ht.lock.RUnlock() 41 i := _hash(k) 42 return ht.items[i] 43 } 44 45 func (ht *HashTable) Remove(k Key) { 46 ht.lock.Lock() 47 defer ht.lock.Unlock() 48 i := _hash(k) 49 delete(ht.items, i) 50 } 51 52 func (ht *HashTable) Size() int { 53 ht.lock.RLock() 54 defer ht.lock.RUnlock() 55 return len(ht.items) 56 } 57 58 func (ht *HashTable) PrintHashTable() { 59 spew.Dump(ht) 60 } 61 62 func (ht *HashTable) ToBytes() ([]byte, error) { 63 return protocol.Marshal(ht.Items()) 64 } 65 66 func (ht *HashTable) Items() map[int]interface{} { 67 I := make(map[int]interface{}, ht.Size()) 68 for k, v := range ht.items { 69 I[k] = v 70 } 71 return I 72 }