/
StreamingJsonDecoder.kt
378 lines (333 loc) · 14.5 KB
/
StreamingJsonDecoder.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
/*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME
import kotlinx.serialization.internal.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.jvm.*
/**
* [JsonDecoder] which reads given JSON from [AbstractJsonLexer] field by field.
*/
@OptIn(ExperimentalSerializationApi::class, ExperimentalUnsignedTypes::class)
internal open class StreamingJsonDecoder(
final override val json: Json,
private val mode: WriteMode,
@JvmField internal val lexer: AbstractJsonLexer,
descriptor: SerialDescriptor,
discriminatorHolder: DiscriminatorHolder?
) : JsonDecoder, AbstractDecoder() {
// A mutable reference to the discriminator that have to be skipped when in optimistic phase
// of polymorphic serialization, see `decodeSerializableValue`
internal class DiscriminatorHolder(@JvmField var discriminatorToSkip: String?)
private fun DiscriminatorHolder?.trySkip(unknownKey: String): Boolean {
if (this == null) return false
if (discriminatorToSkip == unknownKey) {
discriminatorToSkip = null
return true
}
return false
}
override val serializersModule: SerializersModule = json.serializersModule
private var currentIndex = -1
private var discriminatorHolder: DiscriminatorHolder? = discriminatorHolder
private val configuration = json.configuration
private val elementMarker: JsonElementMarker? = if (configuration.explicitNulls) null else JsonElementMarker(descriptor)
override fun decodeJsonElement(): JsonElement = JsonTreeReader(json.configuration, lexer).read()
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T {
try {
/*
* This is an optimized path over decodeSerializableValuePolymorphic(deserializer):
* dSVP reads the very next JSON tree into a memory as JsonElement and then runs TreeJsonDecoder over it
* in order to deal with an arbitrary order of keys, but with the price of additional memory pressure
* and CPU consumption.
* We would like to provide best possible performance for data produced by kotlinx.serialization
* itself, for that we do the following optimistic optimization:
*
* 0) Remember current position in the string
* 1) Read the very next key of JSON structure
* 2) If it matches* the descriminator key, read the value, remember current position
* 3) Return the value, recover an initial position
* (*) -- if it doesn't match, fallback to dSVP method.
*/
if (deserializer !is AbstractPolymorphicSerializer<*> || json.configuration.useArrayPolymorphism) {
return deserializer.deserialize(this)
}
val discriminator = deserializer.descriptor.classDiscriminator(json)
val type = lexer.consumeLeadingMatchingValue(discriminator, configuration.isLenient)
var actualSerializer: DeserializationStrategy<out Any>? = null
if (type != null) {
actualSerializer = deserializer.findPolymorphicSerializerOrNull(this, type)
}
if (actualSerializer == null) {
// Fallback if we haven't found discriminator or serializer
return decodeSerializableValuePolymorphic<T>(deserializer as DeserializationStrategy<T>)
}
discriminatorHolder = DiscriminatorHolder(discriminator)
@Suppress("UNCHECKED_CAST")
val result = actualSerializer.deserialize(this) as T
return result
} catch (e: MissingFieldException) {
throw MissingFieldException(e.message + " at path: " + lexer.path.getPath(), e)
}
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
val newMode = json.switchMode(descriptor)
lexer.path.pushDescriptor(descriptor)
lexer.consumeNextToken(newMode.begin)
checkLeadingComma()
return when (newMode) {
// In fact resets current index that these modes rely on
WriteMode.LIST, WriteMode.MAP, WriteMode.POLY_OBJ -> StreamingJsonDecoder(
json,
newMode,
lexer,
descriptor,
discriminatorHolder
)
else -> if (mode == newMode && json.configuration.explicitNulls) {
this
} else {
StreamingJsonDecoder(json, newMode, lexer, descriptor, discriminatorHolder)
}
}
}
override fun endStructure(descriptor: SerialDescriptor) {
// If we're ignoring unknown keys, we have to skip all undecoded elements,
// e.g. for object serialization. It can be the case when the descriptor does
// not have any elements and decodeElementIndex is not invoked at all
if (json.configuration.ignoreUnknownKeys && descriptor.elementsCount == 0) {
skipLeftoverElements(descriptor)
}
// First consume the object so we know it's correct
lexer.consumeNextToken(mode.end)
// Then cleanup the path
lexer.path.popDescriptor()
}
private fun skipLeftoverElements(descriptor: SerialDescriptor) {
while (decodeElementIndex(descriptor) != DECODE_DONE) {
// Skip elements
}
}
override fun decodeNotNullMark(): Boolean {
return !(elementMarker?.isUnmarkedNull ?: false) && lexer.tryConsumeNotNull()
}
override fun decodeNull(): Nothing? {
// Do nothing, null was consumed by `decodeNotNullMark`
return null
}
private fun checkLeadingComma() {
if (lexer.peekNextToken() == TC_COMMA) {
lexer.fail("Unexpected leading comma")
}
}
override fun <T> decodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T>,
previousValue: T?
): T {
val isMapKey = mode == WriteMode.MAP && index and 1 == 0
// Reset previous key
if (isMapKey) {
lexer.path.resetCurrentMapKey()
}
// Deserialize the key
val value = super.decodeSerializableElement(descriptor, index, deserializer, previousValue)
// Put the key to the path
if (isMapKey) {
lexer.path.updateCurrentMapKey(value)
}
return value
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
val index = when (mode) {
WriteMode.OBJ -> decodeObjectIndex(descriptor)
WriteMode.MAP -> decodeMapIndex()
else -> decodeListIndex() // Both for LIST and default polymorphic
}
// The element of the next index that will be decoded
if (mode != WriteMode.MAP) {
lexer.path.updateDescriptorIndex(index)
}
return index
}
private fun decodeMapIndex(): Int {
var hasComma = false
val decodingKey = currentIndex % 2 != 0
if (decodingKey) {
if (currentIndex != -1) {
hasComma = lexer.tryConsumeComma()
}
} else {
lexer.consumeNextToken(COLON)
}
return if (lexer.canConsumeValue()) {
if (decodingKey) {
if (currentIndex == -1) lexer.require(!hasComma) { "Unexpected trailing comma" }
else lexer.require(hasComma) { "Expected comma after the key-value pair" }
}
++currentIndex
} else {
if (hasComma) lexer.fail("Expected '}', but had ',' instead")
CompositeDecoder.DECODE_DONE
}
}
/*
* Checks whether JSON has `null` value for non-null property or unknown enum value for enum property
*/
private fun coerceInputValue(descriptor: SerialDescriptor, index: Int): Boolean = json.tryCoerceValue(
descriptor.getElementDescriptor(index),
{ !lexer.tryConsumeNotNull() },
{ lexer.peekString(configuration.isLenient) },
{ lexer.consumeString() /* skip unknown enum string*/ }
)
@Suppress("INVISIBLE_MEMBER")
private fun decodeObjectIndex(descriptor: SerialDescriptor): Int {
// hasComma checks are required to properly react on trailing commas
var hasComma = lexer.tryConsumeComma()
while (lexer.canConsumeValue()) { // TODO: consider merging comma consumption and this check
hasComma = false
val key = decodeStringKey()
lexer.consumeNextToken(COLON)
val index = descriptor.getJsonNameIndex(json, key)
val isUnknown = if (index != UNKNOWN_NAME) {
if (configuration.coerceInputValues && coerceInputValue(descriptor, index)) {
hasComma = lexer.tryConsumeComma()
false // Known element, but coerced
} else {
elementMarker?.mark(index)
return index // Known element without coercing, return it
}
} else {
true // unknown element
}
if (isUnknown) { // slow-path for unknown keys handling
hasComma = handleUnknown(key)
}
}
if (hasComma) lexer.fail("Unexpected trailing comma")
return elementMarker?.nextUnmarkedIndex() ?: CompositeDecoder.DECODE_DONE
}
private fun handleUnknown(key: String): Boolean {
if (configuration.ignoreUnknownKeys || discriminatorHolder.trySkip(key)) {
lexer.skipElement(configuration.isLenient)
} else {
// Here we cannot properly update json path indicies
// as we do not have a proper SerialDecriptor in our hands
lexer.failOnUnknownKey(key)
}
return lexer.tryConsumeComma()
}
private fun decodeListIndex(): Int {
// Prohibit leading comma
val hasComma = lexer.tryConsumeComma()
return if (lexer.canConsumeValue()) {
if (currentIndex != -1 && !hasComma) lexer.fail("Expected end of the array or comma")
++currentIndex
} else {
if (hasComma) lexer.fail("Unexpected trailing comma")
CompositeDecoder.DECODE_DONE
}
}
override fun decodeBoolean(): Boolean {
/*
* We prohibit non true/false boolean literals at all as it is considered way too error-prone,
* but allow quoted literal in relaxed mode for booleans.
*/
return if (configuration.isLenient) {
lexer.consumeBooleanLenient()
} else {
lexer.consumeBoolean()
}
}
/*
* The rest of the primitives are allowed to be quoted and unquoted
* to simplify integrations with third-party API.
*/
override fun decodeByte(): Byte {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toByte().toLong()) lexer.fail("Failed to parse byte for input '$value'")
return value.toByte()
}
override fun decodeShort(): Short {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toShort().toLong()) lexer.fail("Failed to parse short for input '$value'")
return value.toShort()
}
override fun decodeInt(): Int {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toInt().toLong()) lexer.fail("Failed to parse int for input '$value'")
return value.toInt()
}
override fun decodeLong(): Long {
return lexer.consumeNumericLiteral()
}
override fun decodeFloat(): Float {
val result = lexer.parseString("float") { toFloat() }
val specialFp = json.configuration.allowSpecialFloatingPointValues
if (specialFp || result.isFinite()) return result
lexer.throwInvalidFloatingPointDecoded(result)
}
override fun decodeDouble(): Double {
val result = lexer.parseString("double") { toDouble() }
val specialFp = json.configuration.allowSpecialFloatingPointValues
if (specialFp || result.isFinite()) return result
lexer.throwInvalidFloatingPointDecoded(result)
}
override fun decodeChar(): Char {
val string = lexer.consumeStringLenient()
if (string.length != 1) lexer.fail("Expected single char, but got '$string'")
return string[0]
}
private fun decodeStringKey(): String {
return if (configuration.isLenient) {
lexer.consumeStringLenientNotNull()
} else {
lexer.consumeKeyString()
}
}
override fun decodeString(): String {
return if (configuration.isLenient) {
lexer.consumeStringLenientNotNull()
} else {
lexer.consumeString()
}
}
override fun decodeInline(descriptor: SerialDescriptor): Decoder =
if (descriptor.isUnsignedNumber) JsonDecoderForUnsignedTypes(lexer, json)
else super.decodeInline(descriptor)
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int {
return enumDescriptor.getJsonNameIndexOrThrow(json, decodeString(), " at path " + lexer.path.getPath())
}
}
@OptIn(ExperimentalSerializationApi::class)
@ExperimentalUnsignedTypes
internal class JsonDecoderForUnsignedTypes(
private val lexer: AbstractJsonLexer,
json: Json
) : AbstractDecoder() {
override val serializersModule: SerializersModule = json.serializersModule
override fun decodeElementIndex(descriptor: SerialDescriptor): Int = error("unsupported")
override fun decodeInt(): Int = lexer.parseString("UInt") { toUInt().toInt() }
override fun decodeLong(): Long = lexer.parseString("ULong") { toULong().toLong() }
override fun decodeByte(): Byte = lexer.parseString("UByte") { toUByte().toByte() }
override fun decodeShort(): Short = lexer.parseString("UShort") { toUShort().toShort() }
}
private inline fun <T> AbstractJsonLexer.parseString(expectedType: String, block: String.() -> T): T {
val input = consumeStringLenient()
try {
return input.block()
} catch (e: IllegalArgumentException) {
fail("Failed to parse type '$expectedType' for input '$input'")
}
}