@@ -18,14 +18,14 @@ import (
18
18
type batch [H header.Header [H ]] struct {
19
19
lk sync.RWMutex
20
20
heights map [string ]uint64
21
- headers [ ]H
21
+ headers map [ uint64 ]H
22
22
}
23
23
24
24
// newBatch creates the batch with the given pre-allocated size.
25
25
func newBatch [H header.Header [H ]](size int ) * batch [H ] {
26
26
return & batch [H ]{
27
27
heights : make (map [string ]uint64 , size ),
28
- headers : make ([] H , 0 , size ),
28
+ headers : make (map [ uint64 ] H , size ),
29
29
}
30
30
}
31
31
@@ -40,7 +40,7 @@ func (b *batch[H]) Len() int {
40
40
func (b * batch [H ]) GetAll () []H {
41
41
b .lk .RLock ()
42
42
defer b .lk .RUnlock ()
43
- return b .headers
43
+ return slices . Collect ( maps . Values ( b .headers ))
44
44
}
45
45
46
46
// Get returns a header by its hash.
@@ -53,44 +53,22 @@ func (b *batch[H]) Get(hash header.Hash) H {
53
53
return zero
54
54
}
55
55
56
- return b .getByHeight ( height )
56
+ return b .headers [ height ]
57
57
}
58
58
59
59
// GetByHeight returns a header by its height.
60
60
func (b * batch [H ]) GetByHeight (height uint64 ) H {
61
61
b .lk .RLock ()
62
62
defer b .lk .RUnlock ()
63
- return b .getByHeight (height )
64
- }
65
-
66
- func (b * batch [H ]) getByHeight (height uint64 ) H {
67
- var (
68
- ln = uint64 (len (b .headers ))
69
- zero H
70
- )
71
- if ln == 0 {
72
- return zero
73
- }
74
-
75
- head := b .headers [ln - 1 ].Height ()
76
- base := head - ln
77
- if height > head || height <= base {
78
- return zero
79
- }
80
-
81
- h := b .headers [height - base - 1 ]
82
- if h .Height () == height {
83
- return h
84
- }
85
- return zero
63
+ return b .headers [height ]
86
64
}
87
65
88
66
// Append appends new headers to the batch.
89
67
func (b * batch [H ]) Append (headers ... H ) {
90
68
b .lk .Lock ()
91
69
defer b .lk .Unlock ()
92
70
for _ , h := range headers {
93
- b .headers = append ( b . headers , h )
71
+ b .headers [ h . Height ()] = h
94
72
b .heights [h .Hash ().String ()] = h .Height ()
95
73
}
96
74
}
@@ -111,9 +89,7 @@ func (b *batch[H]) DeleteRange(from, to uint64) {
111
89
maps .DeleteFunc (b .heights , func (_ string , height uint64 ) bool {
112
90
return from <= height && height < to
113
91
})
114
-
115
- b .headers = slices .DeleteFunc (b .headers , func (h H ) bool {
116
- height := h .Height ()
92
+ maps .DeleteFunc (b .headers , func (height uint64 , _ H ) bool {
117
93
return from <= height && height < to
118
94
})
119
95
}
@@ -122,8 +98,10 @@ func (b *batch[H]) DeleteRange(from, to uint64) {
122
98
func (b * batch [H ]) Reset () {
123
99
b .lk .Lock ()
124
100
defer b .lk .Unlock ()
125
- b .headers = b .headers [:0 ]
126
101
for k := range b .heights {
127
102
delete (b .heights , k )
128
103
}
104
+ for k := range b .headers {
105
+ delete (b .headers , k )
106
+ }
129
107
}
0 commit comments