diff --git a/candid/idl/vector.go b/candid/idl/vector.go index 592e3c2..997ab5b 100644 --- a/candid/idl/vector.go +++ b/candid/idl/vector.go @@ -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. diff --git a/candid/idl/vector_test.go b/candid/idl/vector_test.go index 0995d2b..989dbb3 100644 --- a/candid/idl/vector_test.go +++ b/candid/idl/vector_test.go @@ -1,6 +1,7 @@ package idl_test import ( + "errors" "github.com/aviate-labs/agent-go/candid/idl" "testing" ) @@ -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") } @@ -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") + } + }) +}