Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider empty slices to be "zero" #624

Merged
merged 2 commits into from
Dec 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion serializer/serix/map_encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func (api *API) mapEncodeStructFields(
continue
}

if sField.settings.omitEmpty && fieldValue.IsZero() {
if sField.settings.omitEmpty && api.isValueEmpty(fieldValue) {
continue
}

Expand Down Expand Up @@ -323,3 +323,19 @@ func (api *API) mapEncodeMap(ctx context.Context, value reflect.Value, ts TypeSe

return m, nil
}

// Returns whether the value is empty.
//
// Thin wrapper around reflect.Value.IsZero to also consider slices of length 0 as empty.
func (api *API) isValueEmpty(value reflect.Value) bool {
if value.IsZero() {
return true
}

switch value.Kind() {
case reflect.Slice:
return value.Len() == 0
}

return false
}
55 changes: 55 additions & 0 deletions serializer/serix/serix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package serix_test

import (
"context"
"encoding/json"
"reflect"
"strings"
"testing"

"github.com/iancoleman/orderedmap"
Expand Down Expand Up @@ -808,3 +810,56 @@ func (test *decodingTest) run(t *testing.T) {

require.EqualValues(t, test.source, jsonDest)
}

func TestSerixOmitEmpty(t *testing.T) {
type Numbers struct {
Bytes []uint8 `serix:",omitempty"`
}
type omitEmptyTest struct {
name string
expectEmpty bool
source Numbers
}

tests := []omitEmptyTest{
{
name: "ok - slice empty",
expectEmpty: true,
source: Numbers{
Bytes: []uint8{},
},
},
{
name: "ok - nil slice",
expectEmpty: true,
source: Numbers{
Bytes: nil,
},
},
{
name: "ok - non-empty slice",
expectEmpty: false,
source: Numbers{
Bytes: []uint8{0xff},
},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
encodedJson, err := testAPI.JSONEncode(context.Background(), test.source)
require.NoError(t, err)

dec := json.NewDecoder(strings.NewReader(string(encodedJson)))
var decoded Numbers
err = dec.Decode(&decoded)
require.NoError(t, err)

if test.expectEmpty {
require.Empty(t, decoded.Bytes)
} else {
require.NotEmpty(t, decoded.Bytes)
}
})
}
}
Loading