Skip to content

Commit

Permalink
Don't panic with 'omitempty' and uncomparable type
Browse files Browse the repository at this point in the history
  • Loading branch information
arp242 committed Jul 28, 2022
1 parent 2e74712 commit 5539367
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions encode.go
Expand Up @@ -653,6 +653,11 @@ func isEmpty(rv reflect.Value) bool {
case reflect.Array, reflect.Slice, reflect.Map, reflect.String:
return rv.Len() == 0
case reflect.Struct:
// TODO: should probably return an error here, or do this check
// somewhere else.
if !rv.Type().Comparable() {
return false
}
return reflect.Zero(rv.Type()).Interface() == rv.Interface()
case reflect.Bool:
return !rv.Bool()
Expand Down
18 changes: 18 additions & 0 deletions encode_test.go
Expand Up @@ -212,6 +212,24 @@ time = 1985-06-18T15:16:17Z
v, expected, nil)
}

func TestEncodeWithOmitEmptyUncomparable(t *testing.T) {
type nest struct {
Field []string `toml:"Field,omitempty"`
}
s := struct {
Values nest `toml:"values,omitempty"`
Empty nest `toml:"empty,omitempty"`
}{Values: nest{[]string{"XXX"}}}

buf := new(bytes.Buffer)
err := NewEncoder(buf).Encode(s)
// if !errorContains(err, "comparing uncomparable type struct") {
// t.Fatalf("wrong error: %v", err)
// }
fmt.Println(err)
fmt.Println(buf.String())
}

func TestEncodeWithOmitZero(t *testing.T) {
type simple struct {
Number int `toml:"number,omitzero"`
Expand Down

0 comments on commit 5539367

Please sign in to comment.