diff options
Diffstat (limited to 'vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go')
-rw-r--r-- | vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go b/vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go new file mode 100644 index 0000000..ba92647 --- /dev/null +++ b/vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go | |||
@@ -0,0 +1,64 @@ | |||
1 | package cty | ||
2 | |||
3 | // UnknownAsNull returns a value of the same type as the given value but | ||
4 | // with any unknown values (including nested values) replaced with null | ||
5 | // values of the same type. | ||
6 | // | ||
7 | // This can be useful if a result is to be serialized in a format that can't | ||
8 | // represent unknowns, such as JSON, as long as the caller does not need to | ||
9 | // retain the unknown value information. | ||
10 | func UnknownAsNull(val Value) Value { | ||
11 | ty := val.Type() | ||
12 | switch { | ||
13 | case val.IsNull(): | ||
14 | return val | ||
15 | case !val.IsKnown(): | ||
16 | return NullVal(ty) | ||
17 | case ty.IsListType() || ty.IsTupleType() || ty.IsSetType(): | ||
18 | length := val.LengthInt() | ||
19 | if length == 0 { | ||
20 | // If there are no elements then we can't have unknowns | ||
21 | return val | ||
22 | } | ||
23 | vals := make([]Value, 0, length) | ||
24 | it := val.ElementIterator() | ||
25 | for it.Next() { | ||
26 | _, v := it.Element() | ||
27 | vals = append(vals, UnknownAsNull(v)) | ||
28 | } | ||
29 | switch { | ||
30 | case ty.IsListType(): | ||
31 | return ListVal(vals) | ||
32 | case ty.IsTupleType(): | ||
33 | return TupleVal(vals) | ||
34 | default: | ||
35 | return SetVal(vals) | ||
36 | } | ||
37 | case ty.IsMapType() || ty.IsObjectType(): | ||
38 | var length int | ||
39 | switch { | ||
40 | case ty.IsMapType(): | ||
41 | length = val.LengthInt() | ||
42 | default: | ||
43 | length = len(val.Type().AttributeTypes()) | ||
44 | } | ||
45 | if length == 0 { | ||
46 | // If there are no elements then we can't have unknowns | ||
47 | return val | ||
48 | } | ||
49 | vals := make(map[string]Value, length) | ||
50 | it := val.ElementIterator() | ||
51 | for it.Next() { | ||
52 | k, v := it.Element() | ||
53 | vals[k.AsString()] = UnknownAsNull(v) | ||
54 | } | ||
55 | switch { | ||
56 | case ty.IsMapType(): | ||
57 | return MapVal(vals) | ||
58 | default: | ||
59 | return ObjectVal(vals) | ||
60 | } | ||
61 | } | ||
62 | |||
63 | return val | ||
64 | } | ||