Example #1
0
// RoundtripTester is a test helper to test a MarshalUnmarshaler
func RoundtripTester(t *testing.T, c codec.MarshalUnmarshaler, vals ...interface{}) {
	var val, to interface{}
	if len(vals) > 0 {
		if len(vals) != 2 {
			panic("Wrong number of vals, expected 2")
		}
		val = vals[0]
		to = vals[1]
	} else {
		val = &testStruct{Name: "test"}
		to = &testStruct{}
	}

	encoded, err := c.Marshal(val)
	if err != nil {
		t.Fatal("Encode error:", err)
	}
	err = c.Unmarshal(encoded, to)
	if err != nil {
		t.Fatal("Decode error:", err)
	}
	if !reflect.DeepEqual(val, to) {
		t.Fatalf("Roundtrip codec mismatch, expected\n%#v\ngot\n%#v", val, to)
	}
}
Example #2
0
// toBytes turns an interface into a slice of bytes
func toBytes(key interface{}, codec codec.MarshalUnmarshaler) ([]byte, error) {
	if key == nil {
		return nil, nil
	}
	switch t := key.(type) {
	case []byte:
		return t, nil
	case string:
		return []byte(t), nil
	case int:
		return numbertob(int64(t))
	case uint:
		return numbertob(uint64(t))
	case int8, int16, int32, int64, uint8, uint16, uint32, uint64:
		return numbertob(t)
	default:
		return codec.Marshal(key)
	}
}