Skip to content

Commit

Permalink
Merge pull request #30 from superfly/resset-type-alias
Browse files Browse the repository at this point in the history
resset: allow type aliases as IDs
  • Loading branch information
btoews authored Aug 7, 2024
2 parents 371b593 + 683d767 commit 699743b
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions resset/resource_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import (
"golang.org/x/exp/slices"
)

type Integer interface {
uint | uint8 | uint16 | uint32 | uint64 | int | int8 | int16 | int32 | int64
type ID interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~string
}

// ZeroID gets the zero value (0, or "") for a resource. This is used to refer
// to an unspecified resource. For example, when creating a new app, you would
// check for app:0:c permission.
func ZeroID[ID Integer | string]() (ret ID) {
func ZeroID[I ID]() (ret I) {
return
}

Expand All @@ -33,10 +33,10 @@ func ZeroID[ID Integer | string]() (ret ID) {
// type myCaveat struct {
// Resources resset.ResourceSet[uint64]
// }
type ResourceSet[ID Integer | string | Prefix] map[ID]Action
type ResourceSet[I ID] map[I]Action

func New[ID Integer | string | Prefix](p Action, ids ...ID) ResourceSet[ID] {
ret := make(ResourceSet[ID], len(ids))
func New[I ID](p Action, ids ...I) ResourceSet[I] {
ret := make(ResourceSet[I], len(ids))

for _, id := range ids {
ret[id] = p
Expand All @@ -45,7 +45,7 @@ func New[ID Integer | string | Prefix](p Action, ids ...ID) ResourceSet[ID] {
return ret
}

func (rs ResourceSet[ID]) Prohibits(id *ID, action Action) error {
func (rs ResourceSet[I]) Prohibits(id *I, action Action) error {
if err := rs.validate(); err != nil {
return err
}
Expand All @@ -56,7 +56,7 @@ func (rs ResourceSet[ID]) Prohibits(id *ID, action Action) error {
var (
foundPerm = false
perm = ActionAll
zeroID ID
zeroID I
)

if zeroPerm, hasZero := rs[zeroID]; hasZero {
Expand Down Expand Up @@ -86,7 +86,7 @@ var _ msgpack.CustomEncoder = ResourceSet[uint64]{}
var _ msgpack.CustomEncoder = ResourceSet[int32]{}
var _ msgpack.CustomEncoder = ResourceSet[string]{}

func (rs ResourceSet[ID]) EncodeMsgpack(enc *msgpack.Encoder) error {
func (rs ResourceSet[I]) EncodeMsgpack(enc *msgpack.Encoder) error {
if err := enc.EncodeMapLen(len(rs)); err != nil {
return err
}
Expand Down Expand Up @@ -116,13 +116,13 @@ func (rs ResourceSet[ID]) validate() error {
return nil
}

func match[ID Integer | string | Prefix](a, b ID) bool {
m, isM := any(a).(matcher[ID])
func match[I ID](a, b I) bool {
m, isM := any(a).(matcher[I])
return a == b || (isM && m.Match(b))
}

type matcher[T any] interface {
Match(T) bool
type matcher[I any] interface {
Match(I) bool
}

type Prefix string
Expand Down

0 comments on commit 699743b

Please sign in to comment.