really bad struct encoding

master
Jordan Orelli 10 years ago
parent 10cb56adf5
commit fdc088b3bc

@ -2,8 +2,10 @@ package moon
import ( import (
"bytes" "bytes"
"fmt"
"math" "math"
"reflect" "reflect"
"runtime"
"strconv" "strconv"
) )
@ -20,7 +22,20 @@ type encoder struct {
scratch [64]byte 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)) e.encodeValue(reflect.ValueOf(v))
return nil return nil
} }
@ -49,8 +64,10 @@ func typeEncoder(t reflect.Type) encodeFn {
return encodeFloat64 return encodeFloat64
case reflect.String: case reflect.String:
return encodeString return encodeString
case reflect.Struct:
return encodeStruct
default: 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 ( var (
encodeFloat32 = encodeFloat(32) encodeFloat32 = encodeFloat(32)
encodeFloat64 = encodeFloat(64) encodeFloat64 = encodeFloat(64)

@ -4,6 +4,11 @@ import (
"testing" "testing"
) )
type person struct {
Name string
Age int
}
var valueTests = []struct { var valueTests = []struct {
in interface{} in interface{}
out string out string
@ -23,6 +28,7 @@ var valueTests = []struct {
// better than something having things change type. // better than something having things change type.
{"a string", `"a string"`}, {"a string", `"a string"`},
{`it's got "quotes"`, `"it's got \"quotes\""`}, {`it's got "quotes"`, `"it's got \"quotes\""`},
{person{"jordan", 28}, `{Name: "jordan" Age: 28}`},
} }
func TestWriteValues(t *testing.T) { func TestWriteValues(t *testing.T) {

Loading…
Cancel
Save