aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/zclconf/go-cty/cty/unknown_as_null.go
blob: ba926475ce5cec5740b51d3e86c763ec36b5b219 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cty

// UnknownAsNull returns a value of the same type as the given value but
// with any unknown values (including nested values) replaced with null
// values of the same type.
//
// This can be useful if a result is to be serialized in a format that can't
// represent unknowns, such as JSON, as long as the caller does not need to
// retain the unknown value information.
func UnknownAsNull(val Value) Value {
	ty := val.Type()
	switch {
	case val.IsNull():
		return val
	case !val.IsKnown():
		return NullVal(ty)
	case ty.IsListType() || ty.IsTupleType() || ty.IsSetType():
		length := val.LengthInt()
		if length == 0 {
			// If there are no elements then we can't have unknowns
			return val
		}
		vals := make([]Value, 0, length)
		it := val.ElementIterator()
		for it.Next() {
			_, v := it.Element()
			vals = append(vals, UnknownAsNull(v))
		}
		switch {
		case ty.IsListType():
			return ListVal(vals)
		case ty.IsTupleType():
			return TupleVal(vals)
		default:
			return SetVal(vals)
		}
	case ty.IsMapType() || ty.IsObjectType():
		var length int
		switch {
		case ty.IsMapType():
			length = val.LengthInt()
		default:
			length = len(val.Type().AttributeTypes())
		}
		if length == 0 {
			// If there are no elements then we can't have unknowns
			return val
		}
		vals := make(map[string]Value, length)
		it := val.ElementIterator()
		for it.Next() {
			k, v := it.Element()
			vals[k.AsString()] = UnknownAsNull(v)
		}
		switch {
		case ty.IsMapType():
			return MapVal(vals)
		default:
			return ObjectVal(vals)
		}
	}

	return val
}