added set method

This commit is contained in:
NeonXP 2022-11-21 04:46:32 +03:00
parent 4054a50ce4
commit 0d431048d3
No known key found for this signature in database
GPG key ID: B0DA6283C40CB2CB
7 changed files with 60 additions and 6 deletions

View file

@ -30,6 +30,15 @@ func (n *ArrayNode) MarshalJSON() ([]byte, error) {
}, []byte("")), nil
}
func (n *ArrayNode) Set(v any) error {
val, ok := v.(NodeArrayValue)
if !ok {
return fmt.Errorf("%v is not array", v)
}
n.Value = val
return nil
}
func (n *ArrayNode) Index(idx int) (Node, error) {
if len(n.Value) <= idx {
return nil, fmt.Errorf("index %d out of range [0...%d]", idx, len(n.Value)-1)

View file

@ -1,5 +1,7 @@
package model
import "fmt"
type BooleanNode struct {
Value bool
}
@ -14,3 +16,12 @@ func (n *BooleanNode) MarshalJSON() ([]byte, error) {
}
return []byte("false"), nil
}
func (n *BooleanNode) Set(v any) error {
val, ok := v.(bool)
if !ok {
return fmt.Errorf("%v is not boolean", v)
}
n.Value = val
return nil
}

View file

@ -4,6 +4,7 @@ package model
type Node interface {
Type() NodeType
MarshalJSON() ([]byte, error)
Set(v any) error
}
// NewNode creates new node from value

View file

@ -9,3 +9,7 @@ func (n NullNode) Type() NodeType {
func (n NullNode) MarshalJSON() ([]byte, error) {
return []byte("null"), nil
}
func (n NullNode) Set(v any) error {
return nil
}

View file

@ -1,6 +1,9 @@
package model
import "strconv"
import (
"fmt"
"strconv"
)
type NumberNode struct {
Value float64
@ -13,3 +16,13 @@ func (n NumberNode) Type() NodeType {
func (n *NumberNode) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatFloat(n.Value, 'g', -1, 64)), nil
}
func (n *NumberNode) Set(v any) error {
switch v := v.(type) {
case float64:
n.Value = v
case int:
n.Value = float64(v)
}
return fmt.Errorf("%v is not number", v)
}

View file

@ -6,7 +6,7 @@ import (
)
type ObjectNode struct {
Value map[string]Node
Value NodeObjectValue
}
func (n ObjectNode) Type() NodeType {
@ -30,10 +30,6 @@ func (n *ObjectNode) MarshalJSON() ([]byte, error) {
}, []byte("")), nil
}
func (n *ObjectNode) Set(k string, v any) {
n.Value[k] = NewNode(v)
}
func (n *ObjectNode) Get(k string) (Node, error) {
child, ok := n.Value[k]
if !ok {
@ -51,3 +47,12 @@ func (n *ObjectNode) Merge(n2 *ObjectNode) {
func (n *ObjectNode) Len() int {
return len(n.Value)
}
func (n *ObjectNode) Set(v any) error {
val, ok := v.(NodeObjectValue)
if !ok {
return fmt.Errorf("%v is not object", v)
}
n.Value = val
return nil
}

View file

@ -1,5 +1,7 @@
package model
import "fmt"
type StringNode struct {
Value string
}
@ -11,3 +13,12 @@ func (n StringNode) Type() NodeType {
func (n *StringNode) MarshalJSON() ([]byte, error) {
return []byte(`"` + n.Value + `"`), nil
}
func (n *StringNode) Set(v any) error {
val, ok := v.(string)
if !ok {
return fmt.Errorf("%v is not string", v)
}
n.Value = val
return nil
}