Skip to content

Commit

Permalink
Fix slice encoding
Browse files Browse the repository at this point in the history
Updates the util.ReflectValue function to not call Elem() on
a reflect.Value that is a slice as it is only allowed on
an interface or pointer and will panic otherwise.
  • Loading branch information
chrisroberts committed Jul 2, 2024
1 parent de99036 commit d4ebce2
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
6 changes: 6 additions & 0 deletions cursor/encoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,9 @@ func (s *encoderSuite) TestZeroValuePtr() {
_, err := e.Encode(struct{ ID *string }{})
s.Nil(err)
}

func (s *encoderSuite) TestSliceValue() {
e := NewEncoder([]EncoderField{{Key: "Slice"}})
_, err := e.Encode(struct{ Slice []string }{Slice: []string{"value"}})
s.Nil(err)
}
22 changes: 22 additions & 0 deletions cursor/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,28 @@ func (s *encodingSuite) TestStructPtr() {
s.Equal(sv, *(v.(*structValue)))
}

/* slice */

type sliceModel struct {
Value []byte
ValuePtr *[]byte
}

func (s *encodingSuite) TestSlice() {
c, _ := s.encodeValue(sliceModel{
Value: []byte("123"),
})
v, _ := s.decodeValue(sliceModel{}, c)
s.Equal([]byte("123"), v)
}

func (s *encodingSuite) TestSlicePtr() {
sv := []byte("123")
c, _ := s.encodeValuePtr(sliceModel{ValuePtr: &sv})
v, _ := s.decodeValuePtr(sliceModel{}, c)
s.Equal(sv, *(v.(*[]byte)))
}

/* multiple */

type multipleModel struct {
Expand Down
4 changes: 2 additions & 2 deletions internal/util/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"reflect"
)

// ReflectValue returns reflect value underlying given value, unwrapping pointer and slice
// ReflectValue returns reflect value underlying given value, unwrapping pointer
func ReflectValue(v interface{}) reflect.Value {
rv, ok := v.(reflect.Value)
if !ok {
rv = reflect.ValueOf(v)
}
for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Slice {
for rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
return rv
Expand Down

0 comments on commit d4ebce2

Please sign in to comment.