Skip to content

Commit

Permalink
Add support for encoding empty interfaces (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
corpix authored and fjl committed Sep 18, 2017
1 parent 2258234 commit 9fafd69
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 9 additions & 3 deletions encode.go
Expand Up @@ -61,20 +61,26 @@ func (cfg *Config) NewEncoder(w io.Writer) *Encoder {
// Encode writes the TOML of v to the stream.
// See the documentation for Marshal for details about the conversion of Go values to TOML.
func (e *Encoder) Encode(v interface{}) error {
rv := reflect.ValueOf(v)
var (
buf = &tableBuf{typ: ast.TableTypeNormal}
rv = reflect.ValueOf(v)
err error
)

for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return &marshalNilError{rv.Type()}
}
rv = rv.Elem()
}
buf := &tableBuf{typ: ast.TableTypeNormal}
var err error

switch rv.Kind() {
case reflect.Struct:
err = buf.structFields(e.cfg, rv)
case reflect.Map:
err = buf.mapFields(e.cfg, rv)
case reflect.Interface:
return e.Encode(rv.Interface())
default:
err = &marshalTableError{rv.Type()}
}
Expand Down
8 changes: 8 additions & 0 deletions encode_test.go
Expand Up @@ -165,6 +165,14 @@ var marshalTests = []struct {
},
expect: loadTestData("marshal-key-escape.toml"),
},
// empty interface:
{
v: func() interface{} {
var v interface{} = map[string]interface{}{"foo": "bar"}
return &v
}(),
expect: []byte("foo = \"bar\"\n"),
},
}

func TestMarshal(t *testing.T) {
Expand Down

0 comments on commit 9fafd69

Please sign in to comment.