-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathJSONWriter.java
More file actions
252 lines (236 loc) · 6.74 KB
/
Copy pathJSONWriter.java
File metadata and controls
252 lines (236 loc) · 6.74 KB
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
247
248
249
250
251
252
package charred;
import java.io.Writer;
import java.io.IOException;
import java.io.Flushable;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.function.BiConsumer;
import java.util.List;
import java.util.Map;
import clojure.lang.Ratio;
public class JSONWriter implements AutoCloseable, Flushable {
int indent;
//All output goes through this unsynchronized buffer - w is the same object.
public final Writer w;
final UnsyncBufferedWriter bw;
public final boolean escapeJSSep;
public final boolean escapeSlash;
public final boolean escapeUnicode;
public final String indentStr;
public final BiConsumer<JSONWriter,Object> objConsumer;
final CharBuffer charBuffer;
public JSONWriter(Writer _w,
boolean _escapeJSSep,
boolean _escapeSlash,
boolean _escapeUnicode,
String _indentStr,
BiConsumer<JSONWriter,Object> _objConsumer) {
bw = _w instanceof UnsyncBufferedWriter ? (UnsyncBufferedWriter)_w : new UnsyncBufferedWriter(_w);
w = bw;
indent = 0;
charBuffer = new CharBuffer();
escapeJSSep = _escapeJSSep;
escapeSlash = _escapeSlash;
escapeUnicode = _escapeUnicode;
indentStr = _indentStr != null && _indentStr.length() != 0 ? _indentStr : null;
objConsumer = _objConsumer;
}
public int indent() { return indent; }
public void indent(int i) { indent = i; }
public CharBuffer charBuffer() { charBuffer.clear(); return charBuffer; }
public static void escape(final CharBuffer cb, final char data) {
cb.append('\\');
cb.append(data);
}
static final char[] HEX = "0123456789abcdef".toCharArray();
public static void toHexString(final CharBuffer cb, final char data) {
escape(cb, 'u');
cb.append(HEX[(data >> 12) & 0xF]);
cb.append(HEX[(data >> 8) & 0xF]);
cb.append(HEX[(data >> 4) & 0xF]);
cb.append(HEX[data & 0xF]);
}
public static void writeBuffer(Writer w, CharBuffer b) throws IOException {
w.write(b.buffer(), 0, b.length());
}
public static boolean isJSSep(final char data) {
return data == 8232 || data == 8233;
}
public void writeStringFallback(CharBuffer cb, CharSequence data) throws IOException {
final int dlen = data.length();
for (int idx = 0; idx < dlen; ++idx ) {
final char cdata = data.charAt(idx);
switch(cdata) {
case '\\':
case '"':
escape(cb,cdata);
break;
case '/':
if (escapeSlash)
escape(cb,cdata);
else
cb.append(cdata);
break;
case '\f': escape(cb,'f'); break;
case '\n': escape(cb, 'n'); break;
case '\r': escape(cb, 'r'); break;
case '\b': escape(cb, 'b'); break;
case '\t': escape(cb, 't'); break;
default:
if (cdata < 32 ||
(escapeJSSep && isJSSep(cdata))) {
toHexString(cb, cdata);
} else if (escapeUnicode && (cdata >= 128)) {
toHexString(cb,cdata);
} else {
cb.append(cdata);
}
break;
}
}
}
public void writeString(CharSequence data) throws IOException {
final int dlen = data.length();
int idx = 0;
while (idx < dlen) {
final char c = data.charAt(idx);
final int cInt = (int) c;
if (cInt >= 32 && cInt < 128
&& cInt != 34 // "
&& cInt != 92 // \
&& cInt != 47 // /
) {
++idx;
} else {
break;
}
}
final UnsyncBufferedWriter writer = bw;
//Common case - nothing to escape so write the string straight through.
if (idx == dlen && data instanceof String) {
writer.write('"');
writer.write((String)data);
writer.write('"');
return;
}
final CharBuffer cb = charBuffer();
cb.append('"');
cb.append(data.subSequence(0, idx));
writeStringFallback(cb,data.subSequence(idx, dlen));
cb.append('"');
writeBuffer(writer,cb);
}
public void writeNumber(Number n) throws Exception {
if (n instanceof Long || n instanceof Integer || n instanceof Short || n instanceof Byte) {
bw.writeLong(n.longValue());
return;
}
if (n instanceof Ratio)
n = ((Ratio)n).doubleValue();
if (n instanceof Double) {
final Double dn = (Double)n;
if (!Double.isFinite(dn)) {
if (Double.isNaN(dn))
throw new CharredException("JSON encoding error - NAN detected");
else
throw new CharredException("JSON encoding error - +/-INF detected");
}
} else if (n instanceof Float) {
final Float dn = (Float)n;
if (!Float.isFinite(dn)) {
if (Float.isNaN(dn))
throw new CharredException("JSON encoding error - NAN detected");
else
throw new CharredException("JSON encoding error - +/-INF detected");
}
}
w.write(n.toString());
}
public void writeIndent() throws Exception {
if (indent == 0 || indentStr == null)
return;
if (indent == 1)
w.write(indentStr);
else {
for(int idx = 0; idx < indent; ++idx)
w.write(indentStr);
}
}
public void writeObject(Object obj) throws Exception {
final BiConsumer<JSONWriter,Object> consumer = objConsumer;
if (obj instanceof String) {
writeString((String)obj);
} else if (obj instanceof Number) {
writeNumber((Number)obj);
} else if (obj == null) {
w.write("null");
}
else if (obj instanceof Boolean) {
if ((Boolean)obj)
w.write("true");
else
w.write("false");
} else {
//We bail here to the consumer so we can do things like stringify keywords and such.
//Thus we accept a very small hit to perf in the case where that isn't necessary.
consumer.accept(this,obj);
}
}
public void writeArray(Iterator<Object> iter) throws Exception {
++indent;
w.write('[');
boolean first = true;
for(boolean c = iter.hasNext(); c; c = iter.hasNext() ) {
if(!first)
w.write(',');
first = false;
writeObject(iter.next());
}
w.write(']');
--indent;
}
public void writeMap(Iterator<Map.Entry> iter) throws Exception {
final boolean hasIndent = indentStr != null;
if (hasIndent) {
if (indent != 0) w.write('\n');
writeIndent();
}
w.write('{');
++indent;
boolean first = true;
for (boolean c = iter.hasNext(); c; c = iter.hasNext()) {
Map.Entry val = iter.next();
Object k = val.getKey();
Object v = val.getValue();
if (! (k instanceof String) )
k = String.valueOf(k);
if (!first) {
w.write(",");
}
if(hasIndent) {
w.write('\n');
writeIndent();
}
first = false;
writeString((String)k);
if(hasIndent)
w.write(": ");
else
w.write(":");
writeObject(v);
}
--indent;
if (hasIndent && !first) {
w.write('\n');
writeIndent();
}
w.write('}');
}
public void close() throws Exception {
w.close();
}
public void flush() throws IOException {
w.flush();
}
}