summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/slime/ArrayValue.java
blob: ac1a33eea0d65a83df562797307988ea405394e7 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.slime;

final class ArrayValue extends Value {

    private int capacity = 16;
    private int used = 0;
    private Value[] values = new Value[capacity];
    private final SymbolTable names;

    public ArrayValue(SymbolTable names) { this.names = names; }
    public Type type() { return Type.ARRAY; }
    public int children() { return used; }
    public int entries() { return used; }
    public Value entry(int index) {
        return (index < used) ? values[index] : NixValue.invalid();
    }

    public void accept(Visitor v) { v.visitArray(this); }

    public void traverse(ArrayTraverser at) {
        for (int i = 0; i < used; i++) {
            at.entry(i, values[i]);
        }
    }

    private void grow() {
        Value[] v = values;
        capacity = (capacity << 1);
        values = new Value[capacity];
        System.arraycopy(v, 0, values, 0, used);
    }

    protected Value addLeaf(Value value) {
        if (used == capacity) {
            grow();
        }
        values[used++] = value;
        return value;
    }

    public Value addArray() { return addLeaf(new ArrayValue(names)); }
    public Value addObject() { return addLeaf(new ObjectValue(names)); }

}