Skip to content

Commit 0f5e723

Browse files
authored
Merge pull request #12 from hashicorp/paddy_implement_as
Flesh out the As method.
2 parents 34080cf + 6d46ef7 commit 0f5e723

File tree

1 file changed

+48
-5
lines changed

1 file changed

+48
-5
lines changed

tfprotov5/tftypes/value.go

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package tftypes
33
import (
44
"bytes"
55
"fmt"
6+
"math/big"
67

78
"github.com/vmihailenco/msgpack"
89
)
@@ -39,13 +40,55 @@ func NewValue(t Type, val interface{}) Value {
3940
}
4041
}
4142

42-
func (v Value) As(dst interface{}) error {
43+
func (val Value) As(dst interface{}) error {
4344
unmarshaler, ok := dst.(Unmarshaler)
44-
if !ok {
45-
// TODO: let's do unmarshaling to builtin types out of the box
46-
return fmt.Errorf("can't unmarshal into %T, needs UnmarshalTerraform5Type method", dst)
45+
if ok {
46+
return unmarshaler.UnmarshalTerraform5Type(val)
4747
}
48-
return unmarshaler.UnmarshalTerraform5Type(v)
48+
if val.IsNull() {
49+
return fmt.Errorf("unmarshaling null values is not supported")
50+
}
51+
if !val.IsKnown() {
52+
return fmt.Errorf("unmarshaling unknown values is not supported")
53+
}
54+
switch target := dst.(type) {
55+
case *string:
56+
v, ok := val.value.(string)
57+
if !ok {
58+
return fmt.Errorf("can't unmarshal %s into %T, expected string", val.typ, dst)
59+
}
60+
*target = v
61+
return nil
62+
case *big.Float:
63+
v, ok := val.value.(*big.Float)
64+
if !ok {
65+
return fmt.Errorf("can't unmarshal %s into %T, expected *big.Float", val.typ, dst)
66+
}
67+
target.Set(v)
68+
return nil
69+
case *bool:
70+
v, ok := val.value.(bool)
71+
if !ok {
72+
return fmt.Errorf("can't unmarshal %s into %T, expected boolean", val.typ, dst)
73+
}
74+
*target = v
75+
return nil
76+
case *map[string]Value:
77+
v, ok := val.value.(map[string]Value)
78+
if !ok {
79+
return fmt.Errorf("can't unmarshal %s into %T, expected map[string]tftypes.Value", val.typ, dst)
80+
}
81+
*target = v
82+
return nil
83+
case *[]Value:
84+
v, ok := val.value.([]Value)
85+
if !ok {
86+
return fmt.Errorf("can't unmarshal %s into %T expected []tftypes.Value", val.typ, dst)
87+
}
88+
*target = v
89+
return nil
90+
}
91+
return fmt.Errorf("can't unmarshal into %T, needs UnmarshalTerraform5Type method", dst)
4992
}
5093

5194
func (v Value) Is(t Type) bool {

0 commit comments

Comments
 (0)