Skip to content

Commit

Permalink
Evaluate omitempty against un-dereferenced fields
Browse files Browse the repository at this point in the history
Fixes #371
  • Loading branch information
cespare committed May 23, 2023
1 parent d56d9f6 commit a4df7e3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
23 changes: 14 additions & 9 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,24 +493,27 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
writeFields := func(fields [][]int) {
for _, fieldIndex := range fields {
fieldType := rt.FieldByIndex(fieldIndex)
fieldVal := eindirect(rv.FieldByIndex(fieldIndex))
fieldVal := rv.FieldByIndex(fieldIndex)

if isNil(fieldVal) { /// Don't write anything for nil fields.
opts := getOptions(fieldType.Tag)
if opts.skip {
continue
}
if opts.omitempty && isEmpty(fieldVal) {
continue
}

opts := getOptions(fieldType.Tag)
if opts.skip {
fieldVal = eindirect(fieldVal)

if isNil(fieldVal) { // Don't write anything for nil fields.
continue
}

keyName := fieldType.Name
if opts.name != "" {
keyName = opts.name
}

if opts.omitempty && enc.isEmpty(fieldVal) {
continue
}
if opts.omitzero && isZero(fieldVal) {
continue
}
Expand Down Expand Up @@ -652,7 +655,7 @@ func isZero(rv reflect.Value) bool {
return false
}

func (enc *Encoder) isEmpty(rv reflect.Value) bool {
func isEmpty(rv reflect.Value) bool {
switch rv.Kind() {
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
return rv.Len() == 0
Expand All @@ -667,13 +670,15 @@ func (enc *Encoder) isEmpty(rv reflect.Value) bool {
// type b struct{ s []string }
// s := a{field: b{s: []string{"AAA"}}}
for i := 0; i < rv.NumField(); i++ {
if !enc.isEmpty(rv.Field(i)) {
if !isEmpty(rv.Field(i)) {
return false
}
}
return true
case reflect.Bool:
return !rv.Bool()
case reflect.Pointer:
return rv.IsNil()
}
return false
}
Expand Down
3 changes: 0 additions & 3 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,8 +261,6 @@ func TestEncodeOmitEmptyPointer(t *testing.T) {
})

t.Run("zero values", func(t *testing.T) {
// TODO: this needs to be fixed; https://github.com/BurntSushi/toml/issues/371
t.Skip()
str := ""
sl := []string{}
m := map[string]string{}
Expand All @@ -277,7 +275,6 @@ func TestEncodeOmitEmptyPointer(t *testing.T) {
slice = []
[map]
XXX = ""
[struct]
string = ""
Expand Down

0 comments on commit a4df7e3

Please sign in to comment.