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
|
// Copyright 2018 The dexon-consensus Authors
// This file is part of the dexon-consensus library.
//
// The dexon-consensus library is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// The dexon-consensus library is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the dexon-consensus library. If not, see
// <http://www.gnu.org/licenses/>.
package common
import (
"container/heap"
"sync"
)
type heightEventFn func(uint64)
type heightEvent struct {
h uint64
fn heightEventFn
}
// heightEvents implements a Min-Heap structure.
type heightEvents []heightEvent
func (h heightEvents) Len() int { return len(h) }
func (h heightEvents) Less(i, j int) bool { return h[i].h < h[j].h }
func (h heightEvents) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *heightEvents) Push(x interface{}) {
*h = append(*h, x.(heightEvent))
}
func (h *heightEvents) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
// Event implements the Observer pattern.
type Event struct {
heightEvents heightEvents
heightEventsLock sync.Mutex
}
// NewEvent creates a new event instance.
func NewEvent() *Event {
he := heightEvents{}
heap.Init(&he)
return &Event{
heightEvents: he,
}
}
// RegisterHeight to get notified on a specific height.
func (e *Event) RegisterHeight(h uint64, fn heightEventFn) {
e.heightEventsLock.Lock()
defer e.heightEventsLock.Unlock()
heap.Push(&e.heightEvents, heightEvent{
h: h,
fn: fn,
})
}
// NotifyHeight and trigger function callback.
func (e *Event) NotifyHeight(h uint64) {
fns := func() (fns []heightEventFn) {
e.heightEventsLock.Lock()
defer e.heightEventsLock.Unlock()
if len(e.heightEvents) == 0 {
return
}
for h >= e.heightEvents[0].h {
he := heap.Pop(&e.heightEvents).(heightEvent)
fns = append(fns, he.fn)
if len(e.heightEvents) == 0 {
return
}
}
return
}()
for _, fn := range fns {
fn(h)
}
}
// Reset clears all pending event
func (e *Event) Reset() {
e.heightEventsLock.Lock()
defer e.heightEventsLock.Unlock()
e.heightEvents = heightEvents{}
}
|