-
Notifications
You must be signed in to change notification settings - Fork 653
/
MapJsonReader.kt
410 lines (353 loc) · 11.3 KB
/
MapJsonReader.kt
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
package com.apollographql.apollo3.api.json
import com.apollographql.apollo3.api.json.BufferedSourceJsonReader.Companion.MAX_STACK_SIZE
import com.apollographql.apollo3.api.json.MapJsonReader.Companion.buffer
import com.apollographql.apollo3.api.json.internal.toDoubleExact
import com.apollographql.apollo3.api.json.internal.toIntExact
import com.apollographql.apollo3.api.json.internal.toLongExact
import com.apollographql.apollo3.exception.JsonDataException
import kotlin.jvm.JvmOverloads
/**
* A [JsonReader] that reads data from a regular [Map<String, Any?>]
*
* Map values should be any of:
* - String
* - Int
* - Double
* - Long
* - JsonNumber
* - null
* - Map<String, Any?> where values are any of these values recursively
* - List<Any?> where values are any of these values recursively
*
* Anything else is undefined
*
* To read from a [okio.BufferedSource], see also [BufferedSourceJsonReader]
*
* @param root the root [Map] to read from
* @param pathRoot the path root to be prefixed to the returned path when calling [getPath]. Useful for [buffer].
*/
class MapJsonReader
@JvmOverloads
constructor(
val root: Map<String, Any?>,
private val pathRoot: List<Any> = emptyList(),
) : JsonReader {
private var peekedToken: JsonReader.Token
/**
* Depending on what [peekedToken] is, [peekedData] can be safely cast to a Map, Entry
* or other values
*/
private var peekedData: Any? = null
/**
* Can contain either:
* - an Int representing the next index to be read in a List
* - a String representing the current key to be read in a Map
* - null if peekedToken is BEGIN_OBJECT
*/
private val path = arrayOfNulls<Any>(MAX_STACK_SIZE)
/**
* The current object memorized in case we need to rewind
*/
private var containerStack = arrayOfNulls<Map<String, Any?>>(MAX_STACK_SIZE)
private val iteratorStack = arrayOfNulls<Iterator<*>>(MAX_STACK_SIZE)
private val nameIndexStack = IntArray(MAX_STACK_SIZE)
private var stackSize = 0
init {
peekedToken = JsonReader.Token.BEGIN_OBJECT
peekedData = root
}
private fun anyToToken(any: Any?) = when (any) {
null -> JsonReader.Token.NULL
is List<*> -> JsonReader.Token.BEGIN_ARRAY
is Map<*, *> -> JsonReader.Token.BEGIN_OBJECT
is Int -> JsonReader.Token.NUMBER
is Long -> JsonReader.Token.LONG
is Double -> JsonReader.Token.NUMBER
is JsonNumber -> JsonReader.Token.NUMBER
is String -> JsonReader.Token.STRING
is Boolean -> JsonReader.Token.BOOLEAN
else -> error("Unsupported value $any")
}
/**
* Updates [peekedToken] and [peekedData]
*
* Requires [iteratorStack] and [path]
*/
private fun advanceIterator() {
if (stackSize == 0) {
peekedToken = JsonReader.Token.END_DOCUMENT
return
}
val currentIterator = iteratorStack[stackSize - 1]!!
if (path[stackSize - 1] is Int) {
path[stackSize - 1] = (path[stackSize - 1] as Int) + 1
}
if (currentIterator.hasNext()) {
val next = currentIterator.next()
peekedData = next
peekedToken = when (next) {
is Map.Entry<*, *> -> JsonReader.Token.NAME
else -> anyToToken(next)
}
} else {
peekedToken = if (path[stackSize - 1] is Int) {
JsonReader.Token.END_ARRAY
} else {
JsonReader.Token.END_OBJECT
}
}
}
override fun beginArray() = apply {
if (peek() != JsonReader.Token.BEGIN_ARRAY) {
throw JsonDataException("Expected BEGIN_ARRAY but was ${peek()} at path ${getPathAsString()}")
}
val currentValue = peekedData as List<Any?>
check(stackSize < MAX_STACK_SIZE) {
"Nesting too deep"
}
stackSize++
path[stackSize - 1] = -1
iteratorStack[stackSize - 1] = currentValue.iterator()
advanceIterator()
}
override fun endArray() = apply {
if (peek() != JsonReader.Token.END_ARRAY) {
throw JsonDataException("Expected END_ARRAY but was ${peek()} at path ${getPathAsString()}")
}
stackSize--
iteratorStack[stackSize] = null // allow garbage collection
path[stackSize] = null // allow garbage collection
advanceIterator()
}
override fun beginObject() = apply {
if (peek() != JsonReader.Token.BEGIN_OBJECT) {
throw JsonDataException("Expected BEGIN_OBJECT but was ${peek()} at path ${getPathAsString()}")
}
check(stackSize < MAX_STACK_SIZE) {
"Nesting too deep"
}
stackSize++
@Suppress("UNCHECKED_CAST")
containerStack[stackSize - 1] = peekedData as Map<String, Any?>
rewind()
}
override fun endObject() = apply {
if (peek() != JsonReader.Token.END_OBJECT) {
throw JsonDataException("Expected END_OBJECT but was ${peek()} at path ${getPathAsString()}")
}
stackSize--
iteratorStack[stackSize] = null // allow garbage collection
path[stackSize] = null // allow garbage collection
containerStack[stackSize] = null // allow garbage collection
advanceIterator()
}
override fun hasNext(): Boolean {
return when (peek()) {
JsonReader.Token.END_OBJECT -> false
JsonReader.Token.END_ARRAY -> false
else -> true
}
}
override fun peek(): JsonReader.Token {
return peekedToken
}
override fun nextName(): String {
if (peek() != JsonReader.Token.NAME) {
throw JsonDataException("Expected NAME but was ${peek()} at path ${getPathAsString()}")
}
@Suppress("UNCHECKED_CAST")
val data = peekedData as Map.Entry<String, Any?>
path[stackSize - 1] = data.key
peekedData = data.value
peekedToken = anyToToken(data.value)
return data.key
}
override fun nextString(): String? {
// If we have a number, we convert it to a string
when (peek()) {
JsonReader.Token.STRING,
JsonReader.Token.NUMBER,
JsonReader.Token.LONG,
-> Unit
else -> {
throw JsonDataException("Expected a String but was ${peek()} at path ${getPathAsString()}")
}
}
return (peekedData!!.toString()).also {
advanceIterator()
}
}
override fun nextBoolean(): Boolean {
if (peek() != JsonReader.Token.BOOLEAN) {
throw JsonDataException("Expected BOOLEAN but was ${peek()} at path ${getPathAsString()}")
}
return (peekedData as Boolean).also {
advanceIterator()
}
}
override fun nextNull(): Nothing? {
if (peek() != JsonReader.Token.NULL) {
throw JsonDataException("Expected NULL but was ${peek()} at path ${getPathAsString()}")
}
advanceIterator()
return null
}
override fun nextDouble(): Double {
when (peek()) {
JsonReader.Token.STRING,
JsonReader.Token.NUMBER,
JsonReader.Token.LONG,
-> Unit
else -> {
throw JsonDataException("Expected a Double but was ${peek()} at path ${getPathAsString()}")
}
}
return when (val value = peekedData) {
is Int -> value.toDouble()
is Long -> value.toDoubleExact()
is Double -> value
is String -> value.toDouble()
is JsonNumber -> value.value.toDouble()
else -> error("Expected a Double but got $value instead")
}.also {
advanceIterator()
}
}
override fun nextInt(): Int {
when (peek()) {
JsonReader.Token.STRING,
JsonReader.Token.NUMBER,
JsonReader.Token.LONG,
-> Unit
else -> {
throw JsonDataException("Expected an Int but was ${peek()} at path ${getPathAsString()}")
}
}
return when (val value = peekedData) {
is Int -> value
is Long -> value.toIntExact()
is Double -> value.toIntExact()
is String -> value.toInt()
is JsonNumber -> value.value.toInt()
else -> error("Expected an Int but got $value instead")
}.also {
advanceIterator()
}
}
override fun nextLong(): Long {
when (peek()) {
JsonReader.Token.STRING,
JsonReader.Token.NUMBER,
JsonReader.Token.LONG,
-> Unit
else -> {
throw JsonDataException("Expected a Long but was ${peek()} at path ${getPathAsString()}")
}
}
return when (val value = peekedData) {
is Int -> value.toLong()
is Long -> value
is Double -> value.toLongExact()
is String -> value.toLong()
is JsonNumber -> value.value.toLong()
else -> error("Expected Int but got $value instead")
}.also {
advanceIterator()
}
}
override fun nextNumber(): JsonNumber {
when (peek()) {
JsonReader.Token.STRING,
JsonReader.Token.NUMBER,
JsonReader.Token.LONG,
-> Unit
else -> {
throw JsonDataException("Expected a Number but was ${peek()} at path ${getPathAsString()}")
}
}
return when (val value = peekedData) {
is Int, is Long, is Double -> JsonNumber(value.toString())
is String -> JsonNumber(value) // assert value is a valid number
is JsonNumber -> value
else -> error("Expected JsonNumber but got $value instead")
}.also {
advanceIterator()
}
}
override fun skipValue() {
advanceIterator()
}
override fun close() {
}
private fun findName(needle: String, haystack: List<String>): Int {
val expectedIndex = nameIndexStack[stackSize - 1]
if (expectedIndex < haystack.size && haystack[expectedIndex] == needle) {
/**
* Our guess succeeded
*
* Note that for a same object, haystack might have different size.
* For an example, for responseBased codegen and polymorphic fields, this is going
* to be called once with just ["__typename"] and then later on with ["__typename", "id", "name"]
*/
nameIndexStack[stackSize - 1] = nameIndexStack[stackSize - 1] + 1
return expectedIndex
} else {
// guess failed, go back to full search
val index = haystack.indexOf(needle)
if (index != -1) {
// reset the prediction
nameIndexStack[stackSize - 1] = index + 1
}
return index
}
}
override fun selectName(names: List<String>): Int {
while (hasNext()) {
val name = nextName()
val index = findName(name, names)
if (index != -1) {
return index
}
// A name was present in the json but not in the expected list
skipValue()
}
return -1
}
/**
* Rewinds to the beginning of the current object.
*/
override fun rewind() {
val container = containerStack[stackSize - 1]
path[stackSize - 1] = null
iteratorStack[stackSize - 1] = container!!.iterator()
nameIndexStack[stackSize - 1] = 0
advanceIterator()
}
override fun getPath(): List<Any> {
val result = mutableListOf<Any>()
result.addAll(pathRoot)
for (index in 0 until stackSize) {
path[index]?.let { result += it }
}
return result
}
private fun getPathAsString() = getPath().joinToString(".")
companion object {
/**
* buffers the next Object. Has to be called in `BEGIN_OBJECT` position.
* The returned [MapJsonReader] can use [MapJsonReader.rewind] to read fields
* multiple times
*/
fun JsonReader.buffer(): MapJsonReader {
if (this is MapJsonReader) return this
val token = this.peek()
check(token == JsonReader.Token.BEGIN_OBJECT) {
"Failed to buffer json reader, expected `BEGIN_OBJECT` but found `$token` json token"
}
val pathRoot = getPath()
@Suppress("UNCHECKED_CAST")
val data = this.readAny() as Map<String, Any?>
return MapJsonReader(root = data, pathRoot = pathRoot)
}
}
}