From 9fafd69674167c06933b1787ae235618431ce87f Mon Sep 17 00:00:00 2001 From: corpix Date: Mon, 18 Sep 2017 21:04:37 +0000 Subject: [PATCH] Add support for encoding empty interfaces (#39) --- encode.go | 12 +++++++++--- encode_test.go | 8 ++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/encode.go b/encode.go index ae6bfd5..15602f0 100644 --- a/encode.go +++ b/encode.go @@ -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()} } diff --git a/encode_test.go b/encode_test.go index 3e7b3d5..9125789 100644 --- a/encode_test.go +++ b/encode_test.go @@ -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) {