proposal_storage.gno
1.38 Kb · 57 lines
1package commondao
2
3import (
4 "gno.land/p/nt/bptree/v0"
5 "gno.land/p/nt/seqid/v0"
6)
7
8// newProposalStorage creates a new proposal storage.
9func newProposalStorage() *proposalStorage {
10 return &proposalStorage{bptree.NewBPTree32()}
11}
12
13// proposalStorage stores proposals indexed by ID.
14type proposalStorage struct {
15 storage *bptree.BPTree // string(proposal ID) -> *Proposal
16}
17
18// Get returns a proposal or nil when proposal doesn't exist.
19func (s proposalStorage) Get(id uint64) *Proposal {
20 if v := s.storage.Get(makeProposalKey(id)); v != nil {
21 return v.(*Proposal)
22 }
23 return nil
24}
25
26// Add adds a proposal to the storage.
27func (s *proposalStorage) Add(p *Proposal) {
28 if p == nil {
29 return
30 }
31
32 s.storage.Set(makeProposalKey(p.ID()), p)
33}
34
35// Remove removes a proposal from the storage.
36func (s *proposalStorage) Remove(id uint64) {
37 s.storage.Remove(makeProposalKey(id))
38}
39
40// Size returns the number of proposals that the storage contains.
41func (s proposalStorage) Size() int {
42 return s.storage.Size()
43}
44
45// Iterate iterates proposals.
46func (s proposalStorage) Iterate(offset, count int, reverse bool, fn func(*Proposal) bool) bool {
47 cb := func(_ string, v any) bool { return fn(v.(*Proposal)) }
48
49 if reverse {
50 return s.storage.ReverseIterateByOffset(offset, count, cb)
51 }
52 return s.storage.IterateByOffset(offset, count, cb)
53}
54
55func makeProposalKey(id uint64) string {
56 return seqid.ID(id).String()
57}