proposal_storage.gno
2.02 Kb ยท 86 lines
1package commondao
2
3import (
4 "gno.land/p/nt/avl"
5 "gno.land/p/nt/seqid"
6)
7
8// ProposalStorage defines an interface for proposal storages.
9type ProposalStorage interface {
10 // Has checks if a proposal exists.
11 Has(id uint64) bool
12
13 // Get returns a proposal or nil when proposal doesn't exist.
14 Get(id uint64) *Proposal
15
16 // Add adds a proposal to the storage.
17 Add(*Proposal)
18
19 // Remove removes a proposal from the storage.
20 Remove(id uint64)
21
22 // Size returns the number of proposals that the storage contains.
23 Size() int
24
25 // Iterate iterates proposals.
26 Iterate(offset, count int, reverse bool, fn func(*Proposal) bool) bool
27}
28
29// NewProposalStorage creates a new proposal storage.
30func NewProposalStorage() ProposalStorage {
31 return &proposalStorage{avl.NewTree()}
32}
33
34type proposalStorage struct {
35 storage *avl.Tree // string(proposal ID) -> *Proposal
36}
37
38// Has checks if a proposal exists.
39func (s proposalStorage) Has(id uint64) bool {
40 return s.storage.Has(makeProposalKey(id))
41}
42
43// Get returns a proposal or nil when proposal doesn't exist.
44func (s proposalStorage) Get(id uint64) *Proposal {
45 if v, found := s.storage.Get(makeProposalKey(id)); found {
46 return v.(*Proposal)
47 }
48 return nil
49}
50
51// Add adds a proposal to the storage.
52func (s *proposalStorage) Add(p *Proposal) {
53 if p == nil {
54 return
55 }
56
57 s.storage.Set(makeProposalKey(p.ID()), p)
58}
59
60// Remove removes a proposal from the storage.
61func (s *proposalStorage) Remove(id uint64) {
62 s.storage.Remove(makeProposalKey(id))
63}
64
65// Size returns the number of proposals that the storage contains.
66func (s proposalStorage) Size() int {
67 return s.storage.Size()
68}
69
70// Iterate iterates proposals.
71func (s proposalStorage) Iterate(offset, count int, reverse bool, fn func(*Proposal) bool) bool {
72 if fn == nil {
73 return false
74 }
75
76 cb := func(_ string, v any) bool { return fn(v.(*Proposal)) }
77
78 if reverse {
79 return s.storage.ReverseIterateByOffset(offset, count, cb)
80 }
81 return s.storage.IterateByOffset(offset, count, cb)
82}
83
84func makeProposalKey(id uint64) string {
85 return seqid.ID(id).String()
86}