Skip to content
This repository has been archived by the owner on Mar 13, 2019. It is now read-only.

Support encoding of pointers as interface types #6

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions asn1_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"math/big"
"reflect"
"testing"
"fmt"
)

// isBytesEqual compares two byte arrays/slices.
Expand All @@ -26,9 +27,14 @@ type testCase struct {
expected []byte
}

func (t testCase) String() string {
return fmt.Sprintf("testCase: value %#v (%T) expects %#v", t.value, t.value, t.expected)
}

// testEncode encodes an object and compares with the expected bytes.
func testEncode(t *testing.T, ctx *Context, options string, tests ...testCase) {
for _, test := range tests {
t.Logf("Testing case: %v", test)
data, err := ctx.EncodeWithOptions(test.value, options)
if err != nil {
t.Fatal(err)
Expand Down Expand Up @@ -670,3 +676,30 @@ func TestArraySlice(t *testing.T) {
ctx := NewContext()
testEncodeDecode(t, ctx, "", testCases...)
}

func TestPointerInterface(t *testing.T) {
type I interface {}
type Type struct {
A int
B string
C bool
}
var obj I
obj = &Type{1, "abc", true}
ctx := NewContext()
// We cannot use testSimple because the type is I
data, err := ctx.Encode(obj)
if err != nil {
t.Fatal(err)
}
value := new(Type)
rest, err := ctx.Decode(data, value)
if err != nil {
t.Fatal(err)
}
if len(rest) > 0 {
t.Fatalf("Unexpected remaining bytes when decoding \"%v\": %#v\n",
obj, rest)
}
checkEqual(t, obj, value)
}
5 changes: 1 addition & 4 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ func (ctx *Context) EncodeWithOptions(obj interface{}, options string) (data []b
func (ctx *Context) encode(value reflect.Value, opts *fieldOptions) (*rawValue, error) {

// Skip the interface type
switch value.Kind() {
case reflect.Interface:
value = value.Elem()
}
value = getActualType(value)

// If a value is missing the default value is used
empty := isEmpty(value)
Expand Down
15 changes: 15 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,21 @@ func (ctx *Context) decodeNull(data []byte, value reflect.Value) error {
* Helper functions
*/

// getActualType recursively gets the underlying type of Interfaces and Pointers.
func getActualType(value reflect.Value) reflect.Value {
for {
if value.Type() == bigIntType {
return value
}
switch value.Kind() {
case reflect.Interface, reflect.Ptr:
value = value.Elem()
default:
return value
}
}
}

func checkInt(ctx *Context, data []byte) error {
if ctx.der.decoding {
if len(data) >= 2 {
Expand Down