-
Notifications
You must be signed in to change notification settings - Fork 620
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add a way to reorder elements during encoding
- Loading branch information
Showing
2 changed files
with
318 additions
and
0 deletions.
There are no files selected for viewing
246 changes: 246 additions & 0 deletions
246
core/commonMain/src/kotlinx/serialization/encoding/ReorderingCompositeEncoder.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,246 @@ | ||
/* | ||
* Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package kotlinx.serialization.encoding | ||
|
||
import kotlinx.serialization.* | ||
import kotlinx.serialization.descriptors.* | ||
import kotlinx.serialization.modules.* | ||
|
||
|
||
/** | ||
* Encodes composite elements in a specific order managed by [mapElementIndex]. | ||
* | ||
* This encoder will replicate the behavior of a standard encoding, but calling the `encode*Element` methods in | ||
* the order defined by [mapElementIndex]. It first buffers each `encode*Element` calls in an array following | ||
* the given indexes using [mapElementIndex], then when [endStructure] is called, it encodes the buffered calls | ||
* in the expected order by replaying the previous calls on the given [compositeEncoderDelegate]. | ||
* | ||
* @param compositeEncoderDelegate the [CompositeEncoder] to be used to encode the given descriptor's elements in the expected order. | ||
* @param structureDescriptor descriptor of the structure being encoded and reordered | ||
* @param mapElementIndex maps the element index to a new positional zero-based index. If this mapper provides the same index for multiple elements, only the last one will be encoded as the previous ones will be overridden. The mapped index just helps to reorder the elements, but the reordered `encode*Element` method calls will still pass the original element index. | ||
*/ | ||
@ExperimentalSerializationApi | ||
internal class ReorderingCompositeEncoder( | ||
structureDescriptor: SerialDescriptor, | ||
private val compositeEncoderDelegate: CompositeEncoder, | ||
private val mapElementIndex: (SerialDescriptor, Int) -> Int, | ||
) : CompositeEncoder { | ||
private var bufferedCalls = Array<BufferedCall?>(structureDescriptor.elementsCount) { null } | ||
|
||
override val serializersModule: SerializersModule | ||
// No need to return a serializers module as it's not used during buffering | ||
get() = EmptySerializersModule() | ||
|
||
private data class BufferedCall( | ||
val originalElementIndex: Int, | ||
val encoder: () -> Unit, | ||
) | ||
|
||
private fun bufferEncoding( | ||
descriptor: SerialDescriptor, | ||
index: Int, | ||
encoder: () -> Unit | ||
) { | ||
bufferedCalls[mapElementIndex(descriptor, index)] = BufferedCall(index, encoder) | ||
} | ||
|
||
override fun endStructure(descriptor: SerialDescriptor) { | ||
encodeBufferedFields(descriptor) | ||
} | ||
|
||
private fun encodeBufferedFields(descriptor: SerialDescriptor) { | ||
bufferedCalls.filterNotNull().forEach { fieldToEncode -> | ||
fieldToEncode.encoder() | ||
} | ||
compositeEncoderDelegate.endStructure(descriptor) | ||
} | ||
|
||
override fun encodeBooleanElement(descriptor: SerialDescriptor, index: Int, value: Boolean) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeBooleanElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeByteElement(descriptor: SerialDescriptor, index: Int, value: Byte) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeByteElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeCharElement(descriptor: SerialDescriptor, index: Int, value: Char) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeCharElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeDoubleElement(descriptor: SerialDescriptor, index: Int, value: Double) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeDoubleElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeFloatElement(descriptor: SerialDescriptor, index: Int, value: Float) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeFloatElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeIntElement(descriptor: SerialDescriptor, index: Int, value: Int) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeIntElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeLongElement(descriptor: SerialDescriptor, index: Int, value: Long) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeLongElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun <T : Any> encodeNullableSerializableElement( | ||
descriptor: SerialDescriptor, | ||
index: Int, | ||
serializer: SerializationStrategy<T>, | ||
value: T? | ||
) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeNullableSerializableElement(descriptor, index, serializer, value) | ||
} | ||
} | ||
|
||
override fun <T> encodeSerializableElement( | ||
descriptor: SerialDescriptor, | ||
index: Int, | ||
serializer: SerializationStrategy<T>, | ||
value: T | ||
) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeSerializableElement(descriptor, index, serializer, value) | ||
} | ||
} | ||
|
||
override fun encodeShortElement(descriptor: SerialDescriptor, index: Int, value: Short) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeShortElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeStringElement(descriptor: SerialDescriptor, index: Int, value: String) { | ||
bufferEncoding(descriptor, index) { | ||
compositeEncoderDelegate.encodeStringElement(descriptor, index, value) | ||
} | ||
} | ||
|
||
override fun encodeInlineElement(descriptor: SerialDescriptor, index: Int): Encoder { | ||
return BufferingInlineEncoder(descriptor, index) | ||
} | ||
|
||
override fun shouldEncodeElementDefault(descriptor: SerialDescriptor, index: Int): Boolean { | ||
return compositeEncoderDelegate.shouldEncodeElementDefault(descriptor, index) | ||
} | ||
|
||
private inner class BufferingInlineEncoder( | ||
private val descriptor: SerialDescriptor, | ||
private val elementIndex: Int, | ||
) : Encoder { | ||
private var encodeNotNullMarkCalled = false | ||
|
||
override val serializersModule: SerializersModule | ||
get() = this@ReorderingCompositeEncoder.serializersModule | ||
|
||
private fun bufferEncoding(encoder: Encoder.() -> Unit) { | ||
bufferEncoding(descriptor, elementIndex) { | ||
compositeEncoderDelegate.encodeInlineElement(descriptor, elementIndex).apply { | ||
if (encodeNotNullMarkCalled) { | ||
encodeNotNullMark() | ||
} | ||
encoder() | ||
} | ||
} | ||
} | ||
|
||
override fun encodeNotNullMark() { | ||
encodeNotNullMarkCalled = true | ||
} | ||
|
||
override fun <T : Any> encodeNullableSerializableValue(serializer: SerializationStrategy<T>, value: T?) { | ||
bufferEncoding { encodeNullableSerializableValue(serializer, value) } | ||
} | ||
|
||
override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) { | ||
bufferEncoding { encodeSerializableValue(serializer, value) } | ||
} | ||
|
||
override fun encodeBoolean(value: Boolean) { | ||
bufferEncoding { encodeBoolean(value) } | ||
} | ||
|
||
override fun encodeByte(value: Byte) { | ||
bufferEncoding { encodeByte(value) } | ||
} | ||
|
||
override fun encodeChar(value: Char) { | ||
bufferEncoding { encodeChar(value) } | ||
} | ||
|
||
override fun encodeDouble(value: Double) { | ||
bufferEncoding { encodeDouble(value) } | ||
} | ||
|
||
override fun encodeEnum(enumDescriptor: SerialDescriptor, index: Int) { | ||
bufferEncoding { encodeEnum(enumDescriptor, index) } | ||
} | ||
|
||
override fun encodeFloat(value: Float) { | ||
bufferEncoding { encodeFloat(value) } | ||
} | ||
|
||
override fun encodeInt(value: Int) { | ||
bufferEncoding { encodeInt(value) } | ||
} | ||
|
||
override fun encodeLong(value: Long) { | ||
bufferEncoding { encodeLong(value) } | ||
} | ||
|
||
@ExperimentalSerializationApi | ||
override fun encodeNull() { | ||
bufferEncoding { encodeNull() } | ||
} | ||
|
||
override fun encodeShort(value: Short) { | ||
bufferEncoding { encodeShort(value) } | ||
} | ||
|
||
override fun encodeString(value: String) { | ||
bufferEncoding { encodeString(value) } | ||
} | ||
|
||
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { | ||
invalidCall("beginStructure") | ||
} | ||
|
||
override fun encodeInline(descriptor: SerialDescriptor): Encoder { | ||
invalidCall("encodeInline") | ||
} | ||
|
||
private fun invalidCall(methodName: String): Nothing { | ||
// This method is normally called by encodeSerializableValue or encodeNullableSerializableValue that is buffered, so we should never go here during buffering as it will be delegated to the concrete CompositeEncoder | ||
throw UnsupportedOperationException("$methodName should not be called when reordering fields, as it should be done by encodeSerializableValue or encodeNullableSerializableValue") | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Encodes the [structureDescriptor] elements in a specific order provided by [elementIndexMapper]. | ||
* | ||
* @param structureDescriptor descriptor of the structure being encoded and reordered | ||
* @param elementIndexMapper maps the element index to a new positional zero-based index. If this mapper provides the same index for multiple elements, only the last one will be encoded as the previous ones will be overridden. The mapped index just helps to reorder the elements, but the reordered `encode*Element` method calls will still pass the original element index. | ||
*/ | ||
@ExperimentalSerializationApi | ||
public fun CompositeEncoder.encodeReorderingElements( | ||
structureDescriptor: SerialDescriptor, | ||
elementIndexMapper: (SerialDescriptor, Int) -> Int, | ||
): CompositeEncoder = ReorderingCompositeEncoder(structureDescriptor, this, elementIndexMapper) |
72 changes: 72 additions & 0 deletions
72
core/commonTest/src/kotlinx/serialization/encoding/ReorderingCompositeEncoderTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
/* | ||
* Copyright 2017-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. | ||
*/ | ||
|
||
package kotlinx.serialization.encoding | ||
|
||
import kotlinx.serialization.* | ||
import kotlinx.serialization.descriptors.* | ||
import kotlinx.serialization.modules.* | ||
import kotlin.jvm.* | ||
import kotlin.test.* | ||
|
||
class ReorderingCompositeEncoderTest { | ||
@Test | ||
fun shouldReorderWell() { | ||
val first = 42 | ||
val second = "string" | ||
val third = true | ||
val value = OuterToBeReordered(Middle(Inner(second, third)), first) | ||
|
||
val encoder = ReorderingEncoder().apply { | ||
encodeSerializableValue(OuterToBeReordered.serializer(), value) | ||
} | ||
|
||
assertContentEquals(actual = encoder.encodedValues, expected = listOf(first, second, third)) | ||
} | ||
|
||
private class ReorderingEncoder( | ||
val encodedValues: MutableList<Any?> = mutableListOf() | ||
) : AbstractEncoder() { | ||
override val serializersModule: SerializersModule | ||
get() = EmptySerializersModule() | ||
|
||
override fun encodeValue(value: Any) { | ||
encodedValues.add(value) | ||
} | ||
|
||
override fun encodeNull() { | ||
encodedValues.add(null) | ||
} | ||
|
||
override fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder { | ||
return BasicCompositeEncoder().encodeReorderingElements(descriptor) { _, index -> | ||
// invert fields | ||
if (index == 0) 1 else 0 | ||
} | ||
} | ||
|
||
private inner class BasicCompositeEncoder : AbstractEncoder() { | ||
override val serializersModule: SerializersModule | ||
get() = EmptySerializersModule() | ||
|
||
override fun encodeValue(value: Any) { | ||
encodedValues.add(value) | ||
} | ||
|
||
override fun encodeNull() { | ||
encodedValues.add(null) | ||
} | ||
} | ||
} | ||
|
||
@Serializable | ||
private data class OuterToBeReordered(val a: Middle, val b: Int) | ||
|
||
@JvmInline | ||
@Serializable | ||
private value class Middle(val i: Inner) | ||
|
||
@Serializable | ||
private data class Inner(val c: String, val d: Boolean) | ||
} |