member_storage.gno
2.12 Kb ยท 72 lines
1package commondao
2
3import (
4 "gno.land/p/moul/addrset"
5)
6
7// MemberStorage defines an interface for member storages.
8type MemberStorage interface {
9 // Size returns the number of members in the storage.
10 Size() int
11
12 // Has checks if a member exists in the storage.
13 Has(address) bool
14
15 // Add adds a member to the storage.
16 // Returns true if the member is added, or false if it already existed.
17 Add(address) bool
18
19 // Remove removes a member from the storage.
20 // Returns true if member was removed, or false if it was not found.
21 Remove(address) bool
22
23 // Grouping returns member groups when supported.
24 // When nil is returned it means that grouping of members is not supported.
25 // Member groups can be used by implementations that require grouping users
26 // by roles or by tiers for example.
27 Grouping() MemberGrouping
28
29 // IterateByOffset iterates members starting at the given offset.
30 // The callback can return true to stop iteration.
31 IterateByOffset(offset, count int, fn func(address) bool)
32}
33
34// NewMemberStorage creates a new member storage.
35// Function returns a new member storage that doesn't support member groups.
36// This type of storage is useful when there is no need to group members.
37func NewMemberStorage() MemberStorage {
38 return &memberStorage{}
39}
40
41// NewMemberStorageWithGrouping a new member storage with support for member groups.
42// Member groups can be used by implementations that require grouping users by roles
43// or by tiers for example.
44func NewMemberStorageWithGrouping(options ...MemberGroupingOption) MemberStorage {
45 return &memberStorage{grouping: NewMemberGrouping(options...)}
46}
47
48type memberStorage struct {
49 addrset.Set
50
51 grouping MemberGrouping
52}
53
54// Grouping returns member groups.
55func (s memberStorage) Grouping() MemberGrouping {
56 return s.grouping
57}
58
59// CountStorageMembers returns the total number of members in the storage.
60// It counts all members in each group and the ones without group.
61func CountStorageMembers(s MemberStorage) int {
62 if s == nil {
63 return 0
64 }
65
66 c := s.Size()
67 s.Grouping().IterateByOffset(0, s.Grouping().Size(), func(g MemberGroup) bool {
68 c += g.Members().Size()
69 return false
70 })
71 return c
72}