/
value_struct.go
75 lines (60 loc) · 1.52 KB
/
value_struct.go
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
65
66
67
68
69
70
71
72
73
74
75
package codegen
import "strings"
type structValue struct {
name string
props []*StructPropertyValue
isAddress bool
}
type StructPropertyValue struct {
name string
val Value
}
// InitStruct creates a new struct initialisation
func InitStruct(structName string) *structValue {
return &structValue{
name: structName,
props: make([]*StructPropertyValue, 0),
}
}
// Props adds properties with values to the struct initialisation
func (s *structValue) Props(properties ...*StructPropertyValue) *structValue {
s.props = properties
return s
}
// Address returns a pointer to the initialised struct
func (s *structValue) Address() *structValue {
s.isAddress = true
return s
}
// AddPropValue adds a new property value to the struct initialisation
func (s *structValue) AddPropValue(propertyName string, propertyValue Value) *StructPropertyValue {
prop := PropValue(propertyName, propertyValue)
s.props = append(s.props, prop)
return prop
}
// PropValue creates a new property with its value
func PropValue(propertyName string, propertyValue Value) *StructPropertyValue {
return &StructPropertyValue{
name: propertyName,
val: propertyValue,
}
}
func (s *structValue) writeValue(sb *strings.Builder) {
if s.isAddress {
sb.WriteByte('&')
}
sb.WriteString(s.name)
sb.WriteByte('{')
for i, prop := range s.props {
if i != 0 {
sb.WriteByte(',')
}
sb.WriteString(prop.name)
sb.WriteByte(':')
prop.val.writeValue(sb)
}
sb.WriteByte('}')
}
func (s *structValue) isPointer() bool {
return false
}