/
concurrent_debt_map.go
104 lines (79 loc) · 1.86 KB
/
concurrent_debt_map.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
102
103
104
/**
* @file
* @copyright defined in go-seele/LICENSE
*/
package core
import (
"sync"
"github.com/seeleteam/go-seele/common"
"github.com/seeleteam/go-seele/common/errors"
"github.com/seeleteam/go-seele/core/types"
)
var errDebtFull = errors.New("too many debts in to confirmed debt")
type ConcurrentDebtMap struct {
capacity int
lock sync.RWMutex
value map[common.Hash]*types.Debt
}
func NewConcurrentDebtMap(capacity int) *ConcurrentDebtMap {
return &ConcurrentDebtMap{
value: make(map[common.Hash]*types.Debt),
capacity: capacity,
lock: sync.RWMutex{},
}
}
func (m *ConcurrentDebtMap) count() int {
m.lock.RLock()
defer m.lock.RUnlock()
return len(m.value)
}
func (m *ConcurrentDebtMap) remove(hash common.Hash) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.value, hash)
}
// removeByValue remove debts by Debt
func (m *ConcurrentDebtMap) removeByValue(debt *types.Debt) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.value, debt.Hash)
}
func (m *ConcurrentDebtMap) add(debt *types.Debt) error {
m.lock.Lock()
defer m.lock.Unlock()
if len(m.value) >= m.capacity && m.value[debt.Hash] == nil {
return errDebtFull
}
m.value[debt.Hash] = debt
return nil
}
func (m *ConcurrentDebtMap) get(hash common.Hash) *types.Debt {
m.lock.RLock()
defer m.lock.RUnlock()
return m.value[hash]
}
func (m *ConcurrentDebtMap) has(hash common.Hash) bool {
m.lock.RLock()
defer m.lock.RUnlock()
return m.value[hash] != nil
}
func (m *ConcurrentDebtMap) items() map[common.Hash]*types.Debt {
tmp := make(map[common.Hash]*types.Debt)
m.lock.RLock()
defer m.lock.RUnlock()
for h, d := range m.value {
tmp[h] = d
}
return tmp
}
func (m *ConcurrentDebtMap) getList() []*types.Debt {
m.lock.RLock()
defer m.lock.RUnlock()
tmp := make([]*types.Debt, len(m.value))
i := 0
for _, d := range m.value {
tmp[i] = d
i++
}
return tmp
}