aboutsummaryrefslogtreecommitdiff
path: root/model/arrayNode.go
blob: 203e01cbefe60a3e98e9b708c05274484d07437b (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
package model

import (
	"bytes"
	"fmt"
)

type ArrayNode struct {
	Value NodeArrayValue
}

func (n ArrayNode) Type() NodeType {
	return ArrayType
}

func (n *ArrayNode) MarshalJSON() ([]byte, error) {
	result := make([][]byte, 0, len(n.Value))
	for _, v := range n.Value {
		b, err := v.MarshalJSON()
		if err != nil {
			return nil, err
		}
		result = append(result, b)
	}
	return bytes.Join(
		[][]byte{
			[]byte("["),
			bytes.Join(result, []byte(", ")),
			[]byte("]"),
		}, []byte("")), 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)
	}
	return n.Value[idx], nil
}

func (n *ArrayNode) Merge(n2 *ArrayNode) {
	n.Value = append(n.Value, n2.Value...)
}

func (n *ArrayNode) Len() int {
	return len(n.Value)
}

type NodeArrayValue []Node