Skip to content

Commit d9b9172

Browse files
authored
Evaluate omitempty against un-dereferenced fields (#392)
Fixes #371
1 parent 5073d46 commit d9b9172

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

encode.go

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -493,24 +493,27 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) {
493493
writeFields := func(fields [][]int) {
494494
for _, fieldIndex := range fields {
495495
fieldType := rt.FieldByIndex(fieldIndex)
496-
fieldVal := eindirect(rv.FieldByIndex(fieldIndex))
496+
fieldVal := rv.FieldByIndex(fieldIndex)
497497

498-
if isNil(fieldVal) { /// Don't write anything for nil fields.
498+
opts := getOptions(fieldType.Tag)
499+
if opts.skip {
500+
continue
501+
}
502+
if opts.omitempty && isEmpty(fieldVal) {
499503
continue
500504
}
501505

502-
opts := getOptions(fieldType.Tag)
503-
if opts.skip {
506+
fieldVal = eindirect(fieldVal)
507+
508+
if isNil(fieldVal) { // Don't write anything for nil fields.
504509
continue
505510
}
511+
506512
keyName := fieldType.Name
507513
if opts.name != "" {
508514
keyName = opts.name
509515
}
510516

511-
if opts.omitempty && enc.isEmpty(fieldVal) {
512-
continue
513-
}
514517
if opts.omitzero && isZero(fieldVal) {
515518
continue
516519
}
@@ -652,7 +655,7 @@ func isZero(rv reflect.Value) bool {
652655
return false
653656
}
654657

655-
func (enc *Encoder) isEmpty(rv reflect.Value) bool {
658+
func isEmpty(rv reflect.Value) bool {
656659
switch rv.Kind() {
657660
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
658661
return rv.Len() == 0
@@ -667,13 +670,15 @@ func (enc *Encoder) isEmpty(rv reflect.Value) bool {
667670
// type b struct{ s []string }
668671
// s := a{field: b{s: []string{"AAA"}}}
669672
for i := 0; i < rv.NumField(); i++ {
670-
if !enc.isEmpty(rv.Field(i)) {
673+
if !isEmpty(rv.Field(i)) {
671674
return false
672675
}
673676
}
674677
return true
675678
case reflect.Bool:
676679
return !rv.Bool()
680+
case reflect.Ptr:
681+
return rv.IsNil()
677682
}
678683
return false
679684
}

encode_test.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,6 @@ func TestEncodeOmitEmptyPointer(t *testing.T) {
261261
})
262262

263263
t.Run("zero values", func(t *testing.T) {
264-
// TODO: this needs to be fixed; https://github.com/BurntSushi/toml/issues/371
265-
t.Skip()
266264
str := ""
267265
sl := []string{}
268266
m := map[string]string{}
@@ -277,7 +275,6 @@ func TestEncodeOmitEmptyPointer(t *testing.T) {
277275
slice = []
278276
279277
[map]
280-
XXX = ""
281278
282279
[struct]
283280
string = ""

0 commit comments

Comments
 (0)