Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MakeTypedEncoder: accept results by pointer or value #134

Merged
merged 2 commits into from Nov 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions encoding.go
Expand Up @@ -92,16 +92,23 @@ func MakeTypedEncoder(f interface{}) func(*Request) func(io.Writer) Encoder {
}

valType := t.In(2)
valTypePtr := reflect.PtrTo(valType)

return MakeEncoder(func(req *Request, w io.Writer, i interface{}) error {
if reflect.TypeOf(i) != valType {
iType := reflect.TypeOf(i)
iValue := reflect.ValueOf(i)
switch iType {
case valType:
case valTypePtr:
iValue = iValue.Elem()
default:
return fmt.Errorf("unexpected type %T, expected %v", i, valType)
}

out := val.Call([]reflect.Value{
reflect.ValueOf(req),
reflect.ValueOf(w),
reflect.ValueOf(i),
iValue,
})

err, ok := out[0].Interface().(error)
Expand Down
25 changes: 25 additions & 0 deletions encoding_test.go
Expand Up @@ -36,6 +36,31 @@ func TestMakeTypedEncoder(t *testing.T) {
}
}

func TestMakeTypedEncoderByValue(t *testing.T) {
expErr := fmt.Errorf("command fooTestObj failed")
f := MakeTypedEncoder(func(req *Request, w io.Writer, v fooTestObj) error {
if v.Good {
return nil
}
return expErr
})

req := &Request{}

encoderFunc := f(req)

buf := new(bytes.Buffer)
encoder := encoderFunc(buf)

if err := encoder.Encode(&fooTestObj{true}); err != nil {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't there be a test that passes fooTestObject by value?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, internally we always pass to Encode by pointer (or should, at least).

t.Fatal(err)
}

if err := encoder.Encode(&fooTestObj{false}); err != expErr {
t.Fatal("expected: ", expErr)
}
}

func TestMakeTypedEncoderArrays(t *testing.T) {
f := MakeTypedEncoder(func(req *Request, w io.Writer, v []fooTestObj) error {
if len(v) != 2 {
Expand Down