aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/slime/JsonFormat.java
blob: cbe06c73c78db334f8717f1f38d554f7324d78b0 (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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.slime;

import com.yahoo.io.AbstractByteWriter;
import com.yahoo.io.ByteWriter;
import com.yahoo.text.AbstractUtf8Array;
import com.yahoo.text.Utf8;
import com.yahoo.text.Utf8String;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;

import static ai.vespa.validation.Validation.requireInRange;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * Encodes json from a slime object.
 *
 * @author Ulf Lilleengen
 */
public final class JsonFormat implements SlimeFormat {

    private final static byte [] HEX = Utf8.toBytes("0123456789ABCDEF");
    private final int indent;

    public JsonFormat(int indent) {
        this.indent = requireInRange(indent, "JSON space indent count", 0, 8);
    }

    public JsonFormat(boolean compact) {
        this(compact ? 0 : 2);
    }

    @Override
    public void encode(OutputStream os, Slime slime) throws IOException {
        new Encoder(slime.get(), os, indent).encode();
    }

    public void encode(OutputStream os, Inspector value) throws IOException {
        new Encoder(value, os, indent).encode();
    }

    public void encode(AbstractByteWriter os, Slime slime) throws IOException {
        new Encoder(slime.get(), os, indent).encode();
    }

    public void encode(AbstractByteWriter os, Inspector value) throws IOException {
        new Encoder(value, os, indent).encode();
    }

    /** Returns the given slime data as UTF-8-encoded JSON */
    public static byte[] toJsonBytes(Slime slime) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            new JsonFormat(true).encode(baos, slime);
            return baos.toByteArray();
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    /** Returns the given UTF-8-encoded JSON as a Slime object */
    public static Slime jsonToSlime(byte[] json) {
        Slime slime = new Slime();
        new JsonDecoder().decode(slime, json);
        return slime;
    }

    static final class Encoder implements ArrayTraverser, ObjectTraverser {
        private final Inspector top;
        private final AbstractByteWriter out;
        private final byte[] indent;
        private boolean head = true;
        private int level = 0;
        final static AbstractUtf8Array NULL=new Utf8String("null");
        final static AbstractUtf8Array FALSE=new Utf8String("false");
        final static AbstractUtf8Array TRUE=new Utf8String("true");

        public Encoder(Inspector value, OutputStream out, int indent) {
            this(value, new ByteWriter(out), indent);
        }

        public Encoder(Inspector value, AbstractByteWriter out, int indent) {
            this.top = value;
            this.out = out;
            this.indent = indent == 0 ? null : " ".repeat(indent).getBytes(UTF_8);
        }

        public void encode() throws IOException {
            encodeValue(top);
            if (indent != null) {
                out.append((byte) '\n');
            }
            out.flush();
        }

        private void encodeNIX() throws IOException {
            out.write(NULL);
        }

        private void encodeBOOL(boolean value) throws IOException {
            out.write(value ? TRUE : FALSE);
        }

        private void encodeLONG(long value) throws IOException {
            out.write(value);
        }

        private void encodeDOUBLE(double value) throws IOException {
            if (Double.isFinite(value)) {
                out.write(String.valueOf(value));
            } else {
                out.write(NULL);
            }
        }

        private void encodeSTRING(byte[] value) throws IOException {

            byte [] data = new byte[value.length * 6 + 2];
            int len = 2;
            int p = 0;
            data[p++] = '"';
            for (int pos = 0; pos < value.length; pos++) {
                byte c = value[pos];
                switch (c) {
                case '"':  data[p++] = '\\'; data[p++] = '"';  len += 2; break;
                case '\\': data[p++] = '\\'; data[p++] = '\\'; len += 2; break;
                case '\b': data[p++] = '\\'; data[p++] = 'b';  len += 2; break;
                case '\f': data[p++] = '\\'; data[p++] = 'f';  len += 2; break;
                case '\n': data[p++] = '\\'; data[p++] = 'n';  len += 2; break;
                case '\r': data[p++] = '\\'; data[p++] = 'r';  len += 2; break;
                case '\t': data[p++] = '\\'; data[p++] = 't';  len += 2; break;
                default:
                    if (c > 0x1f || c < 0) {
                        data[p++] = c;
                        len++;
                    } else { // requires escaping according to RFC 4627
                        data[p++] = '\\'; data[p++] = 'u'; data[p++] = '0'; data[p++] = '0';
                        data[p++] = HEX[(c >> 4) & 0xf]; data[p++] = HEX[c & 0xf];
                        len += 6;
                    }
                }
            }
            data[p] = '"';
            out.append(data, 0, len);
        }

        private void encodeDATA(byte[] value) throws IOException {
            int len = value.length * 2 + 4;
            byte [] data = new byte[len];
            int p = 0;

            data[p++] = '"'; data[p++] = '0'; data[p++] = 'x';
            for (int pos = 0; pos < value.length; pos++) {
                data[p++] = HEX[(value[pos] >> 4) & 0xf]; data[p++] = HEX[value[pos] & 0xf];
            }
            data[p] = '"';
            out.append(data, 0, len);
        }

        private void encodeARRAY(Inspector inspector) throws IOException {
            openScope((byte)'[');
            ArrayTraverser at = this;
            inspector.traverse(at);
            closeScope((byte)']');
        }

        private void encodeOBJECT(Inspector inspector) throws IOException {
            openScope((byte)'{');
            ObjectTraverser ot = this;
            inspector.traverse(ot);
            closeScope((byte) '}');
        }

        private void openScope(byte opener) throws IOException {
            out.append(opener);
            level++;
            head = true;
        }

        private void closeScope(byte closer) throws IOException {
            level--;
            separate(false);
            out.append(closer);
        }

        private void encodeValue(Inspector inspector) throws IOException {
            switch(inspector.type()) {
            case NIX:    encodeNIX();                        return;
            case BOOL:   encodeBOOL(inspector.asBool());     return;
            case LONG:   encodeLONG(inspector.asLong());     return;
            case DOUBLE: encodeDOUBLE(inspector.asDouble()); return;
            case STRING: encodeSTRING(inspector.asUtf8());   return;
            case DATA:   encodeDATA(inspector.asData());     return;
            case ARRAY:  encodeARRAY(inspector);             return;
            case OBJECT: encodeOBJECT(inspector);            return;
            }
            assert false : "Should not be reached";
        }

        private void separate(boolean useComma) throws IOException {
            boolean newline = ! head || useComma;
            if ( ! head && useComma) {
                out.append((byte)',');
            } else {
                head = false;
            }
            if (indent != null) {
                if (newline) {
                    out.append((byte) '\n');
                    for (int lvl = 0; lvl < level; lvl++) { out.append(indent); }
                } else {
                    out.append((byte) ' ');
                }
            }
        }

        public void entry(int idx, Inspector inspector) {
            try {
                separate(true);
                encodeValue(inspector);
            } catch (Exception e) {
                // FIXME: Should we fix ArrayTraverser/ObjectTraverser API or do something more fancy here?
                e.printStackTrace();
            }
        }

        public void field(String name, Inspector inspector)  {
            try {
                separate(true);
                encodeSTRING(Utf8Codec.encode(name));
                out.append((byte)':');
                if (indent != null)
                    out.append((byte) ' ');
                encodeValue(inspector);
            } catch (Exception e) {
                // FIXME: Should we fix ArrayTraverser/ObjectTraverser API or do something more fancy here?
                e.printStackTrace();
            }
        }
    }
}