aboutsummaryrefslogtreecommitdiff
path: root/std/factory.go
blob: 11c3de19a56c4bb3a555b6be3d4b87b80f9f92b1 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package std

import (
	"fmt"
	"strconv"
	"strings"

	"go.neonxp.dev/json"
)

func Factory(typ json.NodeType) (json.Node, error) {
	switch typ {
	case json.ObjectType:
		return ObjectNode{}, nil
	case json.ArrayType:
		return &ArrayNode{}, nil
	case json.StringType:
		return &StringNode{}, nil
	case json.NumberType:
		return &NumberNode{}, nil
	case json.BooleanType:
		return &BooleanNode{}, nil
	case json.NullType:
		return NullNode{}, nil
	}
	return nil, fmt.Errorf("unknown type: %s", typ)
}

type ObjectNode map[string]json.Node

func (o ObjectNode) SetKeyValue(k string, v json.Node) {
	o[k] = v
}

func (o ObjectNode) GetByKey(k string) (json.Node, bool) {
	v, ok := o[k]
	return v, ok
}

func (o ObjectNode) String() string {
	res := make([]string, 0, len(o))
	for k, n := range o {
		res = append(res, fmt.Sprintf(`"%s":%s`, k, n.String()))
	}
	return fmt.Sprintf(`{%s}`, strings.Join(res, ","))
}

type ArrayNode []json.Node

func (o *ArrayNode) Append(v json.Node) {
	na := append(*o, v)
	*o = na
}

func (o *ArrayNode) Index(i int) json.Node {
	return (*o)[i]
}

func (o *ArrayNode) Len() int {
	return len(*o)
}

func (o *ArrayNode) String() string {
	res := make([]string, 0, len(*o))
	for _, v := range *o {
		res = append(res, v.String())
	}
	return fmt.Sprintf(`[%s]`, strings.Join(res, ","))
}

type StringNode struct {
	Value string
}

func (o *StringNode) SetString(v string) {
	o.Value = v
}

func (o *StringNode) GetString() string {
	return o.Value
}

func (o *StringNode) String() string {
	return `"` + o.Value + `"`
}

type NumberNode struct {
	Value float64
}

func (o *NumberNode) SetNumber(v float64) {
	o.Value = v
}

func (o *NumberNode) GetNumber() float64 {
	return o.Value
}

func (o *NumberNode) String() string {
	return strconv.FormatFloat(float64(o.Value), 'g', 15, 64)
}

type BooleanNode struct {
	Value bool
}

func (o *BooleanNode) SetBool(v bool) {
	o.Value = v
}

func (o *BooleanNode) GetBool() bool {
	return o.Value
}

func (o BooleanNode) String() string {
	if o.Value {
		return "true"
	}
	return "false"
}

type NullNode struct{}

func (o NullNode) String() string {
	return "null"
}