Repository navigation
Expand file tree
/
Copy pathJson.java
More file actions
511 lines (467 loc) · 19.6 KB
/
Copy pathJson.java
File metadata and controls
511 lines (467 loc) · 19.6 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package com.qoder.taskdeck;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Hand-written JSON for the ledger wire format — no org.json (it is a stub in
* android.jar that throws on the JVM), no Gson, no regex anywhere.
*
* <p>Parse yields plain JDK containers: {@link LinkedHashMap}, {@link ArrayList},
* String, Long (integers), Double (anything with a fraction or exponent),
* Boolean and null. Write accepts exactly those, emits map keys in sorted
* order with two-space pretty indentation and the same {@code " : "}
* separator the Mac's {@code JSONEncoder([.prettyPrinted, .sortedKeys])}
* produces, so a store rendered by either side is textually comparable.
*
* <p>{@link #iso8601(long)} and {@link #parseIso8601(String)} implement the
* date text used for every timestamp: fractional-second output, and input that
* accepts both fractional and whole-second forms with either a {@code Z} or a
* {@code ±HH:mm} offset.
*/
public final class Json {
private Json() {
}
// ------------------------------------------------------------------ parse
/**
* Parses a complete JSON document.
*
* @throws IllegalArgumentException on any malformed input
*/
public static Object parse(String text) {
if (text == null) throw new IllegalArgumentException("cannot parse null");
Parser p = new Parser(text);
Object value = p.readValue();
p.skipWhitespace();
if (!p.atEnd()) throw p.error("trailing characters after document");
return value;
}
/** Recursive-descent scanner. Index arithmetic only — no regex, no substring copies. */
private static final class Parser {
private final String s;
private int i;
Parser(String s) {
this.s = s;
}
boolean atEnd() {
return i >= s.length();
}
IllegalArgumentException error(String message) {
return new IllegalArgumentException(message + " (at index " + i + ")");
}
char peek() {
if (i >= s.length()) throw error("unexpected end of input");
return s.charAt(i);
}
void skipWhitespace() {
while (i < s.length()) {
char c = s.charAt(i);
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') i++;
else break;
}
}
Object readValue() {
skipWhitespace();
char c = peek();
switch (c) {
case '{': return readObject();
case '[': return readArray();
case '"': return readString();
case 't': expectWord("true"); return Boolean.TRUE;
case 'f': expectWord("false"); return Boolean.FALSE;
case 'n': expectWord("null"); return null;
default: return readNumber();
}
}
private void expectWord(String word) {
if (!s.startsWith(word, i)) throw error("expected " + word);
i += word.length();
}
private Map<String, Object> readObject() {
Map<String, Object> m = new LinkedHashMap<String, Object>();
i++; // '{'
skipWhitespace();
if (peek() == '}') { i++; return m; }
while (true) {
skipWhitespace();
if (peek() != '"') throw error("expected a quoted key");
String key = readString();
skipWhitespace();
if (peek() != ':') throw error("expected ':' after key");
i++;
m.put(key, readValue());
skipWhitespace();
char c = peek();
if (c == ',') { i++; continue; }
if (c == '}') { i++; return m; }
throw error("expected ',' or '}'");
}
}
private List<Object> readArray() {
List<Object> a = new ArrayList<Object>();
i++; // '['
skipWhitespace();
if (peek() == ']') { i++; return a; }
while (true) {
a.add(readValue());
skipWhitespace();
char c = peek();
if (c == ',') { i++; continue; }
if (c == ']') { i++; return a; }
throw error("expected ',' or ']'");
}
}
/**
* Strings are scanned character by character; everything the Mac can
* emit is handled, including escaped quotes and braces so a nested
* {@code "{\"k\":v}"} payload terminates on the real closing quote.
*/
private String readString() {
int start = i; // at opening quote
i++;
StringBuilder sb = null; // stays null while the literal needs no unescaping
while (true) {
if (i >= s.length()) throw error("unterminated string");
char c = s.charAt(i);
if (c == '"') {
i++;
return sb == null ? s.substring(start + 1, i - 1) : sb.toString();
}
if (c == '\\') {
if (sb == null) {
sb = new StringBuilder(s.length() - start);
sb.append(s, start + 1, i);
}
i++;
char e = peek();
i++;
switch (e) {
case '"': sb.append('"'); break;
case '\\': sb.append('\\'); break;
case '/': sb.append('/'); break;
case 'b': sb.append('\b'); break;
case 'f': sb.append('\f'); break;
case 'n': sb.append('\n'); break;
case 'r': sb.append('\r'); break;
case 't': sb.append('\t'); break;
case 'u': {
int cp = 0;
for (int k = 0; k < 4; k++) {
char h = peek();
i++;
int d = Character.digit(h, 16);
if (d < 0) throw error("bad hex digit in \\u escape");
cp = cp * 16 + d;
}
sb.append((char) cp);
break;
}
default: throw error("bad escape '\\" + e + "'");
}
continue;
}
if (c < 0x20) throw error("raw control character inside string");
i++;
if (sb != null) sb.append(c);
}
}
/** Integers become Long, anything with a fraction or exponent becomes Double. */
private Object readNumber() {
int start = i;
if (peek() == '-') i++;
int digitsStart = i;
while (i < s.length() && isDigit(s.charAt(i))) i++;
if (i == digitsStart) throw error("value expected");
boolean real = false;
if (i < s.length() && s.charAt(i) == '.') {
real = true;
i++;
int fracStart = i;
while (i < s.length() && isDigit(s.charAt(i))) i++;
if (i == fracStart) throw error("digits expected after '.'");
}
if (i < s.length() && (s.charAt(i) == 'e' || s.charAt(i) == 'E')) {
real = true;
i++;
if (i < s.length() && (s.charAt(i) == '+' || s.charAt(i) == '-')) i++;
int expStart = i;
while (i < s.length() && isDigit(s.charAt(i))) i++;
if (i == expStart) throw error("digits expected in exponent");
}
String raw = s.substring(start, i);
if (!real) {
try {
return Long.valueOf(Long.parseLong(raw));
} catch (NumberFormatException overflow) {
return Double.valueOf(Double.parseDouble(raw));
}
}
return Double.valueOf(Double.parseDouble(raw));
}
}
private static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
// ------------------------------------------------------------------ write
/** Serialises Maps/Lists/Strings/Numbers/Booleans/null to pretty JSON. */
public static String write(Object value) {
StringBuilder sb = new StringBuilder(1024);
writeValue(sb, value, 0);
return sb.toString();
}
private static void writeValue(StringBuilder sb, Object v, int depth) {
if (v == null) {
sb.append("null");
} else if (v instanceof Map) {
writeMap(sb, (Map<?, ?>) v, depth);
} else if (v instanceof List) {
writeList(sb, (List<?>) v, depth);
} else if (v instanceof String) {
writeString(sb, (String) v);
} else if (v instanceof Boolean) {
sb.append(((Boolean) v).booleanValue() ? "true" : "false");
} else if (v instanceof Number) {
writeNumber(sb, (Number) v);
} else {
throw new IllegalArgumentException("cannot JSON-encode " + v.getClass().getName());
}
}
/** Keys sorted like the Mac encoder; insertion order preserved otherwise. */
private static void writeMap(StringBuilder sb, Map<?, ?> map, int depth) {
TreeMap<String, Object> sorted = new TreeMap<String, Object>();
for (Map.Entry<?, ?> e : map.entrySet()) {
sorted.put(String.valueOf(e.getKey()), e.getValue());
}
if (sorted.isEmpty()) {
// Swift's pretty printer emits an empty container as "{\n\n<indent>}".
sb.append("{\n\n");
pad(sb, depth);
sb.append('}');
return;
}
sb.append("{\n");
int written = 0;
int total = sorted.size();
for (Map.Entry<String, Object> e : sorted.entrySet()) {
pad(sb, depth + 1);
writeString(sb, e.getKey());
sb.append(" : ");
writeValue(sb, e.getValue(), depth + 1);
if (++written < total) sb.append(',');
sb.append('\n');
}
pad(sb, depth);
sb.append('}');
}
private static void writeList(StringBuilder sb, List<?> list, int depth) {
if (list.isEmpty()) {
sb.append("[\n\n");
pad(sb, depth);
sb.append(']');
return;
}
sb.append("[\n");
for (int i = 0; i < list.size(); i++) {
pad(sb, depth + 1);
writeValue(sb, list.get(i), depth + 1);
sb.append(i + 1 < list.size() ? ",\n" : "\n");
}
pad(sb, depth);
sb.append(']');
}
private static void pad(StringBuilder sb, int depth) {
for (int i = 0; i < depth; i++) sb.append(" ");
}
private static void writeNumber(StringBuilder sb, Number n) {
if (n instanceof Double || n instanceof Float) {
double d = n.doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d)) {
throw new IllegalArgumentException("cannot JSON-encode " + d);
}
if (d == Math.rint(d) && Math.abs(d) < 1e15) {
sb.append((long) d); // whole-valued doubles print without ".0", as Int does
} else {
sb.append(n.toString());
}
} else {
sb.append(n.toString());
}
}
/**
* Escaping mirrors the Mac's encoder ({@code " }, {@code \ }, {@code /})
* plus the JSON-mandated control-character forms; U+2028 and U+2029 are
* escaped so output is safe to embed in JavaScript, and everything else
* passes through as raw UTF-8 exactly like Foundation does.
*/
private static void writeString(StringBuilder sb, String s) {
sb.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '"') sb.append("\\\"");
else if (c == '\\') sb.append("\\\\");
else if (c == '/') sb.append("\\/");
else if (c == '\n') sb.append("\\n");
else if (c == '\r') sb.append("\\r");
else if (c == '\t') sb.append("\\t");
else if (c == '\b') sb.append("\\b");
else if (c == '\f') sb.append("\\f");
else if (c < 0x20) sb.append("\\u00").append(HEX[(c >> 4) & 0xF]).append(HEX[c & 0xF]);
else if (c == '\u2028') sb.append("\\u2028");
else if (c == '\u2029') sb.append("\\u2029");
else sb.append(c);
}
sb.append('"');
}
private static final char[] HEX = "0123456789ABCDEF".toCharArray();
// ------------------------------------------------------------------- time
/**
* Formats epoch millis exactly the way {@code ISO8601DateFormatter} with
* {@code .withInternetDateTime, .withFractionalSeconds} does: always three
* fraction digits, always UTC — e.g. {@code 2026-09-22T20:14:30.531Z}.
* Pure integer math (Howard Hinnant's days-from-civil), no Calendar, so
* there is no locale or default-timezone surprise on either runtime.
*/
public static String iso8601(long millis) {
long days = millis / MILLIS_PER_DAY;
long rem = millis % MILLIS_PER_DAY;
if (rem < 0) { rem += MILLIS_PER_DAY; days--; }
int hour = (int) (rem / 3600000L);
rem %= 3600000L;
int minute = (int) (rem / 60000L);
rem %= 60000L;
int second = (int) (rem / 1000L);
int ms = (int) (rem % 1000L);
long z = days + 719468L;
long era = (z >= 0 ? z : z - 146096L) / 146097L;
long doe = z - era * 146097L;
long yoe = (doe - doe / 1460L + doe / 36524L - doe / 146096L) / 365L;
long y = yoe + era * 400L;
long doy = doe - (365L * yoe + yoe / 4L - yoe / 100L);
long mp = (5L * doy + 2L) / 153L;
long d = doy - (153L * mp + 2L) / 5L + 1L;
long m = mp + (mp < 10L ? 3L : -9L);
y += (m <= 2L) ? 1L : 0L;
StringBuilder sb = new StringBuilder(24);
padNumber(sb, y, 4);
sb.append('-');
padNumber(sb, m, 2);
sb.append('-');
padNumber(sb, d, 2);
sb.append("T");
padNumber(sb, hour, 2);
sb.append(':');
padNumber(sb, minute, 2);
sb.append(':');
padNumber(sb, second, 2);
sb.append('.');
padNumber(sb, ms, 3);
sb.append('Z');
return sb.toString();
}
private static void padNumber(StringBuilder sb, long value, int width) {
if (value < 0) { sb.append('-'); value = -value; }
long pow = 1;
for (int i = 1; i < width; i++) pow *= 10;
for (long v = value; v < pow && pow > 1; pow /= 10) sb.append('0');
sb.append(value);
}
private static final long MILLIS_PER_DAY = 86400000L;
/**
* Parses ISO-8601 internet date-times, fractional ({@code .531}) or whole
* seconds, with a {@code Z} or {@code ±HH[:mm]} offset — the two forms the
* Mac's decoder accepts on read. Throws IllegalArgumentException on garbage.
*/
public static long parseIso8601(String text) {
if (text == null) throw new IllegalArgumentException("null date string");
int n = text.length();
int i = 0;
int year = readDigits(text, i, 4, "year"); i += 4;
expect(text, i, '-', "date separator"); i++;
int month = readDigits(text, i, 2, "month"); i += 2;
expect(text, i, '-', "date separator"); i++;
int day = readDigits(text, i, 2, "day"); i += 2;
expect(text, i, 'T', "date/time separator"); i++;
int hour = readDigits(text, i, 2, "hour"); i += 2;
expect(text, i, ':', "time separator"); i++;
int minute = readDigits(text, i, 2, "minute"); i += 2;
expect(text, i, ':', "time separator"); i++;
int second = readDigits(text, i, 2, "second"); i += 2;
if (month < 1 || month > 12) throw bad(text, "month out of range");
if (day < 1 || day > daysInMonth(year, month)) throw bad(text, "day out of range");
if (hour > 23 || minute > 59 || second > 60) throw bad(text, "time out of range");
int ms = 0;
if (i < n && (text.charAt(i) == '.' || text.charAt(i) == ',')) {
i++;
int fracStart = i;
while (i < n && isDigit(text.charAt(i))) i++;
int digits = i - fracStart;
if (digits == 0) throw bad(text, "digits expected after the decimal point");
if (digits > 9) throw bad(text, "too many fractional digits");
long frac = 0;
for (int k = fracStart; k < i; k++) frac = frac * 10 + (text.charAt(k) - '0');
long scale = 1;
for (int k = 0; k < digits; k++) scale *= 10;
ms = (int) (frac * 1000L / scale); // truncated beyond millis, like the Mac
}
long offsetSeconds = 0;
if (i >= n) throw bad(text, "time zone missing");
char zc = text.charAt(i);
if (zc == 'Z' || zc == 'z') {
i++;
} else if (zc == '+' || zc == '-') {
int sign = zc == '-' ? -1 : 1;
i++;
int offHour = readDigits(text, i, 2, "offset hour"); i += 2;
if (i < n && text.charAt(i) == ':') i++;
int offMinute = readDigits(text, i, 2, "offset minute"); i += 2;
if (offHour > 23 || offMinute > 59) throw bad(text, "offset out of range");
offsetSeconds = sign * (offHour * 3600L + offMinute * 60L);
} else {
throw bad(text, "unrecognised time zone");
}
if (i != n) throw bad(text, "trailing characters");
long epochDay = daysFromCivil(year, month, day);
long seconds = ((epochDay * 24L + hour) * 60L + minute) * 60L + second - offsetSeconds;
return seconds * 1000L + ms;
}
private static void expect(String s, int i, char c, String what) {
if (i >= s.length()) throw bad(s, "truncated before " + what);
if (s.charAt(i) != c) throw bad(s, "expected '" + c + "' for " + what);
}
private static int readDigits(String s, int from, int count, String what) {
int v = 0;
for (int k = 0; k < count; k++) {
int idx = from + k;
if (idx >= s.length()) throw bad(s, "truncated " + what);
char c = s.charAt(idx);
if (!isDigit(c)) throw bad(s, "non-digit in " + what);
v = v * 10 + (c - '0');
}
return v;
}
private static IllegalArgumentException bad(String text, String message) {
return new IllegalArgumentException("not ISO-8601 (" + message + "): \"" + text + "\"");
}
/** Days since 1970-01-01 for a proleptic-Gregorian y/m/d; Hinnant's days_from_civil. */
private static long daysFromCivil(int y, int m, int d) {
long year = y;
year -= m <= 2 ? 1 : 0;
long era = (year >= 0 ? year : year - 399L) / 400L;
long yoe = year - era * 400L;
long doy = (153L * (m + (m > 2 ? -3 : 9)) + 2L) / 5L + d - 1L;
long doe = yoe * 365L + yoe / 4L - yoe / 100L + doy;
return era * 146097L + doe - 719468L;
}
private static int daysInMonth(int year, int month) {
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return isLeap(year) ? 29 : 28;
default: return 0;
}
}
private static boolean isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}