-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackedDecoder.kt
More file actions
408 lines (343 loc) · 13.1 KB
/
Copy pathPackedDecoder.kt
File metadata and controls
408 lines (343 loc) · 13.1 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
package com.eignex.kencode
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.CompositeDecoder
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.modules.EmptySerializersModule
import kotlinx.serialization.modules.SerializersModule
@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalSerializationApi::class)
class PackedDecoder(
private val input: ByteArray,
private val config: PackedConfiguration = PackedConfiguration(),
override val serializersModule: SerializersModule = EmptySerializersModule()
) : Decoder, CompositeDecoder {
internal var position: Int = 0
private var inStructure: Boolean = false
private var isCollection: Boolean = false
private lateinit var currentDescriptor: SerialDescriptor
private var currentIndex: Int = -1
private var booleanIndices: IntArray = intArrayOf()
private lateinit var booleanValues: BooleanArray
private var nullableIndices: IntArray = intArrayOf()
private lateinit var nullValues: BooleanArray
private var collectionSize = -1
private var collectionIndex = 0
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
inStructure = true
currentDescriptor = descriptor
val kind = descriptor.kind
isCollection = kind is StructureKind.LIST || kind is StructureKind.MAP
if (isCollection) {
booleanIndices = intArrayOf()
nullableIndices = intArrayOf()
return this
}
val boolIdx = (0 until descriptor.elementsCount).filter {
descriptor.getElementDescriptor(it).kind == PrimitiveKind.BOOLEAN
}
booleanIndices = boolIdx.toIntArray()
val nullableIdx = (0 until descriptor.elementsCount).filter {
descriptor.getElementDescriptor(it).isNullable
}
nullableIndices = nullableIdx.toIntArray()
val totalFlags = booleanIndices.size + nullableIndices.size
if (totalFlags == 0) {
booleanValues = BooleanArray(0)
nullValues = BooleanArray(0)
} else {
val allFlags: BooleanArray
if (totalFlags > 64) {
val (byteCount, bytesRead) = PackedUtils.decodeVarInt(
input,
position
)
position += bytesRead
allFlags = PackedUtils.unpackFlags(input, position, byteCount)
position += byteCount
} else {
val (flagsLong, bytesRead) = PackedUtils.decodeVarLong(
input,
position
)
position += bytesRead
allFlags =
PackedUtils.unpackFlagsFromLong(flagsLong, totalFlags)
}
booleanValues = BooleanArray(booleanIndices.size) { i ->
if (i < allFlags.size) allFlags[i] else false
}
val nullOffset = booleanIndices.size
nullValues = BooleanArray(nullableIndices.size) { i ->
val flagIdx = nullOffset + i
if (flagIdx < allFlags.size) allFlags[flagIdx] else false
}
}
return this
}
override fun decodeCollectionSize(descriptor: SerialDescriptor): Int {
val (size, bytesRead) = PackedUtils.decodeVarInt(input, position)
position += bytesRead
collectionSize = size
collectionIndex = 0
return size
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
if (isCollection) {
return if (collectionIndex < collectionSize) {
collectionIndex++
} else {
CompositeDecoder.DECODE_DONE
}
}
val nextIndex = currentIndex + 1
return if (nextIndex < descriptor.elementsCount) {
currentIndex = nextIndex
nextIndex
} else {
CompositeDecoder.DECODE_DONE
}
}
override fun decodeSequentially(): Boolean = true
override fun decodeBoolean(): Boolean {
if (!inStructure || isCollection) {
require(position < input.size)
return input[position++].toInt() != 0
}
return decodeBooleanElement(currentDescriptor, currentIndex)
}
override fun decodeByte(): Byte {
require(position < input.size)
return input[position++]
}
override fun decodeShort(): Short = readShortPos()
override fun decodeInt(): Int {
return if (inStructure && !isCollection) decodeIntElement(
currentDescriptor,
currentIndex
) else readIntPos()
}
override fun decodeLong(): Long {
return if (inStructure && !isCollection) decodeLongElement(
currentDescriptor,
currentIndex
) else readLongPos()
}
override fun decodeFloat(): Float =
java.lang.Float.intBitsToFloat(readIntPos())
override fun decodeDouble(): Double =
java.lang.Double.longBitsToDouble(readLongPos())
override fun decodeChar(): Char = readUtf8Char()
override fun decodeString(): String = readStringInline()
private fun readStringInline(): String {
val (len, bytesRead) = PackedUtils.decodeVarInt(input, position)
position += bytesRead
require(len >= 0 && position + len <= input.size)
val bytes = input.copyOfRange(position, position + len)
position += len
return bytes.toString(Charsets.UTF_8)
}
@ExperimentalSerializationApi
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int {
val (v, bytesRead) = PackedUtils.decodeVarInt(input, position)
position += bytesRead
return v
}
@ExperimentalSerializationApi
override fun decodeNull(): Nothing? = null
@ExperimentalSerializationApi
override fun decodeNotNullMark(): Boolean {
require(!inStructure || isCollection) {
"decodeNotNullMark cannot be called inside classes. Use decodeNullableSerializableElement instead."
}
val (flags, bytesRead) = PackedUtils.decodeVarLong(input, position)
position += bytesRead
return (flags and 1L) == 0L
}
@ExperimentalSerializationApi
override fun decodeInline(descriptor: SerialDescriptor): Decoder = this
override fun endStructure(descriptor: SerialDescriptor) {
inStructure = false
isCollection = false
currentIndex = -1
}
private fun booleanPos(index: Int): Int {
for (i in booleanIndices.indices) if (booleanIndices[i] == index) return i
return -1
}
private fun nullablePos(index: Int): Int {
for (i in nullableIndices.indices) if (nullableIndices[i] == index) return i
return -1
}
override fun decodeBooleanElement(
descriptor: SerialDescriptor,
index: Int
): Boolean {
val pos = booleanPos(index)
if (pos == -1) error("Element $index is not a boolean")
return booleanValues[pos]
}
override fun decodeByteElement(
descriptor: SerialDescriptor,
index: Int
): Byte {
require(position < input.size)
return input[position++]
}
override fun decodeShortElement(
descriptor: SerialDescriptor,
index: Int
): Short = readShortPos()
override fun decodeIntElement(
descriptor: SerialDescriptor,
index: Int
): Int {
val anns = descriptor.getElementAnnotations(index)
val hasFixedInt = anns.hasFixedInt()
val hasVarInt = anns.hasVarInt()
val hasVarUInt = anns.hasVarUInt()
val isVar = when {
hasFixedInt -> false
hasVarInt || hasVarUInt -> true
else -> config.defaultVarInt || config.defaultZigZag
}
val zigZag = when {
hasVarInt -> true
hasVarUInt || hasFixedInt -> false
else -> config.defaultZigZag
}
return if (isVar) {
val (raw, bytesRead) = PackedUtils.decodeVarInt(input, position)
position += bytesRead
if (zigZag) PackedUtils.zigZagDecodeInt(raw) else raw
} else {
readIntPos()
}
}
override fun decodeLongElement(
descriptor: SerialDescriptor,
index: Int
): Long {
val anns = descriptor.getElementAnnotations(index)
val hasFixedInt = anns.hasFixedInt()
val hasVarInt = anns.hasVarInt()
val hasVarUInt = anns.hasVarUInt()
val isVar = when {
hasFixedInt -> false
hasVarInt || hasVarUInt -> true
else -> config.defaultVarInt || config.defaultZigZag
}
val zigZag = when {
hasVarInt -> true
hasVarUInt || hasFixedInt -> false
else -> config.defaultZigZag
}
return if (isVar) {
val (raw, bytesRead) = PackedUtils.decodeVarLong(input, position)
position += bytesRead
if (zigZag) PackedUtils.zigZagDecodeLong(raw) else raw
} else {
readLongPos()
}
}
override fun decodeFloatElement(
descriptor: SerialDescriptor,
index: Int
): Float =
java.lang.Float.intBitsToFloat(readIntPos())
override fun decodeDoubleElement(
descriptor: SerialDescriptor,
index: Int
): Double =
java.lang.Double.longBitsToDouble(readLongPos())
override fun decodeCharElement(
descriptor: SerialDescriptor,
index: Int
): Char = readUtf8Char()
override fun decodeStringElement(
descriptor: SerialDescriptor,
index: Int
): String = readStringInline()
@ExperimentalSerializationApi
override fun decodeInlineElement(
descriptor: SerialDescriptor,
index: Int
): Decoder {
currentIndex = index
return this
}
override fun <T> decodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T>,
previousValue: T?
): T {
currentIndex = index
val kind = deserializer.descriptor.kind
val isInline = deserializer.descriptor.isInline
if ((kind is StructureKind.CLASS || kind is StructureKind.OBJECT || kind is StructureKind.LIST || kind is StructureKind.MAP || kind is PolymorphicKind) && !isInline) {
val subDecoder = PackedDecoder(input, config, serializersModule)
subDecoder.position = this.position
val value = deserializer.deserialize(subDecoder)
this.position = subDecoder.position
currentIndex = -1
return value
}
val value = deserializer.deserialize(this)
currentIndex = -1
return value
}
@ExperimentalSerializationApi
override fun <T : Any> decodeNullableSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T?>,
previousValue: T?
): T? {
require(!isCollection) {
"decodeNullableSerializableElement should not be called for collections."
}
val pos = nullablePos(index)
require(pos != -1) {
"Element $index is not declared as nullable in the descriptor."
}
if (nullValues[pos]) return null
return decodeSerializableElement(
descriptor,
index,
deserializer as DeserializationStrategy<T>,
previousValue
)
}
private fun readShortPos(): Short =
PackedUtils.readShort(input, position).also { position += 2 }
private fun readIntPos(): Int =
PackedUtils.readInt(input, position).also { position += 4 }
private fun readLongPos(): Long =
PackedUtils.readLong(input, position).also { position += 8 }
private fun readUtf8Char(): Char {
require(position < input.size) { "Unexpected EOF while decoding UTF-8 char" }
val b0 = input[position].toInt() and 0xFF
val (len, cp) = when {
(b0 and 0b1000_0000) == 0 -> 1 to b0
(b0 and 0b1110_0000) == 0b1100_0000 -> {
require(position + 2 <= input.size)
val b1 = input[position + 1].toInt() and 0xFF
require((b1 and 0b1100_0000) == 0b1000_0000) { "Invalid UTF-8 continuation byte" }
2 to (((b0 and 0x1F) shl 6) or (b1 and 0x3F))
}
(b0 and 0b1111_0000) == 0b1110_0000 -> {
require(position + 3 <= input.size)
val b1 = input[position + 1].toInt() and 0xFF
val b2 = input[position + 2].toInt() and 0xFF
require((b1 and 0b1100_0000) == 0b1000_0000) { "Invalid UTF-8 continuation byte" }
require((b2 and 0b1100_0000) == 0b1000_0000) { "Invalid UTF-8 continuation byte" }
3 to (((b0 and 0x0F) shl 12) or ((b1 and 0x3F) shl 6) or (b2 and 0x3F))
}
else -> throw IllegalArgumentException("Invalid UTF-8 start byte")
}
position += len
return cp.toChar()
}
}