member_storage.gno

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