Skip to content

Commit

Permalink
Return error on unset variant.
Browse files Browse the repository at this point in the history
  • Loading branch information
q-uint committed May 17, 2024
1 parent d3362d6 commit cc0dcd0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
17 changes: 17 additions & 0 deletions candid/idl/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,20 @@ func TestEncode_issue7(t *testing.T) {
t.Fatal(err)
}
}

func TestVariantType_default(t *testing.T) {
type V = struct {
A *Null `ic:"A,variant"`
B *Null `ic:"B,variant"`
}
raw, err := Marshal([]any{
V{},
})
if err == nil {
t.Error("expected error")
}
var v V
if err := Unmarshal(raw, []any{&v}); err == nil {
t.Error("expected error")
}
}
7 changes: 2 additions & 5 deletions candid/idl/variant.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (variant VariantType) EncodeValue(value any) ([]byte, error) {
return concat(id, v_), nil
}
}
return nil, fmt.Errorf("unknown variant: %variant", value)
return nil, fmt.Errorf("unknown variant: %v", value)
}

func (variant VariantType) String() string {
Expand Down Expand Up @@ -220,10 +220,7 @@ func (variant VariantType) structToVariant(value any) (*Variant, error) {
}, nil
}
if i == v.NumField()-1 {
return &Variant{
Name: tag.Name,
Value: nil,
}, nil
return nil, fmt.Errorf("invalid variant: no variant selected")
}
}
return nil, fmt.Errorf("invalid variant: %s", v.Type())
Expand Down

0 comments on commit cc0dcd0

Please sign in to comment.