From fdc088b3bcbd8695a6e7e13da085f3d51682475f Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Mon, 20 Apr 2015 22:05:48 -0400 Subject: [PATCH] really bad struct encoding --- lib/emit.go | 38 ++++++++++++++++++++++++++++++++++++-- lib/emit_test.go | 6 ++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/lib/emit.go b/lib/emit.go index 8d63f40..6176b75 100644 --- a/lib/emit.go +++ b/lib/emit.go @@ -2,8 +2,10 @@ package moon import ( "bytes" + "fmt" "math" "reflect" + "runtime" "strconv" ) @@ -20,7 +22,20 @@ type encoder struct { scratch [64]byte } -func (e *encoder) encode(v interface{}) error { +func (e *encoder) encode(v interface{}) (err error) { + defer func() { + r := recover() + if r == nil { + return + } + if _, ok := r.(runtime.Error); ok { + panic(r) + } + if s, ok := r.(string); ok { + panic(s) + } + err = r.(error) + }() e.encodeValue(reflect.ValueOf(v)) return nil } @@ -49,8 +64,10 @@ func typeEncoder(t reflect.Type) encodeFn { return encodeFloat64 case reflect.String: return encodeString + case reflect.Struct: + return encodeStruct default: - panic("I don't know what to do here") + panic(fmt.Errorf("unhandled type: %v kind: %v", t, t.Kind())) } } @@ -84,6 +101,23 @@ func encodeFloat(bits int) encodeFn { } } +func encodeStruct(e *encoder, v reflect.Value) { + t := v.Type() + e.WriteByte('{') + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + e.WriteString(f.Name) + e.WriteByte(':') + e.WriteByte(' ') + fv := v.FieldByName(f.Name) + e.encodeValue(fv) + if i != t.NumField()-1 { + e.WriteByte(' ') + } + } + e.WriteByte('}') +} + var ( encodeFloat32 = encodeFloat(32) encodeFloat64 = encodeFloat(64) diff --git a/lib/emit_test.go b/lib/emit_test.go index 2d29c54..b006913 100644 --- a/lib/emit_test.go +++ b/lib/emit_test.go @@ -4,6 +4,11 @@ import ( "testing" ) +type person struct { + Name string + Age int +} + var valueTests = []struct { in interface{} out string @@ -23,6 +28,7 @@ var valueTests = []struct { // better than something having things change type. {"a string", `"a string"`}, {`it's got "quotes"`, `"it's got \"quotes\""`}, + {person{"jordan", 28}, `{Name: "jordan" Age: 28}`}, } func TestWriteValues(t *testing.T) {