-
Notifications
You must be signed in to change notification settings - Fork 0
/
txByHashMap.go
101 lines (82 loc) · 2.23 KB
/
txByHashMap.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package txcache
import (
"github.com/ThotaGopichandThota/gn-core3/core/atomic"
"github.com/ThotaGopichandThota/gn-storage/txcache/maps"
)
// txByHashMap is a new map-like structure for holding and accessing transactions by txHash
type txByHashMap struct {
backingMap *maps.ConcurrentMap
counter atomic.Counter
numBytes atomic.Counter
}
// newTxByHashMap creates a new TxByHashMap instance
func newTxByHashMap(nChunksHint uint32) *txByHashMap {
backingMap := maps.NewConcurrentMap(nChunksHint)
return &txByHashMap{
backingMap: backingMap,
}
}
// addTx adds a transaction to the map
func (txMap *txByHashMap) addTx(tx *WrappedTransaction) bool {
added := txMap.backingMap.SetIfAbsent(string(tx.TxHash), tx)
if added {
txMap.counter.Increment()
txMap.numBytes.Add(tx.Size)
}
return added
}
// removeTx removes a transaction from the map
func (txMap *txByHashMap) removeTx(txHash string) (*WrappedTransaction, bool) {
item, removed := txMap.backingMap.Remove(txHash)
if !removed {
return nil, false
}
tx, ok := item.(*WrappedTransaction)
if !ok {
return nil, false
}
if removed {
txMap.counter.Decrement()
txMap.numBytes.Subtract(tx.Size)
}
return tx, true
}
// getTx gets a transaction from the map
func (txMap *txByHashMap) getTx(txHash string) (*WrappedTransaction, bool) {
txUntyped, ok := txMap.backingMap.Get(txHash)
if !ok {
return nil, false
}
tx := txUntyped.(*WrappedTransaction)
return tx, true
}
// RemoveTxsBulk removes transactions, in bulk
func (txMap *txByHashMap) RemoveTxsBulk(txHashes [][]byte) uint32 {
numRemoved := uint32(0)
for _, txHash := range txHashes {
_, removed := txMap.removeTx(string(txHash))
if removed {
numRemoved++
}
}
return numRemoved
}
// forEach iterates over the senders
func (txMap *txByHashMap) forEach(function ForEachTransaction) {
txMap.backingMap.IterCb(func(key string, item interface{}) {
tx := item.(*WrappedTransaction)
function([]byte(key), tx)
})
}
func (txMap *txByHashMap) clear() {
txMap.backingMap.Clear()
txMap.counter.Set(0)
}
func (txMap *txByHashMap) keys() [][]byte {
keys := txMap.backingMap.Keys()
keysAsBytes := make([][]byte, len(keys))
for i := 0; i < len(keys); i++ {
keysAsBytes[i] = []byte(keys[i])
}
return keysAsBytes
}