diff options
Diffstat (limited to 'internal/node/node.go')
-rw-r--r-- | internal/node/node.go | 71 |
1 files changed, 71 insertions, 0 deletions
diff --git a/internal/node/node.go b/internal/node/node.go new file mode 100644 index 0000000..b8bec52 --- /dev/null +++ b/internal/node/node.go @@ -0,0 +1,71 @@ +package node + +import ( + "fmt" + "strconv" + "strings" + + "go.neonxp.dev/json" + "go.neonxp.dev/objectid" +) + +func Factory(typ json.NodeType) (json.Node, error) { + n := &Node{ + ID: objectid.New(), + Type: typ, + } + switch typ { + case json.ObjectType: + n.objectValue = make(map[string]*Node) + case json.ArrayType: + n.arrayValue = make([]*Node, 0) + } + return n, nil +} + +type Node struct { + ID objectid.ID + Type json.NodeType + Parent objectid.ID + stringValue string + numberValue float64 + boolValue bool + objectValue map[string]*Node + arrayValue []*Node + ACL ACL +} + +func (n *Node) String() string { + switch n.Type { + case json.NullType: + return "null" + case json.StringType: + return `"` + n.stringValue + `"` + case json.NumberType: + return strconv.FormatFloat(n.numberValue, 'g', 15, 64) + case json.BooleanType: + if n.boolValue { + return "true" + } + return "false" + case json.ObjectType: + res := make([]string, 0, len(n.objectValue)) + for k, n := range n.objectValue { + res = append(res, fmt.Sprintf(`"%s":%s`, k, n.String())) + } + return fmt.Sprintf(`{%s}`, strings.Join(res, ",")) + case json.ArrayType: + res := make([]string, 0, len(n.arrayValue)) + for _, v := range n.arrayValue { + res = append(res, v.String()) + } + return fmt.Sprintf(`[%s]`, strings.Join(res, ",")) + } + return "" +} + +func (n *Node) SetParent(v json.Node) { + if v != nil { + n.Parent = v.(*Node).ID + } +} |