Skip to content

Commit

Permalink
Fix json marshalling of Sets (#2161)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Oct 11, 2023
1 parent 0f95f13 commit 99fc926
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
6 changes: 3 additions & 3 deletions utils/set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,13 @@ func (s *Set[T]) UnmarshalJSON(b []byte) error {
return nil
}

func (s *Set[_]) MarshalJSON() ([]byte, error) {
func (s Set[_]) MarshalJSON() ([]byte, error) {
var (
eltBytes = make([][]byte, len(*s))
eltBytes = make([][]byte, len(s))
i int
err error
)
for elt := range *s {
for elt := range s {
eltBytes[i], err = stdjson.Marshal(elt)
if err != nil {
return nil, err
Expand Down
26 changes: 26 additions & 0 deletions utils/set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,29 @@ func TestSetUnmarshalJSON(t *testing.T) {
require.Equal(set1, set2)
}
}

func TestSetReflectJSONMarshal(t *testing.T) {
require := require.New(t)
set := Set[int]{}
{
asJSON, err := json.Marshal(set)
require.NoError(err)
require.Equal("[]", string(asJSON))
}
id1JSON, err := json.Marshal(1)
require.NoError(err)
id2JSON, err := json.Marshal(2)
require.NoError(err)
set.Add(1)
{
asJSON, err := json.Marshal(set)
require.NoError(err)
require.Equal(fmt.Sprintf("[%s]", string(id1JSON)), string(asJSON))
}
set.Add(2)
{
asJSON, err := json.Marshal(set)
require.NoError(err)
require.Equal(fmt.Sprintf("[%s,%s]", string(id1JSON), string(id2JSON)), string(asJSON))
}
}

0 comments on commit 99fc926

Please sign in to comment.