Search Apps Documentation Source Content File Folder Download Copy Actions Download

permission_set.gno

1.32 Kb · 54 lines
 1package boards
 2
 3// PermissionSet defines a type to store any number of permissions.
 4type PermissionSet []uint64
 5
 6// NewPermissionSet creates a new PermissionSet containing the given permissions.
 7func NewPermissionSet(perms ...Permission) PermissionSet {
 8	if len(perms) == 0 {
 9		return nil
10	}
11
12	// Find max permission value to calculate slice size.
13	// This allows any number of permissions to be assigned in any order.
14	var max Permission
15	for _, p := range perms {
16		if p > max {
17			max = p
18		}
19	}
20
21	s := make(PermissionSet, int(max)/64+1)
22	for _, p := range perms {
23		// Calculate the index within the set where the permission should be defined.
24		// Each item in the set can contain 64 permissions, for example:
25		// - Item 0: permissions 0 to 63
26		// - Item 1: permissions 64 to 127
27		idx := int(p) / 64
28
29		// Turn on the bit that matches the permission, ranging from bit 0 to 63
30		s[idx] |= 1 << (uint(p) % 64)
31	}
32	return s
33}
34
35// Has checks if a permission is in the set.
36func (s PermissionSet) Has(p Permission) bool {
37	idx := int(p) / 64
38	if idx >= len(s) {
39		return false
40	}
41
42	// Check if the bit for the current permission is on
43	return s[idx]&(1<<(uint(p)%64)) != 0
44}
45
46// IsEmpty reports whether the set contains no permissions.
47func (s PermissionSet) IsEmpty() bool {
48	for _, v := range s {
49		if v != 0 {
50			return false
51		}
52	}
53	return true
54}