Skip to content

Commit

Permalink
Make sure empty slices are not nil.
Browse files Browse the repository at this point in the history
  • Loading branch information
q-uint committed Dec 18, 2023
1 parent 04ee1f2 commit a6300a8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
5 changes: 5 additions & 0 deletions candid/idl/vector.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ func (vec VectorType) UnmarshalGo(raw any, _v any) error {
return nil
}

if v.Kind() == reflect.Slice && v.IsNil() {
// Create new slice.
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}

rv := reflect.ValueOf(raw)
if v.Kind() == reflect.Array {
// Check if array is big enough.
Expand Down
26 changes: 25 additions & 1 deletion candid/idl/vector_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package idl_test

import (
"errors"
"github.com/aviate-labs/agent-go/candid/idl"
"testing"
)
Expand All @@ -18,7 +19,8 @@ func TestVectorType_UnmarshalGo(t *testing.T) {
if err == nil {
t.Fatal("expected error")
} else {
_, ok := err.(*idl.UnmarshalGoError)
var unmarshalGoError *idl.UnmarshalGoError
ok := errors.As(err, &unmarshalGoError)
if !ok {
t.Fatal("expected UnmarshalGoError")
}
Expand Down Expand Up @@ -87,3 +89,25 @@ func TestVectorType_UnmarshalGo(t *testing.T) {
}).UnmarshalGo([2]any{}, &nv))
})
}

func TestVectorType_empty(t *testing.T) {
typ := idl.VectorType{Type: idl.Nat8Type()}

var x []byte
t.Run("non-nil", func(t *testing.T) {
if err := typ.UnmarshalGo([]byte{}, &x); err != nil {
t.Fatal(err)
}
if x == nil {
t.Error("expected non-nil")
}
})
t.Run("nil", func(t *testing.T) {
if err := typ.UnmarshalGo(nil, &x); err != nil {
t.Fatal(err)
}
if x != nil {
t.Error("expected nil")
}
})
}

0 comments on commit a6300a8

Please sign in to comment.