3
0

Add slice.UInt64s, helper type

Type properly encodes slice of uint64s as JSON array of strings
This commit is contained in:
Denis Arh
2022-07-13 14:18:45 +02:00
parent 39046c52d0
commit af077b0edd
3 changed files with 78 additions and 7 deletions

View File

@@ -1,17 +1,20 @@
package rbac
import "sort"
import (
"github.com/cortezaproject/corteza-server/pkg/slice"
"sort"
)
type (
resolution string
Trace struct {
Resource string `json:"resource"`
Operation string `json:"operation"`
Access Access `json:"access"`
Roles []uint64 `json:"roles"`
Rules []*Rule `json:"rules,omitempty"`
Resolution resolution `json:"resolution,omitempty"`
Resource string `json:"resource"`
Operation string `json:"operation"`
Access Access `json:"access"`
Roles slice.UInt64s `json:"roles"`
Rules []*Rule `json:"rules,omitempty"`
Resolution resolution `json:"resolution,omitempty"`
}
)

View File

@@ -1,5 +1,16 @@
package slice
import (
"bytes"
"strconv"
)
type (
// UInt64s represents slice of uint64 with some extra powers:
// - encodes (JSON) uint64s as strings
UInt64s []uint64
)
func HasUint64(ss []uint64, s uint64) bool {
for i := range ss {
if ss[i] == s {
@@ -9,3 +20,23 @@ func HasUint64(ss []uint64, s uint64) bool {
return false
}
func (uu UInt64s) MarshalJSON() ([]byte, error) {
var (
buf = bytes.Buffer{}
)
buf.WriteByte('[')
for i, u := range uu {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteByte('"')
buf.WriteString(strconv.FormatUint(u, 10))
buf.WriteByte('"')
}
buf.WriteByte(']')
return buf.Bytes(), nil
}

View File

@@ -1,7 +1,9 @@
package slice
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
@@ -37,3 +39,38 @@ func TestHasUint64(t *testing.T) {
})
}
}
func TestUInt64s_MarshalJSON(t *testing.T) {
cases := []struct {
name string
ii UInt64s
json string
}{
{
"empty",
UInt64s{},
`[]`,
},
{
"one",
UInt64s{285372959844073660},
`["285372959844073660"]`,
},
{
"two",
UInt64s{285372959844073660, 285372959844073661},
`["285372959844073660","285372959844073661"]`,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var (
req = require.New(t)
result, err = json.Marshal(c.ii)
)
req.NoError(err)
req.Equal(string(result), c.json)
})
}
}