forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
87 lines (71 loc) · 2.51 KB
/
types.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package types
import (
"fmt"
"sort"
yaml "gopkg.in/yaml.v2"
sdkerrors "github.com/JaTochNietDan/cosmos-sdk/types/errors"
)
// NewCapability returns a reference to a new Capability to be used as an
// actual capability.
func NewCapability(index uint64) *Capability {
return &Capability{Index: index}
}
// String returns the string representation of a Capability. The string contains
// the Capability's memory reference as the string is to be used in a composite
// key and to authenticate capabilities.
func (ck *Capability) String() string {
return fmt.Sprintf("Capability{%p, %d}", ck, ck.Index)
}
func NewOwner(module, name string) Owner {
return Owner{Module: module, Name: name}
}
// Key returns a composite key for an Owner.
func (o Owner) Key() string {
return fmt.Sprintf("%s/%s", o.Module, o.Name)
}
func (o Owner) String() string {
bz, _ := yaml.Marshal(o)
return string(bz)
}
func NewCapabilityOwners() *CapabilityOwners {
return &CapabilityOwners{Owners: make([]Owner, 0)}
}
// Set attempts to add a given owner to the CapabilityOwners. If the owner
// already exists, an error will be returned. Set runs in O(log n) average time
// and O(n) in the worst case.
func (co *CapabilityOwners) Set(owner Owner) error {
i, ok := co.Get(owner)
if ok {
// owner already exists at co.Owners[i]
return sdkerrors.Wrapf(ErrOwnerClaimed, owner.String())
}
// owner does not exist in the set of owners, so we insert at position i
co.Owners = append(co.Owners, Owner{}) // expand by 1 in amortized O(1) / O(n) worst case
copy(co.Owners[i+1:], co.Owners[i:])
co.Owners[i] = owner
return nil
}
// Remove removes a provided owner from the CapabilityOwners if it exists. If the
// owner does not exist, Remove is considered a no-op.
func (co *CapabilityOwners) Remove(owner Owner) {
if len(co.Owners) == 0 {
return
}
i, ok := co.Get(owner)
if ok {
// owner exists at co.Owners[i]
co.Owners = append(co.Owners[:i], co.Owners[i+1:]...)
}
}
// Get returns (i, true) of the provided owner in the CapabilityOwners if the
// owner exists, where i indicates the owner's index in the set. Otherwise
// (i, false) where i indicates where in the set the owner should be added.
func (co *CapabilityOwners) Get(owner Owner) (int, bool) {
// find smallest index s.t. co.Owners[i] >= owner in O(log n) time
i := sort.Search(len(co.Owners), func(i int) bool { return co.Owners[i].Key() >= owner.Key() })
if i < len(co.Owners) && co.Owners[i].Key() == owner.Key() {
// owner exists at co.Owners[i]
return i, true
}
return i, false
}