/
committees.go
75 lines (60 loc) · 1.79 KB
/
committees.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
package client
import (
"fmt"
"sync"
"github.com/goccy/go-json"
)
type Committee struct {
Index uinteger `json:"index"`
Slot uinteger `json:"slot"`
Validators []string `json:"validators"`
}
// Custom deserialization logic for Committee allows us to pool the validator
// slices for reuse. They're quite large, so this cuts down on allocations
// substantially.
var validatorSlicePool sync.Pool = sync.Pool{
New: func() any {
return make([]string, 0, 1024)
},
}
func (c *Committee) UnmarshalJSON(body []byte) error {
var committee map[string]*json.RawMessage
pooledSlice := validatorSlicePool.Get().([]string)
c.Validators = pooledSlice
// Partially parse the json
if err := json.Unmarshal(body, &committee); err != nil {
return fmt.Errorf("error unmarshalling committee json: %w", err)
}
// Parse each field
if err := json.Unmarshal(*committee["index"], &c.Index); err != nil {
return err
}
if err := json.Unmarshal(*committee["slot"], &c.Slot); err != nil {
return err
}
// Since c.Validators was preallocated, this will re-use a buffer if one was available.
if err := json.Unmarshal(*committee["validators"], &c.Validators); err != nil {
return err
}
return nil
}
func (c *CommitteesResponse) Count() int {
return len(c.Data)
}
func (c *CommitteesResponse) Index(idx int) uint64 {
return uint64(c.Data[idx].Index)
}
func (c *CommitteesResponse) Slot(idx int) uint64 {
return uint64(c.Data[idx].Slot)
}
func (c *CommitteesResponse) Validators(idx int) []string {
return c.Data[idx].Validators
}
func (c *CommitteesResponse) Release() {
for _, committee := range c.Data {
// Reset the slice length to 0 (capacity stays the same)
committee.Validators = committee.Validators[:0]
// Return the slice for reuse
validatorSlicePool.Put(committee.Validators)
}
}